code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_test_crc32.h * * Include file for SDL test framework. * * This code is a part of the SDL2_test library, not the main SDL library. */ /* Implements CRC32 calculations (default output is Perl String::CRC32 compatible). */ #ifndef SDL_test_crc32_h_ #define SDL_test_crc32_h_ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* ------------ Definitions --------- */ /* Definition shared by all CRC routines */ #ifndef CrcUint32 #define CrcUint32 unsigned int #endif #ifndef CrcUint8 #define CrcUint8 unsigned char #endif #ifdef ORIGINAL_METHOD #define CRC32_POLY 0x04c11db7 /* AUTODIN II, Ethernet, & FDDI */ #else #define CRC32_POLY 0xEDB88320 /* Perl String::CRC32 compatible */ #endif /** * Data structure for CRC32 (checksum) computation */ typedef struct { CrcUint32 crc32_table[256]; /* CRC table */ } SDLTest_Crc32Context; /* ---------- Function Prototypes ------------- */ /** * \brief Initialize the CRC context * * Note: The function initializes the crc table required for all crc calculations. * * \param crcContext pointer to context variable * * \returns 0 for OK, -1 on error * */ int SDLTest_Crc32Init(SDLTest_Crc32Context * crcContext); /** * \brief calculate a crc32 from a data block * * \param crcContext pointer to context variable * \param inBuf input buffer to checksum * \param inLen length of input buffer * \param crc32 pointer to Uint32 to store the final CRC into * * \returns 0 for OK, -1 on error * */ int SDLTest_Crc32Calc(SDLTest_Crc32Context * crcContext, CrcUint8 *inBuf, CrcUint32 inLen, CrcUint32 *crc32); /* Same routine broken down into three steps */ int SDLTest_Crc32CalcStart(SDLTest_Crc32Context * crcContext, CrcUint32 *crc32); int SDLTest_Crc32CalcEnd(SDLTest_Crc32Context * crcContext, CrcUint32 *crc32); int SDLTest_Crc32CalcBuffer(SDLTest_Crc32Context * crcContext, CrcUint8 *inBuf, CrcUint32 inLen, CrcUint32 *crc32); /** * \brief clean up CRC context * * \param crcContext pointer to context variable * * \returns 0 for OK, -1 on error * */ int SDLTest_Crc32Done(SDLTest_Crc32Context * crcContext); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_test_crc32_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_test_crc32.h
C
apache-2.0
3,385
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_test_font.h * * Include file for SDL test framework. * * This code is a part of the SDL2_test library, not the main SDL library. */ #ifndef SDL_test_font_h_ #define SDL_test_font_h_ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Function prototypes */ #define FONT_CHARACTER_SIZE 8 /** * \brief Draw a string in the currently set font. * * \param renderer The renderer to draw on. * \param x The X coordinate of the upper left corner of the character. * \param y The Y coordinate of the upper left corner of the character. * \param c The character to draw. * * \returns Returns 0 on success, -1 on failure. */ int SDLTest_DrawCharacter(SDL_Renderer *renderer, int x, int y, char c); /** * \brief Draw a string in the currently set font. * * \param renderer The renderer to draw on. * \param x The X coordinate of the upper left corner of the string. * \param y The Y coordinate of the upper left corner of the string. * \param s The string to draw. * * \returns Returns 0 on success, -1 on failure. */ int SDLTest_DrawString(SDL_Renderer *renderer, int x, int y, const char *s); /** * \brief Cleanup textures used by font drawing functions. */ void SDLTest_CleanupTextDrawing(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_test_font_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_test_font.h
C
apache-2.0
2,439
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_test_fuzzer.h * * Include file for SDL test framework. * * This code is a part of the SDL2_test library, not the main SDL library. */ /* Data generators for fuzzing test data in a reproducible way. */ #ifndef SDL_test_fuzzer_h_ #define SDL_test_fuzzer_h_ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Based on GSOC code by Markus Kauppila <markus.kauppila@gmail.com> */ /** * \file * Note: The fuzzer implementation uses a static instance of random context * internally which makes it thread-UNsafe. */ /** * Initializes the fuzzer for a test * * \param execKey Execution "Key" that initializes the random number generator uniquely for the test. * */ void SDLTest_FuzzerInit(Uint64 execKey); /** * Returns a random Uint8 * * \returns Generated integer */ Uint8 SDLTest_RandomUint8(void); /** * Returns a random Sint8 * * \returns Generated signed integer */ Sint8 SDLTest_RandomSint8(void); /** * Returns a random Uint16 * * \returns Generated integer */ Uint16 SDLTest_RandomUint16(void); /** * Returns a random Sint16 * * \returns Generated signed integer */ Sint16 SDLTest_RandomSint16(void); /** * Returns a random integer * * \returns Generated integer */ Sint32 SDLTest_RandomSint32(void); /** * Returns a random positive integer * * \returns Generated integer */ Uint32 SDLTest_RandomUint32(void); /** * Returns random Uint64. * * \returns Generated integer */ Uint64 SDLTest_RandomUint64(void); /** * Returns random Sint64. * * \returns Generated signed integer */ Sint64 SDLTest_RandomSint64(void); /** * \returns random float in range [0.0 - 1.0[ */ float SDLTest_RandomUnitFloat(void); /** * \returns random double in range [0.0 - 1.0[ */ double SDLTest_RandomUnitDouble(void); /** * \returns random float. * */ float SDLTest_RandomFloat(void); /** * \returns random double. * */ double SDLTest_RandomDouble(void); /** * Returns a random boundary value for Uint8 within the given boundaries. * Boundaries are inclusive, see the usage examples below. If validDomain * is true, the function will only return valid boundaries, otherwise non-valid * boundaries are also possible. * If boundary1 > boundary2, the values are swapped * * Usage examples: * RandomUint8BoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 * RandomUint8BoundaryValue(1, 20, SDL_FALSE) returns 0 or 21 * RandomUint8BoundaryValue(0, 99, SDL_FALSE) returns 100 * RandomUint8BoundaryValue(0, 255, SDL_FALSE) returns 0 (error set) * * \param boundary1 Lower boundary limit * \param boundary2 Upper boundary limit * \param validDomain Should the generated boundary be valid (=within the bounds) or not? * * \returns Random boundary value for the given range and domain or 0 with error set */ Uint8 SDLTest_RandomUint8BoundaryValue(Uint8 boundary1, Uint8 boundary2, SDL_bool validDomain); /** * Returns a random boundary value for Uint16 within the given boundaries. * Boundaries are inclusive, see the usage examples below. If validDomain * is true, the function will only return valid boundaries, otherwise non-valid * boundaries are also possible. * If boundary1 > boundary2, the values are swapped * * Usage examples: * RandomUint16BoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 * RandomUint16BoundaryValue(1, 20, SDL_FALSE) returns 0 or 21 * RandomUint16BoundaryValue(0, 99, SDL_FALSE) returns 100 * RandomUint16BoundaryValue(0, 0xFFFF, SDL_FALSE) returns 0 (error set) * * \param boundary1 Lower boundary limit * \param boundary2 Upper boundary limit * \param validDomain Should the generated boundary be valid (=within the bounds) or not? * * \returns Random boundary value for the given range and domain or 0 with error set */ Uint16 SDLTest_RandomUint16BoundaryValue(Uint16 boundary1, Uint16 boundary2, SDL_bool validDomain); /** * Returns a random boundary value for Uint32 within the given boundaries. * Boundaries are inclusive, see the usage examples below. If validDomain * is true, the function will only return valid boundaries, otherwise non-valid * boundaries are also possible. * If boundary1 > boundary2, the values are swapped * * Usage examples: * RandomUint32BoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 * RandomUint32BoundaryValue(1, 20, SDL_FALSE) returns 0 or 21 * RandomUint32BoundaryValue(0, 99, SDL_FALSE) returns 100 * RandomUint32BoundaryValue(0, 0xFFFFFFFF, SDL_FALSE) returns 0 (with error set) * * \param boundary1 Lower boundary limit * \param boundary2 Upper boundary limit * \param validDomain Should the generated boundary be valid (=within the bounds) or not? * * \returns Random boundary value for the given range and domain or 0 with error set */ Uint32 SDLTest_RandomUint32BoundaryValue(Uint32 boundary1, Uint32 boundary2, SDL_bool validDomain); /** * Returns a random boundary value for Uint64 within the given boundaries. * Boundaries are inclusive, see the usage examples below. If validDomain * is true, the function will only return valid boundaries, otherwise non-valid * boundaries are also possible. * If boundary1 > boundary2, the values are swapped * * Usage examples: * RandomUint64BoundaryValue(10, 20, SDL_TRUE) returns 10, 11, 19 or 20 * RandomUint64BoundaryValue(1, 20, SDL_FALSE) returns 0 or 21 * RandomUint64BoundaryValue(0, 99, SDL_FALSE) returns 100 * RandomUint64BoundaryValue(0, 0xFFFFFFFFFFFFFFFF, SDL_FALSE) returns 0 (with error set) * * \param boundary1 Lower boundary limit * \param boundary2 Upper boundary limit * \param validDomain Should the generated boundary be valid (=within the bounds) or not? * * \returns Random boundary value for the given range and domain or 0 with error set */ Uint64 SDLTest_RandomUint64BoundaryValue(Uint64 boundary1, Uint64 boundary2, SDL_bool validDomain); /** * Returns a random boundary value for Sint8 within the given boundaries. * Boundaries are inclusive, see the usage examples below. If validDomain * is true, the function will only return valid boundaries, otherwise non-valid * boundaries are also possible. * If boundary1 > boundary2, the values are swapped * * Usage examples: * RandomSint8BoundaryValue(-10, 20, SDL_TRUE) returns -11, -10, 19 or 20 * RandomSint8BoundaryValue(-100, -10, SDL_FALSE) returns -101 or -9 * RandomSint8BoundaryValue(SINT8_MIN, 99, SDL_FALSE) returns 100 * RandomSint8BoundaryValue(SINT8_MIN, SINT8_MAX, SDL_FALSE) returns SINT8_MIN (== error value) with error set * * \param boundary1 Lower boundary limit * \param boundary2 Upper boundary limit * \param validDomain Should the generated boundary be valid (=within the bounds) or not? * * \returns Random boundary value for the given range and domain or SINT8_MIN with error set */ Sint8 SDLTest_RandomSint8BoundaryValue(Sint8 boundary1, Sint8 boundary2, SDL_bool validDomain); /** * Returns a random boundary value for Sint16 within the given boundaries. * Boundaries are inclusive, see the usage examples below. If validDomain * is true, the function will only return valid boundaries, otherwise non-valid * boundaries are also possible. * If boundary1 > boundary2, the values are swapped * * Usage examples: * RandomSint16BoundaryValue(-10, 20, SDL_TRUE) returns -11, -10, 19 or 20 * RandomSint16BoundaryValue(-100, -10, SDL_FALSE) returns -101 or -9 * RandomSint16BoundaryValue(SINT16_MIN, 99, SDL_FALSE) returns 100 * RandomSint16BoundaryValue(SINT16_MIN, SINT16_MAX, SDL_FALSE) returns SINT16_MIN (== error value) with error set * * \param boundary1 Lower boundary limit * \param boundary2 Upper boundary limit * \param validDomain Should the generated boundary be valid (=within the bounds) or not? * * \returns Random boundary value for the given range and domain or SINT16_MIN with error set */ Sint16 SDLTest_RandomSint16BoundaryValue(Sint16 boundary1, Sint16 boundary2, SDL_bool validDomain); /** * Returns a random boundary value for Sint32 within the given boundaries. * Boundaries are inclusive, see the usage examples below. If validDomain * is true, the function will only return valid boundaries, otherwise non-valid * boundaries are also possible. * If boundary1 > boundary2, the values are swapped * * Usage examples: * RandomSint32BoundaryValue(-10, 20, SDL_TRUE) returns -11, -10, 19 or 20 * RandomSint32BoundaryValue(-100, -10, SDL_FALSE) returns -101 or -9 * RandomSint32BoundaryValue(SINT32_MIN, 99, SDL_FALSE) returns 100 * RandomSint32BoundaryValue(SINT32_MIN, SINT32_MAX, SDL_FALSE) returns SINT32_MIN (== error value) * * \param boundary1 Lower boundary limit * \param boundary2 Upper boundary limit * \param validDomain Should the generated boundary be valid (=within the bounds) or not? * * \returns Random boundary value for the given range and domain or SINT32_MIN with error set */ Sint32 SDLTest_RandomSint32BoundaryValue(Sint32 boundary1, Sint32 boundary2, SDL_bool validDomain); /** * Returns a random boundary value for Sint64 within the given boundaries. * Boundaries are inclusive, see the usage examples below. If validDomain * is true, the function will only return valid boundaries, otherwise non-valid * boundaries are also possible. * If boundary1 > boundary2, the values are swapped * * Usage examples: * RandomSint64BoundaryValue(-10, 20, SDL_TRUE) returns -11, -10, 19 or 20 * RandomSint64BoundaryValue(-100, -10, SDL_FALSE) returns -101 or -9 * RandomSint64BoundaryValue(SINT64_MIN, 99, SDL_FALSE) returns 100 * RandomSint64BoundaryValue(SINT64_MIN, SINT64_MAX, SDL_FALSE) returns SINT64_MIN (== error value) and error set * * \param boundary1 Lower boundary limit * \param boundary2 Upper boundary limit * \param validDomain Should the generated boundary be valid (=within the bounds) or not? * * \returns Random boundary value for the given range and domain or SINT64_MIN with error set */ Sint64 SDLTest_RandomSint64BoundaryValue(Sint64 boundary1, Sint64 boundary2, SDL_bool validDomain); /** * Returns integer in range [min, max] (inclusive). * Min and max values can be negative values. * If Max in smaller than min, then the values are swapped. * Min and max are the same value, that value will be returned. * * \param min Minimum inclusive value of returned random number * \param max Maximum inclusive value of returned random number * * \returns Generated random integer in range */ Sint32 SDLTest_RandomIntegerInRange(Sint32 min, Sint32 max); /** * Generates random null-terminated string. The minimum length for * the string is 1 character, maximum length for the string is 255 * characters and it can contain ASCII characters from 32 to 126. * * Note: Returned string needs to be deallocated. * * \returns Newly allocated random string; or NULL if length was invalid or string could not be allocated. */ char * SDLTest_RandomAsciiString(void); /** * Generates random null-terminated string. The maximum length for * the string is defined by the maxLength parameter. * String can contain ASCII characters from 32 to 126. * * Note: Returned string needs to be deallocated. * * \param maxLength The maximum length of the generated string. * * \returns Newly allocated random string; or NULL if maxLength was invalid or string could not be allocated. */ char * SDLTest_RandomAsciiStringWithMaximumLength(int maxLength); /** * Generates random null-terminated string. The length for * the string is defined by the size parameter. * String can contain ASCII characters from 32 to 126. * * Note: Returned string needs to be deallocated. * * \param size The length of the generated string * * \returns Newly allocated random string; or NULL if size was invalid or string could not be allocated. */ char * SDLTest_RandomAsciiStringOfSize(int size); /** * Returns the invocation count for the fuzzer since last ...FuzzerInit. */ int SDLTest_GetFuzzerInvocationCount(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_test_fuzzer_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_test_fuzzer.h
C
apache-2.0
13,122
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_test_harness.h * * Include file for SDL test framework. * * This code is a part of the SDL2_test library, not the main SDL library. */ /* Defines types for test case definitions and the test execution harness API. Based on original GSOC code by Markus Kauppila <markus.kauppila@gmail.com> */ #ifndef SDL_test_h_arness_h #define SDL_test_h_arness_h #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* ! Definitions for test case structures */ #define TEST_ENABLED 1 #define TEST_DISABLED 0 /* ! Definition of all the possible test return values of the test case method */ #define TEST_ABORTED -1 #define TEST_STARTED 0 #define TEST_COMPLETED 1 #define TEST_SKIPPED 2 /* ! Definition of all the possible test results for the harness */ #define TEST_RESULT_PASSED 0 #define TEST_RESULT_FAILED 1 #define TEST_RESULT_NO_ASSERT 2 #define TEST_RESULT_SKIPPED 3 #define TEST_RESULT_SETUP_FAILURE 4 /* !< Function pointer to a test case setup function (run before every test) */ typedef void (*SDLTest_TestCaseSetUpFp)(void *arg); /* !< Function pointer to a test case function */ typedef int (*SDLTest_TestCaseFp)(void *arg); /* !< Function pointer to a test case teardown function (run after every test) */ typedef void (*SDLTest_TestCaseTearDownFp)(void *arg); /** * Holds information about a single test case. */ typedef struct SDLTest_TestCaseReference { /* !< Func2Stress */ SDLTest_TestCaseFp testCase; /* !< Short name (or function name) "Func2Stress" */ char *name; /* !< Long name or full description "This test pushes func2() to the limit." */ char *description; /* !< Set to TEST_ENABLED or TEST_DISABLED (test won't be run) */ int enabled; } SDLTest_TestCaseReference; /** * Holds information about a test suite (multiple test cases). */ typedef struct SDLTest_TestSuiteReference { /* !< "PlatformSuite" */ char *name; /* !< The function that is run before each test. NULL skips. */ SDLTest_TestCaseSetUpFp testSetUp; /* !< The test cases that are run as part of the suite. Last item should be NULL. */ const SDLTest_TestCaseReference **testCases; /* !< The function that is run after each test. NULL skips. */ SDLTest_TestCaseTearDownFp testTearDown; } SDLTest_TestSuiteReference; /** * \brief Generates a random run seed string for the harness. The generated seed will contain alphanumeric characters (0-9A-Z). * * Note: The returned string needs to be deallocated by the caller. * * \param length The length of the seed string to generate * * \returns The generated seed string */ char *SDLTest_GenerateRunSeed(const int length); /** * \brief Execute a test suite using the given run seed and execution key. * * \param testSuites Suites containing the test case. * \param userRunSeed Custom run seed provided by user, or NULL to autogenerate one. * \param userExecKey Custom execution key provided by user, or 0 to autogenerate one. * \param filter Filter specification. NULL disables. Case sensitive. * \param testIterations Number of iterations to run each test case. * * \returns Test run result; 0 when all tests passed, 1 if any tests failed. */ int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *userRunSeed, Uint64 userExecKey, const char *filter, int testIterations); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_test_h_arness_h */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_test_harness.h
C
apache-2.0
4,612
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_test_images.h * * Include file for SDL test framework. * * This code is a part of the SDL2_test library, not the main SDL library. */ /* Defines some images for tests. */ #ifndef SDL_test_images_h_ #define SDL_test_images_h_ #include "SDL.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** *Type for test images. */ typedef struct SDLTest_SurfaceImage_s { int width; int height; unsigned int bytes_per_pixel; /* 3:RGB, 4:RGBA */ const char *pixel_data; } SDLTest_SurfaceImage_t; /* Test images */ SDL_Surface *SDLTest_ImageBlit(void); SDL_Surface *SDLTest_ImageBlitColor(void); SDL_Surface *SDLTest_ImageBlitAlpha(void); SDL_Surface *SDLTest_ImageBlitBlendAdd(void); SDL_Surface *SDLTest_ImageBlitBlend(void); SDL_Surface *SDLTest_ImageBlitBlendMod(void); SDL_Surface *SDLTest_ImageBlitBlendNone(void); SDL_Surface *SDLTest_ImageBlitBlendAll(void); SDL_Surface *SDLTest_ImageFace(void); SDL_Surface *SDLTest_ImagePrimitives(void); SDL_Surface *SDLTest_ImagePrimitivesBlend(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_test_images_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_test_images.h
C
apache-2.0
2,215
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_test_log.h * * Include file for SDL test framework. * * This code is a part of the SDL2_test library, not the main SDL library. */ /* * * Wrapper to log in the TEST category * */ #ifndef SDL_test_log_h_ #define SDL_test_log_h_ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * \brief Prints given message with a timestamp in the TEST category and INFO priority. * * \param fmt Message to be logged */ void SDLTest_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1); /** * \brief Prints given message with a timestamp in the TEST category and the ERROR priority. * * \param fmt Message to be logged */ void SDLTest_LogError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) SDL_PRINTF_VARARG_FUNC(1); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_test_log_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_test_log.h
C
apache-2.0
1,954
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_test_md5.h * * Include file for SDL test framework. * * This code is a part of the SDL2_test library, not the main SDL library. */ /* *********************************************************************** ** Header file for implementation of MD5 ** ** RSA Data Security, Inc. MD5 Message-Digest Algorithm ** ** Created: 2/17/90 RLR ** ** Revised: 12/27/90 SRD,AJ,BSK,JT Reference C version ** ** Revised (for MD5): RLR 4/27/91 ** ** -- G modified to have y&~z instead of y&z ** ** -- FF, GG, HH modified to add in last register done ** ** -- Access pattern: round 2 works mod 5, round 3 works mod 3 ** ** -- distinct additive constant for each step ** ** -- round 4 added, working mod 7 ** *********************************************************************** */ /* *********************************************************************** ** Message-digest routines: ** ** To form the message digest for a message M ** ** (1) Initialize a context buffer mdContext using MD5Init ** ** (2) Call MD5Update on mdContext and M ** ** (3) Call MD5Final on mdContext ** ** The message digest is now in mdContext->digest[0...15] ** *********************************************************************** */ #ifndef SDL_test_md5_h_ #define SDL_test_md5_h_ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* ------------ Definitions --------- */ /* typedef a 32-bit type */ typedef unsigned long int MD5UINT4; /* Data structure for MD5 (Message-Digest) computation */ typedef struct { MD5UINT4 i[2]; /* number of _bits_ handled mod 2^64 */ MD5UINT4 buf[4]; /* scratch buffer */ unsigned char in[64]; /* input buffer */ unsigned char digest[16]; /* actual digest after Md5Final call */ } SDLTest_Md5Context; /* ---------- Function Prototypes ------------- */ /** * \brief initialize the context * * \param mdContext pointer to context variable * * Note: The function initializes the message-digest context * mdContext. Call before each new use of the context - * all fields are set to zero. */ void SDLTest_Md5Init(SDLTest_Md5Context * mdContext); /** * \brief update digest from variable length data * * \param mdContext pointer to context variable * \param inBuf pointer to data array/string * \param inLen length of data array/string * * Note: The function updates the message-digest context to account * for the presence of each of the characters inBuf[0..inLen-1] * in the message whose digest is being computed. */ void SDLTest_Md5Update(SDLTest_Md5Context * mdContext, unsigned char *inBuf, unsigned int inLen); /** * \brief complete digest computation * * \param mdContext pointer to context variable * * Note: The function terminates the message-digest computation and * ends with the desired message digest in mdContext.digest[0..15]. * Always call before using the digest[] variable. */ void SDLTest_Md5Final(SDLTest_Md5Context * mdContext); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_test_md5_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_test_md5.h
C
apache-2.0
4,630
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_test_memory.h * * Include file for SDL test framework. * * This code is a part of the SDL2_test library, not the main SDL library. */ #ifndef SDL_test_memory_h_ #define SDL_test_memory_h_ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * \brief Start tracking SDL memory allocations * * \note This should be called before any other SDL functions for complete tracking coverage */ int SDLTest_TrackAllocations(void); /** * \brief Print a log of any outstanding allocations * * \note This can be called after SDL_Quit() */ void SDLTest_LogAllocations(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_test_memory_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_test_memory.h
C
apache-2.0
1,787
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_test_random.h * * Include file for SDL test framework. * * This code is a part of the SDL2_test library, not the main SDL library. */ /* A "32-bit Multiply with carry random number generator. Very fast. Includes a list of recommended multipliers. multiply-with-carry generator: x(n) = a*x(n-1) + carry mod 2^32. period: (a*2^31)-1 */ #ifndef SDL_test_random_h_ #define SDL_test_random_h_ #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* --- Definitions */ /* * Macros that return a random number in a specific format. */ #define SDLTest_RandomInt(c) ((int)SDLTest_Random(c)) /* * Context structure for the random number generator state. */ typedef struct { unsigned int a; unsigned int x; unsigned int c; unsigned int ah; unsigned int al; } SDLTest_RandomContext; /* --- Function prototypes */ /** * \brief Initialize random number generator with two integers. * * Note: The random sequence of numbers returned by ...Random() is the * same for the same two integers and has a period of 2^31. * * \param rndContext pointer to context structure * \param xi integer that defines the random sequence * \param ci integer that defines the random sequence * */ void SDLTest_RandomInit(SDLTest_RandomContext * rndContext, unsigned int xi, unsigned int ci); /** * \brief Initialize random number generator based on current system time. * * \param rndContext pointer to context structure * */ void SDLTest_RandomInitTime(SDLTest_RandomContext *rndContext); /** * \brief Initialize random number generator based on current system time. * * Note: ...RandomInit() or ...RandomInitTime() must have been called * before using this function. * * \param rndContext pointer to context structure * * \returns A random number (32bit unsigned integer) * */ unsigned int SDLTest_Random(SDLTest_RandomContext *rndContext); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_test_random_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_test_random.h
C
apache-2.0
3,156
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ #ifndef SDL_thread_h_ #define SDL_thread_h_ /** * \file SDL_thread.h * * Header for the SDL thread management routines. */ #include "SDL_stdinc.h" #include "SDL_error.h" /* Thread synchronization primitives */ #include "SDL_atomic.h" #include "SDL_mutex.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* The SDL thread structure, defined in SDL_thread.c */ struct SDL_Thread; typedef struct SDL_Thread SDL_Thread; /* The SDL thread ID */ typedef unsigned long SDL_threadID; /* Thread local storage ID, 0 is the invalid ID */ typedef unsigned int SDL_TLSID; /** * The SDL thread priority. * * SDL will make system changes as necessary in order to apply the thread priority. * Code which attempts to control thread state related to priority should be aware * that calling SDL_SetThreadPriority may alter such state. * SDL_HINT_THREAD_PRIORITY_POLICY can be used to control aspects of this behavior. * * \note On many systems you require special privileges to set high or time critical priority. */ typedef enum { SDL_THREAD_PRIORITY_LOW, SDL_THREAD_PRIORITY_NORMAL, SDL_THREAD_PRIORITY_HIGH, SDL_THREAD_PRIORITY_TIME_CRITICAL } SDL_ThreadPriority; /** * The function passed to SDL_CreateThread(). * It is passed a void* user context parameter and returns an int. */ typedef int (SDLCALL * SDL_ThreadFunction) (void *data); #if defined(__WIN32__) /** * \file SDL_thread.h * * We compile SDL into a DLL. This means, that it's the DLL which * creates a new thread for the calling process with the SDL_CreateThread() * API. There is a problem with this, that only the RTL of the SDL2.DLL will * be initialized for those threads, and not the RTL of the calling * application! * * To solve this, we make a little hack here. * * We'll always use the caller's _beginthread() and _endthread() APIs to * start a new thread. This way, if it's the SDL2.DLL which uses this API, * then the RTL of SDL2.DLL will be used to create the new thread, and if it's * the application, then the RTL of the application will be used. * * So, in short: * Always use the _beginthread() and _endthread() of the calling runtime * library! */ #define SDL_PASSED_BEGINTHREAD_ENDTHREAD #include <process.h> /* _beginthreadex() and _endthreadex() */ typedef uintptr_t (__cdecl * pfnSDL_CurrentBeginThread) (void *, unsigned, unsigned (__stdcall *func)(void *), void * /*arg*/, unsigned, unsigned * /* threadID */); typedef void (__cdecl * pfnSDL_CurrentEndThread) (unsigned code); #ifndef SDL_beginthread #define SDL_beginthread _beginthreadex #endif #ifndef SDL_endthread #define SDL_endthread _endthreadex #endif /** * Create a thread. */ extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThreadWithStackSize(int (SDLCALL * fn) (void *), const char *name, const size_t stacksize, void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); /** * Create a thread. */ #if defined(SDL_CreateThread) && SDL_DYNAMIC_API #undef SDL_CreateThread #define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #undef SDL_CreateThreadWithStackSize #define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize_REAL(fn, name, stacksize, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #else #define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize(fn, name, data, (pfnSDL_CurrentBeginThread)_beginthreadex, (pfnSDL_CurrentEndThread)SDL_endthread) #endif #elif defined(__OS2__) /* * just like the windows case above: We compile SDL2 * into a dll with Watcom's runtime statically linked. */ #define SDL_PASSED_BEGINTHREAD_ENDTHREAD #ifndef __EMX__ #include <process.h> #else #include <stdlib.h> #endif typedef int (*pfnSDL_CurrentBeginThread)(void (*func)(void *), void *, unsigned, void * /*arg*/); typedef void (*pfnSDL_CurrentEndThread)(void); #ifndef SDL_beginthread #define SDL_beginthread _beginthread #endif #ifndef SDL_endthread #define SDL_endthread _endthread #endif extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, const size_t stacksize, void *data, pfnSDL_CurrentBeginThread pfnBeginThread, pfnSDL_CurrentEndThread pfnEndThread); #if defined(SDL_CreateThread) && SDL_DYNAMIC_API #undef SDL_CreateThread #define SDL_CreateThread(fn, name, data) SDL_CreateThread_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #undef SDL_CreateThreadWithStackSize #define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize_REAL(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #else #define SDL_CreateThread(fn, name, data) SDL_CreateThread(fn, name, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #define SDL_CreateThreadWithStackSize(fn, name, stacksize, data) SDL_CreateThreadWithStackSize(fn, name, stacksize, data, (pfnSDL_CurrentBeginThread)SDL_beginthread, (pfnSDL_CurrentEndThread)SDL_endthread) #endif #else /** * Create a thread with a default stack size. * * This is equivalent to calling: * SDL_CreateThreadWithStackSize(fn, name, 0, data); */ extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThread(SDL_ThreadFunction fn, const char *name, void *data); /** * Create a thread. * * Thread naming is a little complicated: Most systems have very small * limits for the string length (Haiku has 32 bytes, Linux currently has 16, * Visual C++ 6.0 has nine!), and possibly other arbitrary rules. You'll * have to see what happens with your system's debugger. The name should be * UTF-8 (but using the naming limits of C identifiers is a better bet). * There are no requirements for thread naming conventions, so long as the * string is null-terminated UTF-8, but these guidelines are helpful in * choosing a name: * * http://stackoverflow.com/questions/149932/naming-conventions-for-threads * * If a system imposes requirements, SDL will try to munge the string for * it (truncate, etc), but the original string contents will be available * from SDL_GetThreadName(). * * The size (in bytes) of the new stack can be specified. Zero means "use * the system default" which might be wildly different between platforms * (x86 Linux generally defaults to eight megabytes, an embedded device * might be a few kilobytes instead). * * In SDL 2.1, stacksize will be folded into the original SDL_CreateThread * function. */ extern DECLSPEC SDL_Thread *SDLCALL SDL_CreateThreadWithStackSize(SDL_ThreadFunction fn, const char *name, const size_t stacksize, void *data); #endif /** * Get the thread name, as it was specified in SDL_CreateThread(). * This function returns a pointer to a UTF-8 string that names the * specified thread, or NULL if it doesn't have a name. This is internal * memory, not to be free()'d by the caller, and remains valid until the * specified thread is cleaned up by SDL_WaitThread(). */ extern DECLSPEC const char *SDLCALL SDL_GetThreadName(SDL_Thread *thread); /** * Get the thread identifier for the current thread. */ extern DECLSPEC SDL_threadID SDLCALL SDL_ThreadID(void); /** * Get the thread identifier for the specified thread. * * Equivalent to SDL_ThreadID() if the specified thread is NULL. */ extern DECLSPEC SDL_threadID SDLCALL SDL_GetThreadID(SDL_Thread * thread); /** * Set the priority for the current thread */ extern DECLSPEC int SDLCALL SDL_SetThreadPriority(SDL_ThreadPriority priority); /** * Wait for a thread to finish. Threads that haven't been detached will * remain (as a "zombie") until this function cleans them up. Not doing so * is a resource leak. * * Once a thread has been cleaned up through this function, the SDL_Thread * that references it becomes invalid and should not be referenced again. * As such, only one thread may call SDL_WaitThread() on another. * * The return code for the thread function is placed in the area * pointed to by \c status, if \c status is not NULL. * * You may not wait on a thread that has been used in a call to * SDL_DetachThread(). Use either that function or this one, but not * both, or behavior is undefined. * * It is safe to pass NULL to this function; it is a no-op. */ extern DECLSPEC void SDLCALL SDL_WaitThread(SDL_Thread * thread, int *status); /** * A thread may be "detached" to signify that it should not remain until * another thread has called SDL_WaitThread() on it. Detaching a thread * is useful for long-running threads that nothing needs to synchronize * with or further manage. When a detached thread is done, it simply * goes away. * * There is no way to recover the return code of a detached thread. If you * need this, don't detach the thread and instead use SDL_WaitThread(). * * Once a thread is detached, you should usually assume the SDL_Thread isn't * safe to reference again, as it will become invalid immediately upon * the detached thread's exit, instead of remaining until someone has called * SDL_WaitThread() to finally clean it up. As such, don't detach the same * thread more than once. * * If a thread has already exited when passed to SDL_DetachThread(), it will * stop waiting for a call to SDL_WaitThread() and clean up immediately. * It is not safe to detach a thread that might be used with SDL_WaitThread(). * * You may not call SDL_WaitThread() on a thread that has been detached. * Use either that function or this one, but not both, or behavior is * undefined. * * It is safe to pass NULL to this function; it is a no-op. */ extern DECLSPEC void SDLCALL SDL_DetachThread(SDL_Thread * thread); /** * \brief Create an identifier that is globally visible to all threads but refers to data that is thread-specific. * * \return The newly created thread local storage identifier, or 0 on error * * \code * static SDL_SpinLock tls_lock; * static SDL_TLSID thread_local_storage; * * void SetMyThreadData(void *value) * { * if (!thread_local_storage) { * SDL_AtomicLock(&tls_lock); * if (!thread_local_storage) { * thread_local_storage = SDL_TLSCreate(); * } * SDL_AtomicUnlock(&tls_lock); * } * SDL_TLSSet(thread_local_storage, value, 0); * } * * void *GetMyThreadData(void) * { * return SDL_TLSGet(thread_local_storage); * } * \endcode * * \sa SDL_TLSGet() * \sa SDL_TLSSet() */ extern DECLSPEC SDL_TLSID SDLCALL SDL_TLSCreate(void); /** * \brief Get the value associated with a thread local storage ID for the current thread. * * \param id The thread local storage ID * * \return The value associated with the ID for the current thread, or NULL if no value has been set. * * \sa SDL_TLSCreate() * \sa SDL_TLSSet() */ extern DECLSPEC void * SDLCALL SDL_TLSGet(SDL_TLSID id); /** * \brief Set the value associated with a thread local storage ID for the current thread. * * \param id The thread local storage ID * \param value The value to associate with the ID for the current thread * \param destructor A function called when the thread exits, to free the value. * * \return 0 on success, -1 on error * * \sa SDL_TLSCreate() * \sa SDL_TLSGet() */ extern DECLSPEC int SDLCALL SDL_TLSSet(SDL_TLSID id, const void *value, void (SDLCALL *destructor)(void*)); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_thread_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_thread.h
C
apache-2.0
13,574
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ #ifndef SDL_timer_h_ #define SDL_timer_h_ /** * \file SDL_timer.h * * Header for the SDL time management routines. */ #include "SDL_stdinc.h" #include "SDL_error.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif #ifdef __ALIOS__ #include "posix/timer.h" #endif /** * \brief Get the number of milliseconds since the SDL library initialization. * * \note This value wraps if the program runs for more than ~49 days. */ extern DECLSPEC Uint32 SDLCALL SDL_GetTicks(void); /** * \brief Compare SDL ticks values, and return true if A has passed B * * e.g. if you want to wait 100 ms, you could do this: * Uint32 timeout = SDL_GetTicks() + 100; * while (!SDL_TICKS_PASSED(SDL_GetTicks(), timeout)) { * ... do work until timeout has elapsed * } */ #define SDL_TICKS_PASSED(A, B) ((Sint32)((B) - (A)) <= 0) /** * \brief Get the current value of the high resolution counter */ extern DECLSPEC Uint64 SDLCALL SDL_GetPerformanceCounter(void); /** * \brief Get the count per second of the high resolution counter */ extern DECLSPEC Uint64 SDLCALL SDL_GetPerformanceFrequency(void); /** * \brief Wait a specified number of milliseconds before returning. */ extern DECLSPEC void SDLCALL SDL_Delay(Uint32 ms); /** * Function prototype for the timer callback function. * * The callback function is passed the current timer interval and returns * the next timer interval. If the returned value is the same as the one * passed in, the periodic alarm continues, otherwise a new alarm is * scheduled. If the callback returns 0, the periodic alarm is cancelled. */ typedef Uint32 (SDLCALL * SDL_TimerCallback) (Uint32 interval, void *param); /** * Definition of the timer ID type. */ typedef int SDL_TimerID; /** * \brief Add a new timer to the pool of timers already running. * * \return A timer ID, or 0 when an error occurs. */ extern DECLSPEC SDL_TimerID SDLCALL SDL_AddTimer(Uint32 interval, SDL_TimerCallback callback, void *param); /** * \brief Remove a timer knowing its ID. * * \return A boolean value indicating success or failure. * * \warning It is not safe to remove a timer multiple times. */ extern DECLSPEC SDL_bool SDLCALL SDL_RemoveTimer(SDL_TimerID id); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_timer_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_timer.h
C
apache-2.0
3,503
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_touch.h * * Include file for SDL touch event handling. */ #ifndef SDL_touch_h_ #define SDL_touch_h_ #include "SDL_stdinc.h" #include "SDL_error.h" #include "SDL_video.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif typedef Sint64 SDL_TouchID; typedef Sint64 SDL_FingerID; typedef enum { SDL_TOUCH_DEVICE_INVALID = -1, SDL_TOUCH_DEVICE_DIRECT, /* touch screen with window-relative coordinates */ SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE, /* trackpad with absolute device coordinates */ SDL_TOUCH_DEVICE_INDIRECT_RELATIVE /* trackpad with screen cursor-relative coordinates */ } SDL_TouchDeviceType; typedef struct SDL_Finger { SDL_FingerID id; float x; float y; float pressure; } SDL_Finger; /* Used as the device ID for mouse events simulated with touch input */ #define SDL_TOUCH_MOUSEID ((Uint32)-1) /* Used as the SDL_TouchID for touch events simulated with mouse input */ #define SDL_MOUSE_TOUCHID ((Sint64)-1) /* Function prototypes */ /** * \brief Get the number of registered touch devices. */ extern DECLSPEC int SDLCALL SDL_GetNumTouchDevices(void); /** * \brief Get the touch ID with the given index, or 0 if the index is invalid. */ extern DECLSPEC SDL_TouchID SDLCALL SDL_GetTouchDevice(int index); /** * \brief Get the type of the given touch device. */ extern DECLSPEC SDL_TouchDeviceType SDLCALL SDL_GetTouchDeviceType(SDL_TouchID touchID); /** * \brief Get the number of active fingers for a given touch device. */ extern DECLSPEC int SDLCALL SDL_GetNumTouchFingers(SDL_TouchID touchID); /** * \brief Get the finger object of the given touch, with the given index. */ extern DECLSPEC SDL_Finger * SDLCALL SDL_GetTouchFinger(SDL_TouchID touchID, int index); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_touch_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_touch.h
C
apache-2.0
2,946
/* SDL_ttf: A companion library to SDL for working with TrueType (tm) fonts Copyright (C) 2001-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. */ /* This library is a wrapper around the excellent FreeType 2.0 library, available at: http://www.freetype.org/ */ /* Note: In many places, SDL_ttf will say "glyph" when it means "code point." Unicode is hard, we learn as we go, and we apologize for adding to the confusion. */ #ifndef SDL_TTF_H_ #define SDL_TTF_H_ #include "SDL.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL */ #define SDL_TTF_MAJOR_VERSION 2 #define SDL_TTF_MINOR_VERSION 0 #define SDL_TTF_PATCHLEVEL 14 /* This macro can be used to fill a version structure with the compile-time * version of the SDL_ttf library. */ #define SDL_TTF_VERSION(X) \ { \ (X)->major = SDL_TTF_MAJOR_VERSION; \ (X)->minor = SDL_TTF_MINOR_VERSION; \ (X)->patch = SDL_TTF_PATCHLEVEL; \ } /* Backwards compatibility */ #define TTF_MAJOR_VERSION SDL_TTF_MAJOR_VERSION #define TTF_MINOR_VERSION SDL_TTF_MINOR_VERSION #define TTF_PATCHLEVEL SDL_TTF_PATCHLEVEL #define TTF_VERSION(X) SDL_TTF_VERSION(X) /** * This is the version number macro for the current SDL_net version. */ #define SDL_TTF_COMPILEDVERSION \ SDL_VERSIONNUM(SDL_TTF_MAJOR_VERSION, SDL_TTF_MINOR_VERSION, SDL_TTF_PATCHLEVEL) /** * This macro will evaluate to true if compiled with SDL_net at least X.Y.Z. */ #define SDL_TTF_VERSION_ATLEAST(X, Y, Z) \ (SDL_TTF_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z)) /* Make sure this is defined (only available in newer SDL versions) */ #ifndef SDL_DEPRECATED #define SDL_DEPRECATED #endif /* This function gets the version of the dynamically linked SDL_ttf library. it should NOT be used to fill a version structure, instead you should use the SDL_TTF_VERSION() macro. */ extern DECLSPEC const SDL_version * SDLCALL TTF_Linked_Version(void); /* ZERO WIDTH NO-BREAKSPACE (Unicode byte order mark) */ #define UNICODE_BOM_NATIVE 0xFEFF #define UNICODE_BOM_SWAPPED 0xFFFE /* This function tells the library whether UNICODE text is generally byteswapped. A UNICODE BOM character in a string will override this setting for the remainder of that string. */ extern DECLSPEC void SDLCALL TTF_ByteSwappedUNICODE(int swapped); /* The internal structure containing font information */ typedef struct _TTF_Font TTF_Font; /* Initialize the TTF engine - returns 0 if successful, -1 on error */ extern DECLSPEC int SDLCALL TTF_Init(void); /* Open a font file and create a font of the specified point size. * Some .fon fonts will have several sizes embedded in the file, so the * point size becomes the index of choosing which size. If the value * is too high, the last indexed size will be the default. */ extern DECLSPEC TTF_Font * SDLCALL TTF_OpenFont(const char *file, int ptsize); extern DECLSPEC TTF_Font * SDLCALL TTF_OpenFontIndex(const char *file, int ptsize, long index); extern DECLSPEC TTF_Font * SDLCALL TTF_OpenFontRW(SDL_RWops *src, int freesrc, int ptsize); extern DECLSPEC TTF_Font * SDLCALL TTF_OpenFontIndexRW(SDL_RWops *src, int freesrc, int ptsize, long index); /* Set and retrieve the font style */ #define TTF_STYLE_NORMAL 0x00 #define TTF_STYLE_BOLD 0x01 #define TTF_STYLE_ITALIC 0x02 #define TTF_STYLE_UNDERLINE 0x04 #define TTF_STYLE_STRIKETHROUGH 0x08 extern DECLSPEC int SDLCALL TTF_GetFontStyle(const TTF_Font *font); extern DECLSPEC void SDLCALL TTF_SetFontStyle(TTF_Font *font, int style); extern DECLSPEC int SDLCALL TTF_GetFontOutline(const TTF_Font *font); extern DECLSPEC void SDLCALL TTF_SetFontOutline(TTF_Font *font, int outline); /* Set and retrieve FreeType hinter settings */ #define TTF_HINTING_NORMAL 0 #define TTF_HINTING_LIGHT 1 #define TTF_HINTING_MONO 2 #define TTF_HINTING_NONE 3 extern DECLSPEC int SDLCALL TTF_GetFontHinting(const TTF_Font *font); extern DECLSPEC void SDLCALL TTF_SetFontHinting(TTF_Font *font, int hinting); /* Get the total height of the font - usually equal to point size */ extern DECLSPEC int SDLCALL TTF_FontHeight(const TTF_Font *font); /* Get the offset from the baseline to the top of the font This is a positive value, relative to the baseline. */ extern DECLSPEC int SDLCALL TTF_FontAscent(const TTF_Font *font); /* Get the offset from the baseline to the bottom of the font This is a negative value, relative to the baseline. */ extern DECLSPEC int SDLCALL TTF_FontDescent(const TTF_Font *font); /* Get the recommended spacing between lines of text for this font */ extern DECLSPEC int SDLCALL TTF_FontLineSkip(const TTF_Font *font); /* Get/Set whether or not kerning is allowed for this font */ extern DECLSPEC int SDLCALL TTF_GetFontKerning(const TTF_Font *font); extern DECLSPEC void SDLCALL TTF_SetFontKerning(TTF_Font *font, int allowed); /* Get the number of faces of the font */ extern DECLSPEC long SDLCALL TTF_FontFaces(const TTF_Font *font); /* Get the font face attributes, if any */ extern DECLSPEC int SDLCALL TTF_FontFaceIsFixedWidth(const TTF_Font *font); extern DECLSPEC char * SDLCALL TTF_FontFaceFamilyName(const TTF_Font *font); extern DECLSPEC char * SDLCALL TTF_FontFaceStyleName(const TTF_Font *font); /* Check wether a glyph is provided by the font or not */ extern DECLSPEC int SDLCALL TTF_GlyphIsProvided(const TTF_Font *font, Uint16 ch); /* Get the metrics (dimensions) of a glyph To understand what these metrics mean, here is a useful link: http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html */ extern DECLSPEC int SDLCALL TTF_GlyphMetrics(TTF_Font *font, Uint16 ch, int *minx, int *maxx, int *miny, int *maxy, int *advance); /* Get the dimensions of a rendered string of text */ extern DECLSPEC int SDLCALL TTF_SizeText(TTF_Font *font, const char *text, int *w, int *h); extern DECLSPEC int SDLCALL TTF_SizeUTF8(TTF_Font *font, const char *text, int *w, int *h); extern DECLSPEC int SDLCALL TTF_SizeUNICODE(TTF_Font *font, const Uint16 *text, int *w, int *h); /* Create an 8-bit palettized surface and render the given text at fast quality with the given font and color. The 0 pixel is the colorkey, giving a transparent background, and the 1 pixel is set to the text color. This function returns the new surface, or NULL if there was an error. */ extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderText_Solid(TTF_Font *font, const char *text, SDL_Color fg); extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderUTF8_Solid(TTF_Font *font, const char *text, SDL_Color fg); extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderUNICODE_Solid(TTF_Font *font, const Uint16 *text, SDL_Color fg); /* Create an 8-bit palettized surface and render the given glyph at fast quality with the given font and color. The 0 pixel is the colorkey, giving a transparent background, and the 1 pixel is set to the text color. The glyph is rendered without any padding or centering in the X direction, and aligned normally in the Y direction. This function returns the new surface, or NULL if there was an error. */ extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderGlyph_Solid(TTF_Font *font, Uint16 ch, SDL_Color fg); /* Create an 8-bit palettized surface and render the given text at high quality with the given font and colors. The 0 pixel is background, while other pixels have varying degrees of the foreground color. This function returns the new surface, or NULL if there was an error. */ extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderText_Shaded(TTF_Font *font, const char *text, SDL_Color fg, SDL_Color bg); extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderUTF8_Shaded(TTF_Font *font, const char *text, SDL_Color fg, SDL_Color bg); extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderUNICODE_Shaded(TTF_Font *font, const Uint16 *text, SDL_Color fg, SDL_Color bg); /* Create an 8-bit palettized surface and render the given glyph at high quality with the given font and colors. The 0 pixel is background, while other pixels have varying degrees of the foreground color. The glyph is rendered without any padding or centering in the X direction, and aligned normally in the Y direction. This function returns the new surface, or NULL if there was an error. */ extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderGlyph_Shaded(TTF_Font *font, Uint16 ch, SDL_Color fg, SDL_Color bg); /* Create a 32-bit ARGB surface and render the given text at high quality, using alpha blending to dither the font with the given color. This function returns the new surface, or NULL if there was an error. */ extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderText_Blended(TTF_Font *font, const char *text, SDL_Color fg); extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderUTF8_Blended(TTF_Font *font, const char *text, SDL_Color fg); extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderUNICODE_Blended(TTF_Font *font, const Uint16 *text, SDL_Color fg); /* Create a 32-bit ARGB surface and render the given text at high quality, using alpha blending to dither the font with the given color. Text is wrapped to multiple lines on line endings and on word boundaries if it extends beyond wrapLength in pixels. This function returns the new surface, or NULL if there was an error. */ extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderText_Blended_Wrapped(TTF_Font *font, const char *text, SDL_Color fg, Uint32 wrapLength); extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderUTF8_Blended_Wrapped(TTF_Font *font, const char *text, SDL_Color fg, Uint32 wrapLength); extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderUNICODE_Blended_Wrapped(TTF_Font *font, const Uint16 *text, SDL_Color fg, Uint32 wrapLength); /* Create a 32-bit ARGB surface and render the given glyph at high quality, using alpha blending to dither the font with the given color. The glyph is rendered without any padding or centering in the X direction, and aligned normally in the Y direction. This function returns the new surface, or NULL if there was an error. */ extern DECLSPEC SDL_Surface * SDLCALL TTF_RenderGlyph_Blended(TTF_Font *font, Uint16 ch, SDL_Color fg); /* For compatibility with previous versions, here are the old functions */ #define TTF_RenderText(font, text, fg, bg) \ TTF_RenderText_Shaded(font, text, fg, bg) #define TTF_RenderUTF8(font, text, fg, bg) \ TTF_RenderUTF8_Shaded(font, text, fg, bg) #define TTF_RenderUNICODE(font, text, fg, bg) \ TTF_RenderUNICODE_Shaded(font, text, fg, bg) /* Close an opened font file */ extern DECLSPEC void SDLCALL TTF_CloseFont(TTF_Font *font); /* De-initialize the TTF engine */ extern DECLSPEC void SDLCALL TTF_Quit(void); /* Check if the TTF engine is initialized */ extern DECLSPEC int SDLCALL TTF_WasInit(void); /* Get the kerning size of two glyphs indices */ /* DEPRECATED: this function requires FreeType font indexes, not glyphs, by accident, which we don't expose through this API, so it could give wildly incorrect results, especially with non-ASCII values. Going forward, please use TTF_GetFontKerningSizeGlyphs() instead, which does what you probably expected this function to do. */ extern DECLSPEC int TTF_GetFontKerningSize(TTF_Font *font, int prev_index, int index) SDL_DEPRECATED; /* Get the kerning size of two glyphs */ extern DECLSPEC int TTF_GetFontKerningSizeGlyphs(TTF_Font *font, Uint16 previous_ch, Uint16 ch); /* We'll use SDL for reporting errors */ #define TTF_SetError SDL_SetError #define TTF_GetError SDL_GetError /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_TTF_H_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_ttf.h
C
apache-2.0
13,072
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_types.h * * \deprecated */ /* DEPRECATED */ #include "SDL_stdinc.h"
YifuLiu/AliOS-Things
components/SDL2/include/SDL_types.h
C
apache-2.0
1,031
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_version.h * * This header defines the current SDL version. */ #ifndef SDL_version_h_ #define SDL_version_h_ #include "SDL_stdinc.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * \brief Information the version of SDL in use. * * Represents the library's version as three levels: major revision * (increments with massive changes, additions, and enhancements), * minor revision (increments with backwards-compatible changes to the * major revision), and patchlevel (increments with fixes to the minor * revision). * * \sa SDL_VERSION * \sa SDL_GetVersion */ typedef struct SDL_version { Uint8 major; /**< major version */ Uint8 minor; /**< minor version */ Uint8 patch; /**< update version */ } SDL_version; /* Printable format: "%d.%d.%d", MAJOR, MINOR, PATCHLEVEL */ #define SDL_MAJOR_VERSION 2 #define SDL_MINOR_VERSION 0 #define SDL_PATCHLEVEL 13 /** * \brief Macro to determine SDL version program was compiled against. * * This macro fills in a SDL_version structure with the version of the * library you compiled against. This is determined by what header the * compiler uses. Note that if you dynamically linked the library, you might * have a slightly newer or older version at runtime. That version can be * determined with SDL_GetVersion(), which, unlike SDL_VERSION(), * is not a macro. * * \param x A pointer to a SDL_version struct to initialize. * * \sa SDL_version * \sa SDL_GetVersion */ #define SDL_VERSION(x) \ { \ (x)->major = SDL_MAJOR_VERSION; \ (x)->minor = SDL_MINOR_VERSION; \ (x)->patch = SDL_PATCHLEVEL; \ } /** * This macro turns the version numbers into a numeric value: * \verbatim (1,2,3) -> (1203) \endverbatim * * This assumes that there will never be more than 100 patchlevels. */ #define SDL_VERSIONNUM(X, Y, Z) \ ((X)*1000 + (Y)*100 + (Z)) /** * This is the version number macro for the current SDL version. */ #define SDL_COMPILEDVERSION \ SDL_VERSIONNUM(SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL) /** * This macro will evaluate to true if compiled with SDL at least X.Y.Z. */ #define SDL_VERSION_ATLEAST(X, Y, Z) \ (SDL_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z)) /** * \brief Get the version of SDL that is linked against your program. * * If you are linking to SDL dynamically, then it is possible that the * current version will be different than the version you compiled against. * This function returns the current version, while SDL_VERSION() is a * macro that tells you what version you compiled with. * * \code * SDL_version compiled; * SDL_version linked; * * SDL_VERSION(&compiled); * SDL_GetVersion(&linked); * printf("We compiled against SDL version %d.%d.%d ...\n", * compiled.major, compiled.minor, compiled.patch); * printf("But we linked against SDL version %d.%d.%d.\n", * linked.major, linked.minor, linked.patch); * \endcode * * This function may be called safely at any time, even before SDL_Init(). * * \sa SDL_VERSION */ extern DECLSPEC void SDLCALL SDL_GetVersion(SDL_version * ver); /** * \brief Get the code revision of SDL that is linked against your program. * * Returns an arbitrary string (a hash value) uniquely identifying the * exact revision of the SDL library in use, and is only useful in comparing * against other revisions. It is NOT an incrementing number. */ extern DECLSPEC const char *SDLCALL SDL_GetRevision(void); /** * \brief Get the revision number of SDL that is linked against your program. * * Returns a number uniquely identifying the exact revision of the SDL * library in use. It is an incrementing number based on commits to * hg.libsdl.org. */ extern DECLSPEC int SDLCALL SDL_GetRevisionNumber(void); /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_version_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_version.h
C
apache-2.0
5,162
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file SDL_video.h * * Header file for SDL video functions. */ #ifndef SDL_video_h_ #define SDL_video_h_ #include "SDL_stdinc.h" #include "SDL_pixels.h" #include "SDL_rect.h" #include "SDL_surface.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /** * \brief The structure that defines a display mode * * \sa SDL_GetNumDisplayModes() * \sa SDL_GetDisplayMode() * \sa SDL_GetDesktopDisplayMode() * \sa SDL_GetCurrentDisplayMode() * \sa SDL_GetClosestDisplayMode() * \sa SDL_SetWindowDisplayMode() * \sa SDL_GetWindowDisplayMode() */ typedef struct { Uint32 format; /**< pixel format */ int w; /**< width, in screen coordinates */ int h; /**< height, in screen coordinates */ int refresh_rate; /**< refresh rate (or zero for unspecified) */ void *driverdata; /**< driver-specific data, initialize to 0 */ } SDL_DisplayMode; /** * \brief The type used to identify a window * * \sa SDL_CreateWindow() * \sa SDL_CreateWindowFrom() * \sa SDL_DestroyWindow() * \sa SDL_GetWindowData() * \sa SDL_GetWindowFlags() * \sa SDL_GetWindowGrab() * \sa SDL_GetWindowPosition() * \sa SDL_GetWindowSize() * \sa SDL_GetWindowTitle() * \sa SDL_HideWindow() * \sa SDL_MaximizeWindow() * \sa SDL_MinimizeWindow() * \sa SDL_RaiseWindow() * \sa SDL_RestoreWindow() * \sa SDL_SetWindowData() * \sa SDL_SetWindowFullscreen() * \sa SDL_SetWindowGrab() * \sa SDL_SetWindowIcon() * \sa SDL_SetWindowPosition() * \sa SDL_SetWindowSize() * \sa SDL_SetWindowBordered() * \sa SDL_SetWindowResizable() * \sa SDL_SetWindowTitle() * \sa SDL_ShowWindow() */ typedef struct SDL_Window SDL_Window; /** * \brief The flags on a window * * \sa SDL_GetWindowFlags() */ typedef enum { SDL_WINDOW_FULLSCREEN = 0x00000001, /**< fullscreen window */ SDL_WINDOW_OPENGL = 0x00000002, /**< window usable with OpenGL context */ SDL_WINDOW_SHOWN = 0x00000004, /**< window is visible */ SDL_WINDOW_HIDDEN = 0x00000008, /**< window is not visible */ SDL_WINDOW_BORDERLESS = 0x00000010, /**< no window decoration */ SDL_WINDOW_RESIZABLE = 0x00000020, /**< window can be resized */ SDL_WINDOW_MINIMIZED = 0x00000040, /**< window is minimized */ SDL_WINDOW_MAXIMIZED = 0x00000080, /**< window is maximized */ SDL_WINDOW_INPUT_GRABBED = 0x00000100, /**< window has grabbed input focus */ SDL_WINDOW_INPUT_FOCUS = 0x00000200, /**< window has input focus */ SDL_WINDOW_MOUSE_FOCUS = 0x00000400, /**< window has mouse focus */ SDL_WINDOW_FULLSCREEN_DESKTOP = ( SDL_WINDOW_FULLSCREEN | 0x00001000 ), SDL_WINDOW_FOREIGN = 0x00000800, /**< window not created by SDL */ SDL_WINDOW_ALLOW_HIGHDPI = 0x00002000, /**< window should be created in high-DPI mode if supported. On macOS NSHighResolutionCapable must be set true in the application's Info.plist for this to have any effect. */ SDL_WINDOW_MOUSE_CAPTURE = 0x00004000, /**< window has mouse captured (unrelated to INPUT_GRABBED) */ SDL_WINDOW_ALWAYS_ON_TOP = 0x00008000, /**< window should always be above others */ SDL_WINDOW_SKIP_TASKBAR = 0x00010000, /**< window should not be added to the taskbar */ SDL_WINDOW_UTILITY = 0x00020000, /**< window should be treated as a utility window */ SDL_WINDOW_TOOLTIP = 0x00040000, /**< window should be treated as a tooltip */ SDL_WINDOW_POPUP_MENU = 0x00080000, /**< window should be treated as a popup menu */ SDL_WINDOW_VULKAN = 0x10000000, /**< window usable for Vulkan surface */ SDL_WINDOW_METAL = 0x20000000 /**< window usable for Metal view */ } SDL_WindowFlags; /** * \brief Used to indicate that you don't care what the window position is. */ #define SDL_WINDOWPOS_UNDEFINED_MASK 0x1FFF0000u #define SDL_WINDOWPOS_UNDEFINED_DISPLAY(X) (SDL_WINDOWPOS_UNDEFINED_MASK|(X)) #define SDL_WINDOWPOS_UNDEFINED SDL_WINDOWPOS_UNDEFINED_DISPLAY(0) #define SDL_WINDOWPOS_ISUNDEFINED(X) \ (((X)&0xFFFF0000) == SDL_WINDOWPOS_UNDEFINED_MASK) /** * \brief Used to indicate that the window position should be centered. */ #define SDL_WINDOWPOS_CENTERED_MASK 0x2FFF0000u #define SDL_WINDOWPOS_CENTERED_DISPLAY(X) (SDL_WINDOWPOS_CENTERED_MASK|(X)) #define SDL_WINDOWPOS_CENTERED SDL_WINDOWPOS_CENTERED_DISPLAY(0) #define SDL_WINDOWPOS_ISCENTERED(X) \ (((X)&0xFFFF0000) == SDL_WINDOWPOS_CENTERED_MASK) /** * \brief Event subtype for window events */ typedef enum { SDL_WINDOWEVENT_NONE, /**< Never used */ SDL_WINDOWEVENT_SHOWN, /**< Window has been shown */ SDL_WINDOWEVENT_HIDDEN, /**< Window has been hidden */ SDL_WINDOWEVENT_EXPOSED, /**< Window has been exposed and should be redrawn */ SDL_WINDOWEVENT_MOVED, /**< Window has been moved to data1, data2 */ SDL_WINDOWEVENT_RESIZED, /**< Window has been resized to data1xdata2 */ SDL_WINDOWEVENT_SIZE_CHANGED, /**< The window size has changed, either as a result of an API call or through the system or user changing the window size. */ SDL_WINDOWEVENT_MINIMIZED, /**< Window has been minimized */ SDL_WINDOWEVENT_MAXIMIZED, /**< Window has been maximized */ SDL_WINDOWEVENT_RESTORED, /**< Window has been restored to normal size and position */ SDL_WINDOWEVENT_ENTER, /**< Window has gained mouse focus */ SDL_WINDOWEVENT_LEAVE, /**< Window has lost mouse focus */ SDL_WINDOWEVENT_FOCUS_GAINED, /**< Window has gained keyboard focus */ SDL_WINDOWEVENT_FOCUS_LOST, /**< Window has lost keyboard focus */ SDL_WINDOWEVENT_CLOSE, /**< The window manager requests that the window be closed */ SDL_WINDOWEVENT_TAKE_FOCUS, /**< Window is being offered a focus (should SetWindowInputFocus() on itself or a subwindow, or ignore) */ SDL_WINDOWEVENT_HIT_TEST /**< Window had a hit test that wasn't SDL_HITTEST_NORMAL. */ } SDL_WindowEventID; /** * \brief Event subtype for display events */ typedef enum { SDL_DISPLAYEVENT_NONE, /**< Never used */ SDL_DISPLAYEVENT_ORIENTATION /**< Display orientation has changed to data1 */ } SDL_DisplayEventID; typedef enum { SDL_ORIENTATION_UNKNOWN, /**< The display orientation can't be determined */ SDL_ORIENTATION_LANDSCAPE, /**< The display is in landscape mode, with the right side up, relative to portrait mode */ SDL_ORIENTATION_LANDSCAPE_FLIPPED, /**< The display is in landscape mode, with the left side up, relative to portrait mode */ SDL_ORIENTATION_PORTRAIT, /**< The display is in portrait mode */ SDL_ORIENTATION_PORTRAIT_FLIPPED /**< The display is in portrait mode, upside down */ } SDL_DisplayOrientation; /** * \brief An opaque handle to an OpenGL context. */ typedef void *SDL_GLContext; /** * \brief OpenGL configuration attributes */ typedef enum { SDL_GL_RED_SIZE, SDL_GL_GREEN_SIZE, SDL_GL_BLUE_SIZE, SDL_GL_ALPHA_SIZE, SDL_GL_BUFFER_SIZE, SDL_GL_DOUBLEBUFFER, SDL_GL_DEPTH_SIZE, SDL_GL_STENCIL_SIZE, SDL_GL_ACCUM_RED_SIZE, SDL_GL_ACCUM_GREEN_SIZE, SDL_GL_ACCUM_BLUE_SIZE, SDL_GL_ACCUM_ALPHA_SIZE, SDL_GL_STEREO, SDL_GL_MULTISAMPLEBUFFERS, SDL_GL_MULTISAMPLESAMPLES, SDL_GL_ACCELERATED_VISUAL, SDL_GL_RETAINED_BACKING, SDL_GL_CONTEXT_MAJOR_VERSION, SDL_GL_CONTEXT_MINOR_VERSION, SDL_GL_CONTEXT_EGL, SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_SHARE_WITH_CURRENT_CONTEXT, SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, SDL_GL_CONTEXT_RELEASE_BEHAVIOR, SDL_GL_CONTEXT_RESET_NOTIFICATION, SDL_GL_CONTEXT_NO_ERROR } SDL_GLattr; typedef enum { SDL_GL_CONTEXT_PROFILE_CORE = 0x0001, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY = 0x0002, SDL_GL_CONTEXT_PROFILE_ES = 0x0004 /**< GLX_CONTEXT_ES2_PROFILE_BIT_EXT */ } SDL_GLprofile; typedef enum { SDL_GL_CONTEXT_DEBUG_FLAG = 0x0001, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG = 0x0002, SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG = 0x0004, SDL_GL_CONTEXT_RESET_ISOLATION_FLAG = 0x0008 } SDL_GLcontextFlag; typedef enum { SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE = 0x0000, SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH = 0x0001 } SDL_GLcontextReleaseFlag; typedef enum { SDL_GL_CONTEXT_RESET_NO_NOTIFICATION = 0x0000, SDL_GL_CONTEXT_RESET_LOSE_CONTEXT = 0x0001 } SDL_GLContextResetNotification; /* Function prototypes */ /** * \brief Get the number of video drivers compiled into SDL * * \sa SDL_GetVideoDriver() */ extern DECLSPEC int SDLCALL SDL_GetNumVideoDrivers(void); /** * \brief Get the name of a built in video driver. * * \note The video drivers are presented in the order in which they are * normally checked during initialization. * * \sa SDL_GetNumVideoDrivers() */ extern DECLSPEC const char *SDLCALL SDL_GetVideoDriver(int index); /** * \brief Initialize the video subsystem, optionally specifying a video driver. * * \param driver_name Initialize a specific driver by name, or NULL for the * default video driver. * * \return 0 on success, -1 on error * * This function initializes the video subsystem; setting up a connection * to the window manager, etc, and determines the available display modes * and pixel formats, but does not initialize a window or graphics mode. * * \sa SDL_VideoQuit() */ extern DECLSPEC int SDLCALL SDL_VideoInit(const char *driver_name); /** * \brief Shuts down the video subsystem. * * This function closes all windows, and restores the original video mode. * * \sa SDL_VideoInit() */ extern DECLSPEC void SDLCALL SDL_VideoQuit(void); /** * \brief Returns the name of the currently initialized video driver. * * \return The name of the current video driver or NULL if no driver * has been initialized * * \sa SDL_GetNumVideoDrivers() * \sa SDL_GetVideoDriver() */ extern DECLSPEC const char *SDLCALL SDL_GetCurrentVideoDriver(void); /** * \brief Returns the number of available video displays. * * \sa SDL_GetDisplayBounds() */ extern DECLSPEC int SDLCALL SDL_GetNumVideoDisplays(void); /** * \brief Get the name of a display in UTF-8 encoding * * \return The name of a display, or NULL for an invalid display index. * * \sa SDL_GetNumVideoDisplays() */ extern DECLSPEC const char * SDLCALL SDL_GetDisplayName(int displayIndex); /** * \brief Get the desktop area represented by a display, with the primary * display located at 0,0 * * \return 0 on success, or -1 if the index is out of range. * * \sa SDL_GetNumVideoDisplays() */ extern DECLSPEC int SDLCALL SDL_GetDisplayBounds(int displayIndex, SDL_Rect * rect); /** * \brief Get the usable desktop area represented by a display, with the * primary display located at 0,0 * * This is the same area as SDL_GetDisplayBounds() reports, but with portions * reserved by the system removed. For example, on Mac OS X, this subtracts * the area occupied by the menu bar and dock. * * Setting a window to be fullscreen generally bypasses these unusable areas, * so these are good guidelines for the maximum space available to a * non-fullscreen window. * * \return 0 on success, or -1 if the index is out of range. * * \sa SDL_GetDisplayBounds() * \sa SDL_GetNumVideoDisplays() */ extern DECLSPEC int SDLCALL SDL_GetDisplayUsableBounds(int displayIndex, SDL_Rect * rect); /** * \brief Get the dots/pixels-per-inch for a display * * \note Diagonal, horizontal and vertical DPI can all be optionally * returned if the parameter is non-NULL. * * \return 0 on success, or -1 if no DPI information is available or the index is out of range. * * \sa SDL_GetNumVideoDisplays() */ extern DECLSPEC int SDLCALL SDL_GetDisplayDPI(int displayIndex, float * ddpi, float * hdpi, float * vdpi); /** * \brief Get the orientation of a display * * \return The orientation of the display, or SDL_ORIENTATION_UNKNOWN if it isn't available. * * \sa SDL_GetNumVideoDisplays() */ extern DECLSPEC SDL_DisplayOrientation SDLCALL SDL_GetDisplayOrientation(int displayIndex); /** * \brief Returns the number of available display modes. * * \sa SDL_GetDisplayMode() */ extern DECLSPEC int SDLCALL SDL_GetNumDisplayModes(int displayIndex); /** * \brief Fill in information about a specific display mode. * * \note The display modes are sorted in this priority: * \li bits per pixel -> more colors to fewer colors * \li width -> largest to smallest * \li height -> largest to smallest * \li refresh rate -> highest to lowest * * \sa SDL_GetNumDisplayModes() */ extern DECLSPEC int SDLCALL SDL_GetDisplayMode(int displayIndex, int modeIndex, SDL_DisplayMode * mode); /** * \brief Fill in information about the desktop display mode. */ extern DECLSPEC int SDLCALL SDL_GetDesktopDisplayMode(int displayIndex, SDL_DisplayMode * mode); /** * \brief Fill in information about the current display mode. */ extern DECLSPEC int SDLCALL SDL_GetCurrentDisplayMode(int displayIndex, SDL_DisplayMode * mode); /** * \brief Get the closest match to the requested display mode. * * \param displayIndex The index of display from which mode should be queried. * \param mode The desired display mode * \param closest A pointer to a display mode to be filled in with the closest * match of the available display modes. * * \return The passed in value \c closest, or NULL if no matching video mode * was available. * * The available display modes are scanned, and \c closest is filled in with the * closest mode matching the requested mode and returned. The mode format and * refresh_rate default to the desktop mode if they are 0. The modes are * scanned with size being first priority, format being second priority, and * finally checking the refresh_rate. If all the available modes are too * small, then NULL is returned. * * \sa SDL_GetNumDisplayModes() * \sa SDL_GetDisplayMode() */ extern DECLSPEC SDL_DisplayMode * SDLCALL SDL_GetClosestDisplayMode(int displayIndex, const SDL_DisplayMode * mode, SDL_DisplayMode * closest); /** * \brief Get the display index associated with a window. * * \return the display index of the display containing the center of the * window, or -1 on error. */ extern DECLSPEC int SDLCALL SDL_GetWindowDisplayIndex(SDL_Window * window); /** * \brief Set the display mode used when a fullscreen window is visible. * * By default the window's dimensions and the desktop format and refresh rate * are used. * * \param window The window for which the display mode should be set. * \param mode The mode to use, or NULL for the default mode. * * \return 0 on success, or -1 if setting the display mode failed. * * \sa SDL_GetWindowDisplayMode() * \sa SDL_SetWindowFullscreen() */ extern DECLSPEC int SDLCALL SDL_SetWindowDisplayMode(SDL_Window * window, const SDL_DisplayMode * mode); /** * \brief Fill in information about the display mode used when a fullscreen * window is visible. * * \sa SDL_SetWindowDisplayMode() * \sa SDL_SetWindowFullscreen() */ extern DECLSPEC int SDLCALL SDL_GetWindowDisplayMode(SDL_Window * window, SDL_DisplayMode * mode); /** * \brief Get the pixel format associated with the window. */ extern DECLSPEC Uint32 SDLCALL SDL_GetWindowPixelFormat(SDL_Window * window); /** * \brief Create a window with the specified position, dimensions, and flags. * * \param title The title of the window, in UTF-8 encoding. * \param x The x position of the window, ::SDL_WINDOWPOS_CENTERED, or * ::SDL_WINDOWPOS_UNDEFINED. * \param y The y position of the window, ::SDL_WINDOWPOS_CENTERED, or * ::SDL_WINDOWPOS_UNDEFINED. * \param w The width of the window, in screen coordinates. * \param h The height of the window, in screen coordinates. * \param flags The flags for the window, a mask of any of the following: * ::SDL_WINDOW_FULLSCREEN, ::SDL_WINDOW_OPENGL, * ::SDL_WINDOW_HIDDEN, ::SDL_WINDOW_BORDERLESS, * ::SDL_WINDOW_RESIZABLE, ::SDL_WINDOW_MAXIMIZED, * ::SDL_WINDOW_MINIMIZED, ::SDL_WINDOW_INPUT_GRABBED, * ::SDL_WINDOW_ALLOW_HIGHDPI, ::SDL_WINDOW_VULKAN * ::SDL_WINDOW_METAL. * * \return The created window, or NULL if window creation failed. * * If the window is created with the SDL_WINDOW_ALLOW_HIGHDPI flag, its size * in pixels may differ from its size in screen coordinates on platforms with * high-DPI support (e.g. iOS and Mac OS X). Use SDL_GetWindowSize() to query * the client area's size in screen coordinates, and SDL_GL_GetDrawableSize(), * SDL_Vulkan_GetDrawableSize(), or SDL_GetRendererOutputSize() to query the * drawable size in pixels. * * If the window is created with any of the SDL_WINDOW_OPENGL or * SDL_WINDOW_VULKAN flags, then the corresponding LoadLibrary function * (SDL_GL_LoadLibrary or SDL_Vulkan_LoadLibrary) is called and the * corresponding UnloadLibrary function is called by SDL_DestroyWindow(). * * If SDL_WINDOW_VULKAN is specified and there isn't a working Vulkan driver, * SDL_CreateWindow() will fail because SDL_Vulkan_LoadLibrary() will fail. * * If SDL_WINDOW_METAL is specified on an OS that does not support Metal, * SDL_CreateWindow() will fail. * * \note On non-Apple devices, SDL requires you to either not link to the * Vulkan loader or link to a dynamic library version. This limitation * may be removed in a future version of SDL. * * \sa SDL_DestroyWindow() * \sa SDL_GL_LoadLibrary() * \sa SDL_Vulkan_LoadLibrary() */ extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindow(const char *title, int x, int y, int w, int h, Uint32 flags); /** * \brief Create an SDL window from an existing native window. * * \param data A pointer to driver-dependent window creation data * * \return The created window, or NULL if window creation failed. * * \sa SDL_DestroyWindow() */ extern DECLSPEC SDL_Window * SDLCALL SDL_CreateWindowFrom(const void *data); /** * \brief Get the numeric ID of a window, for logging purposes. */ extern DECLSPEC Uint32 SDLCALL SDL_GetWindowID(SDL_Window * window); /** * \brief Get a window from a stored ID, or NULL if it doesn't exist. */ extern DECLSPEC SDL_Window * SDLCALL SDL_GetWindowFromID(Uint32 id); /** * \brief Get the window flags. */ extern DECLSPEC Uint32 SDLCALL SDL_GetWindowFlags(SDL_Window * window); /** * \brief Set the title of a window, in UTF-8 format. * * \sa SDL_GetWindowTitle() */ extern DECLSPEC void SDLCALL SDL_SetWindowTitle(SDL_Window * window, const char *title); /** * \brief Get the title of a window, in UTF-8 format. * * \sa SDL_SetWindowTitle() */ extern DECLSPEC const char *SDLCALL SDL_GetWindowTitle(SDL_Window * window); /** * \brief Set the icon for a window. * * \param window The window for which the icon should be set. * \param icon The icon for the window. */ extern DECLSPEC void SDLCALL SDL_SetWindowIcon(SDL_Window * window, SDL_Surface * icon); /** * \brief Associate an arbitrary named pointer with a window. * * \param window The window to associate with the pointer. * \param name The name of the pointer. * \param userdata The associated pointer. * * \return The previous value associated with 'name' * * \note The name is case-sensitive. * * \sa SDL_GetWindowData() */ extern DECLSPEC void* SDLCALL SDL_SetWindowData(SDL_Window * window, const char *name, void *userdata); /** * \brief Retrieve the data pointer associated with a window. * * \param window The window to query. * \param name The name of the pointer. * * \return The value associated with 'name' * * \sa SDL_SetWindowData() */ extern DECLSPEC void *SDLCALL SDL_GetWindowData(SDL_Window * window, const char *name); /** * \brief Set the position of a window. * * \param window The window to reposition. * \param x The x coordinate of the window in screen coordinates, or * ::SDL_WINDOWPOS_CENTERED or ::SDL_WINDOWPOS_UNDEFINED. * \param y The y coordinate of the window in screen coordinates, or * ::SDL_WINDOWPOS_CENTERED or ::SDL_WINDOWPOS_UNDEFINED. * * \note The window coordinate origin is the upper left of the display. * * \sa SDL_GetWindowPosition() */ extern DECLSPEC void SDLCALL SDL_SetWindowPosition(SDL_Window * window, int x, int y); /** * \brief Get the position of a window. * * \param window The window to query. * \param x Pointer to variable for storing the x position, in screen * coordinates. May be NULL. * \param y Pointer to variable for storing the y position, in screen * coordinates. May be NULL. * * \sa SDL_SetWindowPosition() */ extern DECLSPEC void SDLCALL SDL_GetWindowPosition(SDL_Window * window, int *x, int *y); /** * \brief Set the size of a window's client area. * * \param window The window to resize. * \param w The width of the window, in screen coordinates. Must be >0. * \param h The height of the window, in screen coordinates. Must be >0. * * \note Fullscreen windows automatically match the size of the display mode, * and you should use SDL_SetWindowDisplayMode() to change their size. * * The window size in screen coordinates may differ from the size in pixels, if * the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a platform with * high-dpi support (e.g. iOS or OS X). Use SDL_GL_GetDrawableSize() or * SDL_GetRendererOutputSize() to get the real client area size in pixels. * * \sa SDL_GetWindowSize() * \sa SDL_SetWindowDisplayMode() */ extern DECLSPEC void SDLCALL SDL_SetWindowSize(SDL_Window * window, int w, int h); /** * \brief Get the size of a window's client area. * * \param window The window to query. * \param w Pointer to variable for storing the width, in screen * coordinates. May be NULL. * \param h Pointer to variable for storing the height, in screen * coordinates. May be NULL. * * The window size in screen coordinates may differ from the size in pixels, if * the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a platform with * high-dpi support (e.g. iOS or OS X). Use SDL_GL_GetDrawableSize() or * SDL_GetRendererOutputSize() to get the real client area size in pixels. * * \sa SDL_SetWindowSize() */ extern DECLSPEC void SDLCALL SDL_GetWindowSize(SDL_Window * window, int *w, int *h); /** * \brief Get the size of a window's borders (decorations) around the client area. * * \param window The window to query. * \param top Pointer to variable for storing the size of the top border. NULL is permitted. * \param left Pointer to variable for storing the size of the left border. NULL is permitted. * \param bottom Pointer to variable for storing the size of the bottom border. NULL is permitted. * \param right Pointer to variable for storing the size of the right border. NULL is permitted. * * \return 0 on success, or -1 if getting this information is not supported. * * \note if this function fails (returns -1), the size values will be * initialized to 0, 0, 0, 0 (if a non-NULL pointer is provided), as * if the window in question was borderless. */ extern DECLSPEC int SDLCALL SDL_GetWindowBordersSize(SDL_Window * window, int *top, int *left, int *bottom, int *right); /** * \brief Set the minimum size of a window's client area. * * \param window The window to set a new minimum size. * \param min_w The minimum width of the window, must be >0 * \param min_h The minimum height of the window, must be >0 * * \note You can't change the minimum size of a fullscreen window, it * automatically matches the size of the display mode. * * \sa SDL_GetWindowMinimumSize() * \sa SDL_SetWindowMaximumSize() */ extern DECLSPEC void SDLCALL SDL_SetWindowMinimumSize(SDL_Window * window, int min_w, int min_h); /** * \brief Get the minimum size of a window's client area. * * \param window The window to query. * \param w Pointer to variable for storing the minimum width, may be NULL * \param h Pointer to variable for storing the minimum height, may be NULL * * \sa SDL_GetWindowMaximumSize() * \sa SDL_SetWindowMinimumSize() */ extern DECLSPEC void SDLCALL SDL_GetWindowMinimumSize(SDL_Window * window, int *w, int *h); /** * \brief Set the maximum size of a window's client area. * * \param window The window to set a new maximum size. * \param max_w The maximum width of the window, must be >0 * \param max_h The maximum height of the window, must be >0 * * \note You can't change the maximum size of a fullscreen window, it * automatically matches the size of the display mode. * * \sa SDL_GetWindowMaximumSize() * \sa SDL_SetWindowMinimumSize() */ extern DECLSPEC void SDLCALL SDL_SetWindowMaximumSize(SDL_Window * window, int max_w, int max_h); /** * \brief Get the maximum size of a window's client area. * * \param window The window to query. * \param w Pointer to variable for storing the maximum width, may be NULL * \param h Pointer to variable for storing the maximum height, may be NULL * * \sa SDL_GetWindowMinimumSize() * \sa SDL_SetWindowMaximumSize() */ extern DECLSPEC void SDLCALL SDL_GetWindowMaximumSize(SDL_Window * window, int *w, int *h); /** * \brief Set the border state of a window. * * This will add or remove the window's SDL_WINDOW_BORDERLESS flag and * add or remove the border from the actual window. This is a no-op if the * window's border already matches the requested state. * * \param window The window of which to change the border state. * \param bordered SDL_FALSE to remove border, SDL_TRUE to add border. * * \note You can't change the border state of a fullscreen window. * * \sa SDL_GetWindowFlags() */ extern DECLSPEC void SDLCALL SDL_SetWindowBordered(SDL_Window * window, SDL_bool bordered); /** * \brief Set the user-resizable state of a window. * * This will add or remove the window's SDL_WINDOW_RESIZABLE flag and * allow/disallow user resizing of the window. This is a no-op if the * window's resizable state already matches the requested state. * * \param window The window of which to change the resizable state. * \param resizable SDL_TRUE to allow resizing, SDL_FALSE to disallow. * * \note You can't change the resizable state of a fullscreen window. * * \sa SDL_GetWindowFlags() */ extern DECLSPEC void SDLCALL SDL_SetWindowResizable(SDL_Window * window, SDL_bool resizable); /** * \brief Show a window. * * \sa SDL_HideWindow() */ extern DECLSPEC void SDLCALL SDL_ShowWindow(SDL_Window * window); /** * \brief Hide a window. * * \sa SDL_ShowWindow() */ extern DECLSPEC void SDLCALL SDL_HideWindow(SDL_Window * window); /** * \brief Raise a window above other windows and set the input focus. */ extern DECLSPEC void SDLCALL SDL_RaiseWindow(SDL_Window * window); /** * \brief Make a window as large as possible. * * \sa SDL_RestoreWindow() */ extern DECLSPEC void SDLCALL SDL_MaximizeWindow(SDL_Window * window); /** * \brief Minimize a window to an iconic representation. * * \sa SDL_RestoreWindow() */ extern DECLSPEC void SDLCALL SDL_MinimizeWindow(SDL_Window * window); /** * \brief Restore the size and position of a minimized or maximized window. * * \sa SDL_MaximizeWindow() * \sa SDL_MinimizeWindow() */ extern DECLSPEC void SDLCALL SDL_RestoreWindow(SDL_Window * window); /** * \brief Set a window's fullscreen state. * * \return 0 on success, or -1 if setting the display mode failed. * * \sa SDL_SetWindowDisplayMode() * \sa SDL_GetWindowDisplayMode() */ extern DECLSPEC int SDLCALL SDL_SetWindowFullscreen(SDL_Window * window, Uint32 flags); /** * \brief Get the SDL surface associated with the window. * * \return The window's framebuffer surface, or NULL on error. * * A new surface will be created with the optimal format for the window, * if necessary. This surface will be freed when the window is destroyed. * * \note You may not combine this with 3D or the rendering API on this window. * * \sa SDL_UpdateWindowSurface() * \sa SDL_UpdateWindowSurfaceRects() */ extern DECLSPEC SDL_Surface * SDLCALL SDL_GetWindowSurface(SDL_Window * window); /** * \brief Copy the window surface to the screen. * * \return 0 on success, or -1 on error. * * \sa SDL_GetWindowSurface() * \sa SDL_UpdateWindowSurfaceRects() */ extern DECLSPEC int SDLCALL SDL_UpdateWindowSurface(SDL_Window * window); /** * \brief Copy a number of rectangles on the window surface to the screen. * * \return 0 on success, or -1 on error. * * \sa SDL_GetWindowSurface() * \sa SDL_UpdateWindowSurface() */ extern DECLSPEC int SDLCALL SDL_UpdateWindowSurfaceRects(SDL_Window * window, const SDL_Rect * rects, int numrects); /** * \brief Set a window's input grab mode. * * \param window The window for which the input grab mode should be set. * \param grabbed This is SDL_TRUE to grab input, and SDL_FALSE to release input. * * If the caller enables a grab while another window is currently grabbed, * the other window loses its grab in favor of the caller's window. * * \sa SDL_GetWindowGrab() */ extern DECLSPEC void SDLCALL SDL_SetWindowGrab(SDL_Window * window, SDL_bool grabbed); /** * \brief Get a window's input grab mode. * * \return This returns SDL_TRUE if input is grabbed, and SDL_FALSE otherwise. * * \sa SDL_SetWindowGrab() */ extern DECLSPEC SDL_bool SDLCALL SDL_GetWindowGrab(SDL_Window * window); /** * \brief Get the window that currently has an input grab enabled. * * \return This returns the window if input is grabbed, and NULL otherwise. * * \sa SDL_SetWindowGrab() */ extern DECLSPEC SDL_Window * SDLCALL SDL_GetGrabbedWindow(void); /** * \brief Set the brightness (gamma correction) for a window. * * \return 0 on success, or -1 if setting the brightness isn't supported. * * \sa SDL_GetWindowBrightness() * \sa SDL_SetWindowGammaRamp() */ extern DECLSPEC int SDLCALL SDL_SetWindowBrightness(SDL_Window * window, float brightness); /** * \brief Get the brightness (gamma correction) for a window. * * \return The last brightness value passed to SDL_SetWindowBrightness() * * \sa SDL_SetWindowBrightness() */ extern DECLSPEC float SDLCALL SDL_GetWindowBrightness(SDL_Window * window); /** * \brief Set the opacity for a window * * \param window The window which will be made transparent or opaque * \param opacity Opacity (0.0f - transparent, 1.0f - opaque) This will be * clamped internally between 0.0f and 1.0f. * * \return 0 on success, or -1 if setting the opacity isn't supported. * * \sa SDL_GetWindowOpacity() */ extern DECLSPEC int SDLCALL SDL_SetWindowOpacity(SDL_Window * window, float opacity); /** * \brief Get the opacity of a window. * * If transparency isn't supported on this platform, opacity will be reported * as 1.0f without error. * * \param window The window in question. * \param out_opacity Opacity (0.0f - transparent, 1.0f - opaque) * * \return 0 on success, or -1 on error (invalid window, etc). * * \sa SDL_SetWindowOpacity() */ extern DECLSPEC int SDLCALL SDL_GetWindowOpacity(SDL_Window * window, float * out_opacity); /** * \brief Sets the window as a modal for another window (TODO: reconsider this function and/or its name) * * \param modal_window The window that should be modal * \param parent_window The parent window * * \return 0 on success, or -1 otherwise. */ extern DECLSPEC int SDLCALL SDL_SetWindowModalFor(SDL_Window * modal_window, SDL_Window * parent_window); /** * \brief Explicitly sets input focus to the window. * * You almost certainly want SDL_RaiseWindow() instead of this function. Use * this with caution, as you might give focus to a window that's completely * obscured by other windows. * * \param window The window that should get the input focus * * \return 0 on success, or -1 otherwise. * \sa SDL_RaiseWindow() */ extern DECLSPEC int SDLCALL SDL_SetWindowInputFocus(SDL_Window * window); /** * \brief Set the gamma ramp for a window. * * \param window The window for which the gamma ramp should be set. * \param red The translation table for the red channel, or NULL. * \param green The translation table for the green channel, or NULL. * \param blue The translation table for the blue channel, or NULL. * * \return 0 on success, or -1 if gamma ramps are unsupported. * * Set the gamma translation table for the red, green, and blue channels * of the video hardware. Each table is an array of 256 16-bit quantities, * representing a mapping between the input and output for that channel. * The input is the index into the array, and the output is the 16-bit * gamma value at that index, scaled to the output color precision. * * \sa SDL_GetWindowGammaRamp() */ extern DECLSPEC int SDLCALL SDL_SetWindowGammaRamp(SDL_Window * window, const Uint16 * red, const Uint16 * green, const Uint16 * blue); /** * \brief Get the gamma ramp for a window. * * \param window The window from which the gamma ramp should be queried. * \param red A pointer to a 256 element array of 16-bit quantities to hold * the translation table for the red channel, or NULL. * \param green A pointer to a 256 element array of 16-bit quantities to hold * the translation table for the green channel, or NULL. * \param blue A pointer to a 256 element array of 16-bit quantities to hold * the translation table for the blue channel, or NULL. * * \return 0 on success, or -1 if gamma ramps are unsupported. * * \sa SDL_SetWindowGammaRamp() */ extern DECLSPEC int SDLCALL SDL_GetWindowGammaRamp(SDL_Window * window, Uint16 * red, Uint16 * green, Uint16 * blue); /** * \brief Possible return values from the SDL_HitTest callback. * * \sa SDL_HitTest */ typedef enum { SDL_HITTEST_NORMAL, /**< Region is normal. No special properties. */ SDL_HITTEST_DRAGGABLE, /**< Region can drag entire window. */ SDL_HITTEST_RESIZE_TOPLEFT, SDL_HITTEST_RESIZE_TOP, SDL_HITTEST_RESIZE_TOPRIGHT, SDL_HITTEST_RESIZE_RIGHT, SDL_HITTEST_RESIZE_BOTTOMRIGHT, SDL_HITTEST_RESIZE_BOTTOM, SDL_HITTEST_RESIZE_BOTTOMLEFT, SDL_HITTEST_RESIZE_LEFT } SDL_HitTestResult; /** * \brief Callback used for hit-testing. * * \sa SDL_SetWindowHitTest */ typedef SDL_HitTestResult (SDLCALL *SDL_HitTest)(SDL_Window *win, const SDL_Point *area, void *data); /** * \brief Provide a callback that decides if a window region has special properties. * * Normally windows are dragged and resized by decorations provided by the * system window manager (a title bar, borders, etc), but for some apps, it * makes sense to drag them from somewhere else inside the window itself; for * example, one might have a borderless window that wants to be draggable * from any part, or simulate its own title bar, etc. * * This function lets the app provide a callback that designates pieces of * a given window as special. This callback is run during event processing * if we need to tell the OS to treat a region of the window specially; the * use of this callback is known as "hit testing." * * Mouse input may not be delivered to your application if it is within * a special area; the OS will often apply that input to moving the window or * resizing the window and not deliver it to the application. * * Specifying NULL for a callback disables hit-testing. Hit-testing is * disabled by default. * * Platforms that don't support this functionality will return -1 * unconditionally, even if you're attempting to disable hit-testing. * * Your callback may fire at any time, and its firing does not indicate any * specific behavior (for example, on Windows, this certainly might fire * when the OS is deciding whether to drag your window, but it fires for lots * of other reasons, too, some unrelated to anything you probably care about * _and when the mouse isn't actually at the location it is testing_). * Since this can fire at any time, you should try to keep your callback * efficient, devoid of allocations, etc. * * \param window The window to set hit-testing on. * \param callback The callback to call when doing a hit-test. * \param callback_data An app-defined void pointer passed to the callback. * \return 0 on success, -1 on error (including unsupported). */ extern DECLSPEC int SDLCALL SDL_SetWindowHitTest(SDL_Window * window, SDL_HitTest callback, void *callback_data); /** * \brief Destroy a window. */ extern DECLSPEC void SDLCALL SDL_DestroyWindow(SDL_Window * window); /** * \brief Returns whether the screensaver is currently enabled (default off). * * \sa SDL_EnableScreenSaver() * \sa SDL_DisableScreenSaver() */ extern DECLSPEC SDL_bool SDLCALL SDL_IsScreenSaverEnabled(void); /** * \brief Allow the screen to be blanked by a screensaver * * \sa SDL_IsScreenSaverEnabled() * \sa SDL_DisableScreenSaver() */ extern DECLSPEC void SDLCALL SDL_EnableScreenSaver(void); /** * \brief Prevent the screen from being blanked by a screensaver * * \sa SDL_IsScreenSaverEnabled() * \sa SDL_EnableScreenSaver() */ extern DECLSPEC void SDLCALL SDL_DisableScreenSaver(void); /** * \name OpenGL support functions */ /* @{ */ /** * \brief Dynamically load an OpenGL library. * * \param path The platform dependent OpenGL library name, or NULL to open the * default OpenGL library. * * \return 0 on success, or -1 if the library couldn't be loaded. * * This should be done after initializing the video driver, but before * creating any OpenGL windows. If no OpenGL library is loaded, the default * library will be loaded upon creation of the first OpenGL window. * * \note If you do this, you need to retrieve all of the GL functions used in * your program from the dynamic library using SDL_GL_GetProcAddress(). * * \sa SDL_GL_GetProcAddress() * \sa SDL_GL_UnloadLibrary() */ extern DECLSPEC int SDLCALL SDL_GL_LoadLibrary(const char *path); /** * \brief Get the address of an OpenGL function. */ extern DECLSPEC void *SDLCALL SDL_GL_GetProcAddress(const char *proc); /** * \brief Unload the OpenGL library previously loaded by SDL_GL_LoadLibrary(). * * \sa SDL_GL_LoadLibrary() */ extern DECLSPEC void SDLCALL SDL_GL_UnloadLibrary(void); /** * \brief Return true if an OpenGL extension is supported for the current * context. */ extern DECLSPEC SDL_bool SDLCALL SDL_GL_ExtensionSupported(const char *extension); /** * \brief Reset all previously set OpenGL context attributes to their default values */ extern DECLSPEC void SDLCALL SDL_GL_ResetAttributes(void); /** * \brief Set an OpenGL window attribute before window creation. * * \return 0 on success, or -1 if the attribute could not be set. */ extern DECLSPEC int SDLCALL SDL_GL_SetAttribute(SDL_GLattr attr, int value); /** * \brief Get the actual value for an attribute from the current context. * * \return 0 on success, or -1 if the attribute could not be retrieved. * The integer at \c value will be modified in either case. */ extern DECLSPEC int SDLCALL SDL_GL_GetAttribute(SDL_GLattr attr, int *value); /** * \brief Create an OpenGL context for use with an OpenGL window, and make it * current. * * \sa SDL_GL_DeleteContext() */ extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_CreateContext(SDL_Window * window); /** * \brief Set up an OpenGL context for rendering into an OpenGL window. * * \note The context must have been created with a compatible window. */ extern DECLSPEC int SDLCALL SDL_GL_MakeCurrent(SDL_Window * window, SDL_GLContext context); /** * \brief Get the currently active OpenGL window. */ extern DECLSPEC SDL_Window* SDLCALL SDL_GL_GetCurrentWindow(void); /** * \brief Get the currently active OpenGL context. */ extern DECLSPEC SDL_GLContext SDLCALL SDL_GL_GetCurrentContext(void); /** * \brief Get the size of a window's underlying drawable in pixels (for use * with glViewport). * * \param window Window from which the drawable size should be queried * \param w Pointer to variable for storing the width in pixels, may be NULL * \param h Pointer to variable for storing the height in pixels, may be NULL * * This may differ from SDL_GetWindowSize() if we're rendering to a high-DPI * drawable, i.e. the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a * platform with high-DPI support (Apple calls this "Retina"), and not disabled * by the SDL_HINT_VIDEO_HIGHDPI_DISABLED hint. * * \sa SDL_GetWindowSize() * \sa SDL_CreateWindow() */ extern DECLSPEC void SDLCALL SDL_GL_GetDrawableSize(SDL_Window * window, int *w, int *h); /** * \brief Set the swap interval for the current OpenGL context. * * \param interval 0 for immediate updates, 1 for updates synchronized with the * vertical retrace. If the system supports it, you may * specify -1 to allow late swaps to happen immediately * instead of waiting for the next retrace. * * \return 0 on success, or -1 if setting the swap interval is not supported. * * \sa SDL_GL_GetSwapInterval() */ extern DECLSPEC int SDLCALL SDL_GL_SetSwapInterval(int interval); /** * \brief Get the swap interval for the current OpenGL context. * * \return 0 if there is no vertical retrace synchronization, 1 if the buffer * swap is synchronized with the vertical retrace, and -1 if late * swaps happen immediately instead of waiting for the next retrace. * If the system can't determine the swap interval, or there isn't a * valid current context, this will return 0 as a safe default. * * \sa SDL_GL_SetSwapInterval() */ extern DECLSPEC int SDLCALL SDL_GL_GetSwapInterval(void); /** * \brief Swap the OpenGL buffers for a window, if double-buffering is * supported. */ extern DECLSPEC void SDLCALL SDL_GL_SwapWindow(SDL_Window * window); /** * \brief Delete an OpenGL context. * * \sa SDL_GL_CreateContext() */ extern DECLSPEC void SDLCALL SDL_GL_DeleteContext(SDL_GLContext context); /* @} *//* OpenGL support functions */ /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_video_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_video.h
C
apache-2.0
46,694
/* Simple DirectMedia Layer Copyright (C) 2017, Mark Callow 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. */ /** * \file SDL_vulkan.h * * Header file for functions to creating Vulkan surfaces on SDL windows. */ #ifndef SDL_vulkan_h_ #define SDL_vulkan_h_ #include "SDL_video.h" #include "begin_code.h" /* Set up for C function definitions, even when using C++ */ #ifdef __cplusplus extern "C" { #endif /* Avoid including vulkan.h, don't define VkInstance if it's already included */ #ifdef VULKAN_H_ #define NO_SDL_VULKAN_TYPEDEFS #endif #ifndef NO_SDL_VULKAN_TYPEDEFS #define VK_DEFINE_HANDLE(object) typedef struct object##_T* object; #if defined(__LP64__) || defined(_WIN64) || defined(__x86_64__) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(__powerpc64__) #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef struct object##_T *object; #else #define VK_DEFINE_NON_DISPATCHABLE_HANDLE(object) typedef uint64_t object; #endif VK_DEFINE_HANDLE(VkInstance) VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkSurfaceKHR) #endif /* !NO_SDL_VULKAN_TYPEDEFS */ typedef VkInstance SDL_vulkanInstance; typedef VkSurfaceKHR SDL_vulkanSurface; /* for compatibility with Tizen */ /** * \name Vulkan support functions * * \note SDL_Vulkan_GetInstanceExtensions & SDL_Vulkan_CreateSurface API * is compatable with Tizen's implementation of Vulkan in SDL. */ /* @{ */ /** * \brief Dynamically load a Vulkan loader library. * * \param [in] path The platform dependent Vulkan loader library name, or * \c NULL. * * \return \c 0 on success, or \c -1 if the library couldn't be loaded. * * If \a path is NULL SDL will use the value of the environment variable * \c SDL_VULKAN_LIBRARY, if set, otherwise it loads the default Vulkan * loader library. * * This should be called after initializing the video driver, but before * creating any Vulkan windows. If no Vulkan loader library is loaded, the * default library will be loaded upon creation of the first Vulkan window. * * \note It is fairly common for Vulkan applications to link with \a libvulkan * instead of explicitly loading it at run time. This will work with * SDL provided the application links to a dynamic library and both it * and SDL use the same search path. * * \note If you specify a non-NULL \c path, an application should retrieve all * of the Vulkan functions it uses from the dynamic library using * \c SDL_Vulkan_GetVkGetInstanceProcAddr() unless you can guarantee * \c path points to the same vulkan loader library the application * linked to. * * \note On Apple devices, if \a path is NULL, SDL will attempt to find * the vkGetInstanceProcAddr address within all the mach-o images of * the current process. This is because it is fairly common for Vulkan * applications to link with libvulkan (and historically MoltenVK was * provided as a static library). If it is not found then, on macOS, SDL * will attempt to load \c vulkan.framework/vulkan, \c libvulkan.1.dylib, * followed by \c libvulkan.dylib, in that order. * On iOS SDL will attempt to load \c libvulkan.dylib only. Applications * using a dynamic framework or .dylib must ensure it is included in its * application bundle. * * \note On non-Apple devices, application linking with a static libvulkan is * not supported. Either do not link to the Vulkan loader or link to a * dynamic library version. * * \note This function will fail if there are no working Vulkan drivers * installed. * * \sa SDL_Vulkan_GetVkGetInstanceProcAddr() * \sa SDL_Vulkan_UnloadLibrary() */ extern DECLSPEC int SDLCALL SDL_Vulkan_LoadLibrary(const char *path); /** * \brief Get the address of the \c vkGetInstanceProcAddr function. * * \note This should be called after either calling SDL_Vulkan_LoadLibrary * or creating an SDL_Window with the SDL_WINDOW_VULKAN flag. */ extern DECLSPEC void *SDLCALL SDL_Vulkan_GetVkGetInstanceProcAddr(void); /** * \brief Unload the Vulkan loader library previously loaded by * \c SDL_Vulkan_LoadLibrary(). * * \sa SDL_Vulkan_LoadLibrary() */ extern DECLSPEC void SDLCALL SDL_Vulkan_UnloadLibrary(void); /** * \brief Get the names of the Vulkan instance extensions needed to create * a surface with \c SDL_Vulkan_CreateSurface(). * * \param [in] \c NULL or window Window for which the required Vulkan instance * extensions should be retrieved * \param [in,out] pCount pointer to an \c unsigned related to the number of * required Vulkan instance extensions * \param [out] pNames \c NULL or a pointer to an array to be filled with the * required Vulkan instance extensions * * \return \c SDL_TRUE on success, \c SDL_FALSE on error. * * If \a pNames is \c NULL, then the number of required Vulkan instance * extensions is returned in pCount. Otherwise, \a pCount must point to a * variable set to the number of elements in the \a pNames array, and on * return the variable is overwritten with the number of names actually * written to \a pNames. If \a pCount is less than the number of required * extensions, at most \a pCount structures will be written. If \a pCount * is smaller than the number of required extensions, \c SDL_FALSE will be * returned instead of \c SDL_TRUE, to indicate that not all the required * extensions were returned. * * \note If \c window is not NULL, it will be checked against its creation * flags to ensure that the Vulkan flag is present. This parameter * will be removed in a future major release. * * \note The returned list of extensions will contain \c VK_KHR_surface * and zero or more platform specific extensions * * \note The extension names queried here must be enabled when calling * VkCreateInstance, otherwise surface creation will fail. * * \note \c window should have been created with the \c SDL_WINDOW_VULKAN flag * or be \c NULL * * \code * unsigned int count; * // get count of required extensions * if(!SDL_Vulkan_GetInstanceExtensions(NULL, &count, NULL)) * handle_error(); * * static const char *const additionalExtensions[] = * { * VK_EXT_DEBUG_REPORT_EXTENSION_NAME, // example additional extension * }; * size_t additionalExtensionsCount = sizeof(additionalExtensions) / sizeof(additionalExtensions[0]); * size_t extensionCount = count + additionalExtensionsCount; * const char **names = malloc(sizeof(const char *) * extensionCount); * if(!names) * handle_error(); * * // get names of required extensions * if(!SDL_Vulkan_GetInstanceExtensions(NULL, &count, names)) * handle_error(); * * // copy additional extensions after required extensions * for(size_t i = 0; i < additionalExtensionsCount; i++) * names[i + count] = additionalExtensions[i]; * * VkInstanceCreateInfo instanceCreateInfo = {}; * instanceCreateInfo.enabledExtensionCount = extensionCount; * instanceCreateInfo.ppEnabledExtensionNames = names; * // fill in rest of instanceCreateInfo * * VkInstance instance; * // create the Vulkan instance * VkResult result = vkCreateInstance(&instanceCreateInfo, NULL, &instance); * free(names); * \endcode * * \sa SDL_Vulkan_CreateSurface() */ extern DECLSPEC SDL_bool SDLCALL SDL_Vulkan_GetInstanceExtensions(SDL_Window *window, unsigned int *pCount, const char **pNames); /** * \brief Create a Vulkan rendering surface for a window. * * \param [in] window SDL_Window to which to attach the rendering surface. * \param [in] instance handle to the Vulkan instance to use. * \param [out] surface pointer to a VkSurfaceKHR handle to receive the * handle of the newly created surface. * * \return \c SDL_TRUE on success, \c SDL_FALSE on error. * * \code * VkInstance instance; * SDL_Window *window; * * // create instance and window * * // create the Vulkan surface * VkSurfaceKHR surface; * if(!SDL_Vulkan_CreateSurface(window, instance, &surface)) * handle_error(); * \endcode * * \note \a window should have been created with the \c SDL_WINDOW_VULKAN flag. * * \note \a instance should have been created with the extensions returned * by \c SDL_Vulkan_CreateSurface() enabled. * * \sa SDL_Vulkan_GetInstanceExtensions() */ extern DECLSPEC SDL_bool SDLCALL SDL_Vulkan_CreateSurface(SDL_Window *window, VkInstance instance, VkSurfaceKHR* surface); /** * \brief Get the size of a window's underlying drawable in pixels (for use * with setting viewport, scissor & etc). * * \param window SDL_Window from which the drawable size should be queried * \param w Pointer to variable for storing the width in pixels, * may be NULL * \param h Pointer to variable for storing the height in pixels, * may be NULL * * This may differ from SDL_GetWindowSize() if we're rendering to a high-DPI * drawable, i.e. the window was created with SDL_WINDOW_ALLOW_HIGHDPI on a * platform with high-DPI support (Apple calls this "Retina"), and not disabled * by the \c SDL_HINT_VIDEO_HIGHDPI_DISABLED hint. * * \note On macOS high-DPI support must be enabled for an application by * setting NSHighResolutionCapable to true in its Info.plist. * * \sa SDL_GetWindowSize() * \sa SDL_CreateWindow() */ extern DECLSPEC void SDLCALL SDL_Vulkan_GetDrawableSize(SDL_Window * window, int *w, int *h); /* @} *//* Vulkan support functions */ /* Ends C function definitions when using C++ */ #ifdef __cplusplus } #endif #include "close_code.h" #endif /* SDL_vulkan_h_ */
YifuLiu/AliOS-Things
components/SDL2/include/SDL_vulkan.h
C
apache-2.0
10,965
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file begin_code.h * * This file sets things up for C dynamic library function definitions, * static inlined functions, and structures aligned at 4-byte alignment. * If you don't like ugly C preprocessor code, don't look at this file. :) */ /* This shouldn't be nested -- included it around code only. */ #ifdef _begin_code_h #error Nested inclusion of begin_code.h #endif #define _begin_code_h #ifndef SDL_DEPRECATED # if (__GNUC__ >= 4) /* technically, this arrived in gcc 3.1, but oh well. */ # define SDL_DEPRECATED __attribute__((deprecated)) # else # define SDL_DEPRECATED # endif #endif #ifndef SDL_UNUSED # ifdef __GNUC__ # define SDL_UNUSED __attribute__((unused)) # else # define SDL_UNUSED # endif #endif /* Some compilers use a special export keyword */ #ifndef DECLSPEC # if defined(__WIN32__) || defined(__WINRT__) # ifdef __BORLANDC__ # ifdef BUILD_SDL # define DECLSPEC # else # define DECLSPEC __declspec(dllimport) # endif # else # define DECLSPEC __declspec(dllexport) # endif # elif defined(__OS2__) # ifdef BUILD_SDL # define DECLSPEC __declspec(dllexport) # else # define DECLSPEC # endif # else # if defined(__GNUC__) && __GNUC__ >= 4 # define DECLSPEC __attribute__ ((visibility("default"))) # else # define DECLSPEC # endif # endif #endif /* By default SDL uses the C calling convention */ #ifndef SDLCALL #if (defined(__WIN32__) || defined(__WINRT__)) && !defined(__GNUC__) #define SDLCALL __cdecl #elif defined(__OS2__) || defined(__EMX__) #define SDLCALL _System # if defined (__GNUC__) && !defined(_System) # define _System /* for old EMX/GCC compat. */ # endif #else #define SDLCALL #endif #endif /* SDLCALL */ /* Removed DECLSPEC on Symbian OS because SDL cannot be a DLL in EPOC */ #ifdef __SYMBIAN32__ #undef DECLSPEC #define DECLSPEC #endif /* __SYMBIAN32__ */ /* Force structure packing at 4 byte alignment. This is necessary if the header is included in code which has structure packing set to an alternate value, say for loading structures from disk. The packing is reset to the previous value in close_code.h */ #if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__) #ifdef _MSC_VER #pragma warning(disable: 4103) #endif #ifdef __clang__ #pragma clang diagnostic ignored "-Wpragma-pack" #endif #ifdef __BORLANDC__ #pragma nopackwarning #endif #ifdef _M_X64 /* Use 8-byte alignment on 64-bit architectures, so pointers are aligned */ #pragma pack(push,8) #else #pragma pack(push,4) #endif #endif /* Compiler needs structure packing set */ #ifndef SDL_INLINE #if defined(__GNUC__) #define SDL_INLINE __inline__ #elif defined(_MSC_VER) || defined(__BORLANDC__) || \ defined(__DMC__) || defined(__SC__) || \ defined(__WATCOMC__) || defined(__LCC__) || \ defined(__DECC) || defined(__CC_ARM) #define SDL_INLINE __inline #ifndef __inline__ #define __inline__ __inline #endif #else #define SDL_INLINE inline #ifndef __inline__ #define __inline__ inline #endif #endif #endif /* SDL_INLINE not defined */ #ifndef SDL_FORCE_INLINE #if defined(_MSC_VER) #define SDL_FORCE_INLINE __forceinline #elif ( (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) ) #define SDL_FORCE_INLINE __attribute__((always_inline)) static __inline__ #else #define SDL_FORCE_INLINE static SDL_INLINE #endif #endif /* SDL_FORCE_INLINE not defined */ #ifndef SDL_NORETURN #if defined(__GNUC__) #define SDL_NORETURN __attribute__((noreturn)) #elif defined(_MSC_VER) #define SDL_NORETURN __declspec(noreturn) #else #define SDL_NORETURN #endif #endif /* SDL_NORETURN not defined */ /* Apparently this is needed by several Windows compilers */ #if !defined(__MACH__) #ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void *)0) #endif #endif /* NULL */ #endif /* ! Mac OS X - breaks precompiled headers */
YifuLiu/AliOS-Things
components/SDL2/include/begin_code.h
C
apache-2.0
4,804
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /** * \file close_code.h * * This file reverses the effects of begin_code.h and should be included * after you finish any function and structure declarations in your headers */ #ifndef _begin_code_h #error close_code.h included without matching begin_code.h #endif #undef _begin_code_h /* Reset structure packing at previous byte alignment */ #if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__) #ifdef __BORLANDC__ #pragma nopackwarning #endif #pragma pack(pop) #endif /* Compiler needs structure packing set */
YifuLiu/AliOS-Things
components/SDL2/include/close_code.h
C
apache-2.0
1,480
#! /bin/bash # libtool - Provide generalized library-building support services. # Generated automatically by config.status () # Libtool was configured on host localhost: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool 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. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool 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 GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # The names of the tagged configurations supported by this script. available_tags="RC CXX " # ### BEGIN LIBTOOL CONFIG # Which release of libtool.m4 was used? macro_version=2.4.2 macro_revision=1.3337 # Assembler program. AS="as" # DLL creation program. DLLTOOL="false" # Object dumper program. OBJDUMP="objdump" # Whether or not to build shared libraries. build_libtool_libs=yes # Whether or not to build static libraries. build_old_libs=yes # What type of objects to build. pic_mode=default # Whether or not to optimize for fast installation. fast_install=yes # Shell to use when invoking shell scripts. SHELL="/bin/bash" # An echo program that protects backslashes. ECHO="printf %s\\n" # The PATH separator for the build system. PATH_SEPARATOR=":" # The host system. host_alias= host=x86_64-pc-linux-gnu host_os=linux-gnu # The build system. build_alias= build=x86_64-pc-linux-gnu build_os=linux-gnu # A sed program that does not truncate output. SED="/bin/sed" # Sed that helps us avoid accidentally triggering echo(1) options like -n. Xsed="$SED -e 1s/^X//" # A grep program that handles long lines. GREP="/bin/grep" # An ERE matcher. EGREP="/bin/grep -E" # A literal string matcher. FGREP="/bin/grep -F" # A BSD- or MS-compatible name lister. NM="/usr/bin/nm -B" # Whether we need soft or hard links. LN_S="ln -s" # What is the maximum length of a command? max_cmd_len=1572864 # Object file suffix (normally "o"). objext=o # Executable file suffix (normally ""). exeext= # whether the shell understands "unset". lt_unset=unset # turn spaces into newlines. SP2NL="tr \\040 \\012" # turn newlines into spaces. NL2SP="tr \\015\\012 \\040\\040" # convert $build file names to $host format. to_host_file_cmd=func_convert_file_noop # convert $build files to toolchain format. to_tool_file_cmd=func_convert_file_noop # Method to check whether dependent libraries are shared objects. deplibs_check_method="pass_all" # Command to use when deplibs_check_method = "file_magic". file_magic_cmd="\$MAGIC_CMD" # How to find potential files when deplibs_check_method = "file_magic". file_magic_glob="" # Find potential files using nocaseglob when deplibs_check_method = "file_magic". want_nocaseglob="no" # Command to associate shared and link libraries. sharedlib_from_linklib_cmd="printf %s\\n" # The archiver. AR="ar" # Flags to create an archive. AR_FLAGS="cru" # How to feed a file listing to the archiver. archiver_list_spec="@" # A symbol stripping program. STRIP="strip" # Commands used to install an old-style archive. RANLIB="ranlib" old_postinstall_cmds="chmod 644 \$oldlib~\$RANLIB \$tool_oldlib" old_postuninstall_cmds="" # Whether to use a lock for old archive extraction. lock_old_archive_extraction=no # A C compiler. LTCC="gcc" # LTCC compiler flags. LTCFLAGS="-g -O2 -Iinclude -I/workspace/atos_core_release/components/utilities/SDL/include -idirafter /workspace/atos_core_release/components/utilities/SDL/src/video/khronos " # Take the output of nm and produce a listing of raw symbols and C names. global_symbol_pipe="sed -n -e 's/^.*[ ]\\([ABCDGIRSTW][ABCDGIRSTW]*\\)[ ][ ]*\\([_A-Za-z][_A-Za-z0-9]*\\)\$/\\1 \\2 \\2/p' | sed '/ __gnu_lto/d'" # Transform the output of nm in a proper C declaration. global_symbol_to_cdecl="sed -n -e 's/^T .* \\(.*\\)\$/extern int \\1();/p' -e 's/^[ABCDGIRSTW]* .* \\(.*\\)\$/extern char \\1;/p'" # Transform the output of nm in a C name address pair. global_symbol_to_c_name_address="sed -n -e 's/^: \\([^ ]*\\)[ ]*\$/ {\\\"\\1\\\", (void *) 0},/p' -e 's/^[ABCDGIRSTW]* \\([^ ]*\\) \\([^ ]*\\)\$/ {\"\\2\", (void *) \\&\\2},/p'" # Transform the output of nm in a C name address pair when lib prefix is needed. global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \\([^ ]*\\)[ ]*\$/ {\\\"\\1\\\", (void *) 0},/p' -e 's/^[ABCDGIRSTW]* \\([^ ]*\\) \\(lib[^ ]*\\)\$/ {\"\\2\", (void *) \\&\\2},/p' -e 's/^[ABCDGIRSTW]* \\([^ ]*\\) \\([^ ]*\\)\$/ {\"lib\\2\", (void *) \\&\\2},/p'" # Specify filename containing input files for $NM. nm_file_list_spec="@" # The root where to search for dependent libraries,and in which our libraries should be installed. lt_sysroot= # The name of the directory that contains temporary libtool files. objdir=.libs # Used to examine libraries when file_magic_cmd begins with "file". MAGIC_CMD=file # Must we lock files when doing compilation? need_locks="no" # Manifest tool. MANIFEST_TOOL=":" # Tool to manipulate archived DWARF debug symbol files on Mac OS X. DSYMUTIL="" # Tool to change global to local symbols on Mac OS X. NMEDIT="" # Tool to manipulate fat objects and archives on Mac OS X. LIPO="" # ldd/readelf like tool for Mach-O binaries on Mac OS X. OTOOL="" # ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. OTOOL64="" # Old archive suffix (normally "a"). libext=a # Shared library suffix (normally ".so"). shrext_cmds=".so" # The commands to extract the exported symbol list from a shared archive. extract_expsyms_cmds="" # Variables whose values should be saved in libtool wrapper scripts and # restored at link time. variables_saved_for_relink="PATH LD_LIBRARY_PATH LD_RUN_PATH GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" # Do we need the "lib" prefix for modules? need_lib_prefix=no # Do we need a version for libraries? need_version=no # Library versioning type. version_type=linux # Shared library runtime path variable. runpath_var=LD_RUN_PATH # Shared library path variable. shlibpath_var=LD_LIBRARY_PATH # Is shlibpath searched before the hard-coded library search path? shlibpath_overrides_runpath=no # Format of library name prefix. libname_spec="lib\$name" # List of archive names. First name is the real one, the rest are links. # The last name is the one that the linker finds with -lNAME library_names_spec="\${libname}\${release}\${shared_ext}\$versuffix \${libname}\${release}\${shared_ext}\$major \$libname\${shared_ext}" # The coded name of the library, if different from the real name. soname_spec="\${libname}\${release}\${shared_ext}\$major" # Permission mode override for installation of shared libraries. install_override_mode="" # Command to use after installation of a shared archive. postinstall_cmds="" # Command to use after uninstallation of a shared archive. postuninstall_cmds="" # Commands used to finish a libtool library installation in a directory. finish_cmds="PATH=\\\"\\\$PATH:/sbin\\\" ldconfig -n \$libdir" # As "finish_cmds", except a single script fragment to be evaled but # not shown. finish_eval="" # Whether we should hardcode library paths into libraries. hardcode_into_libs=yes # Compile-time system search path for libraries. sys_lib_search_path_spec="/usr/lib/gcc/x86_64-linux-gnu/5 /usr/lib/x86_64-linux-gnu /usr/lib /lib/x86_64-linux-gnu /lib " # Run-time system search path for libraries. sys_lib_dlsearch_path_spec="/lib /usr/lib /lib/i386-linux-gnu /usr/lib/i386-linux-gnu /lib/i686-linux-gnu /usr/lib/i686-linux-gnu /usr/local/lib /lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/mesa-egl /usr/lib/x86_64-linux-gnu/mesa /lib32 /usr/lib32 /libx32 /usr/libx32 " # Whether dlopen is supported. dlopen_support=unknown # Whether dlopen of programs is supported. dlopen_self=unknown # Whether dlopen of statically linked programs is supported. dlopen_self_static=unknown # Commands to strip libraries. old_striplib="strip --strip-debug" striplib="strip --strip-unneeded" # The linker used to build libraries. LD="/usr/bin/ld -m elf_x86_64" # How to create reloadable object files. reload_flag=" -r" reload_cmds="\$LD\$reload_flag -o \$output\$reload_objs" # Commands used to build an old-style archive. old_archive_cmds="\$AR \$AR_FLAGS \$oldlib\$oldobjs~\$RANLIB \$tool_oldlib" # A language specific compiler. CC="gcc" # Is the compiler the GNU compiler? with_gcc=yes # Compiler flag to turn off builtin functions. no_builtin_flag=" -fno-builtin" # Additional compiler flags for building library objects. pic_flag=" -fPIC -DPIC" # How to pass a linker flag through the compiler. wl="-Wl," # Compiler flag to prevent dynamic linking. link_static_flag="-static" # Does compiler simultaneously support -c and -o options? compiler_c_o="yes" # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=no # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=no # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec="\${wl}--export-dynamic" # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec="\${wl}--whole-archive\$convenience \${wl}--no-whole-archive" # Whether the compiler copes with passing no objects directly. compiler_needs_object="no" # Create an old-style archive from a shared archive. old_archive_from_new_cmds="" # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds="" # Commands used to build a shared archive. archive_cmds="\$CC -shared \$pic_flag \$libobjs \$deplibs \$compiler_flags \${wl}-soname \$wl\$soname -o \$lib" archive_expsym_cmds="echo \\\"{ global:\\\" > \$output_objdir/\$libname.ver~ cat \$export_symbols | sed -e \\\"s/\\\\(.*\\\\)/\\\\1;/\\\" >> \$output_objdir/\$libname.ver~ echo \\\"local: *; };\\\" >> \$output_objdir/\$libname.ver~ \$CC -shared \$pic_flag \$libobjs \$deplibs \$compiler_flags \${wl}-soname \$wl\$soname \${wl}-version-script \${wl}\$output_objdir/\$libname.ver -o \$lib" # Commands used to build a loadable module if different from building # a shared archive. module_cmds="" module_expsym_cmds="" # Whether we are building with GNU ld or not. with_gnu_ld="yes" # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag="" # Flag that enforces no undefined symbols. no_undefined_flag="" # Flag to hardcode $libdir into a binary during linking. # This must work even if $libdir does not exist hardcode_libdir_flag_spec="\${wl}-rpath \${wl}\$libdir" # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator="" # Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=no # Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting ${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=no # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=no # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=unsupported # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=no # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=no # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=unknown # Set to "yes" if exported symbols are required. always_export_symbols=no # The commands to list exported symbols. export_symbols_cmds="\$NM \$libobjs \$convenience | \$global_symbol_pipe | \$SED 's/.* //' | sort | uniq > \$export_symbols" # Symbols that should not be listed in the preloaded symbols. exclude_expsyms="_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*" # Symbols that must always be exported. include_expsyms="" # Commands necessary for linking programs (against libraries) with templates. prelink_cmds="" # Commands necessary for finishing linking programs. postlink_cmds="" # Specify filename containing input files. file_list_spec="" # How to hardcode a shared library path into an executable. hardcode_action=immediate # The directories searched by this compiler when creating a shared library. compiler_lib_search_dirs="" # Dependencies to place before and after the objects being linked to # create a shared library. predep_objects="" postdep_objects="" predeps="" postdeps="" # The library search path used internally by the compiler when linking # a shared library. compiler_lib_search_path="" # ### END LIBTOOL CONFIG # libtool (GNU libtool) 2.4.2 # Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, # 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool 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. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool 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 GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, # or obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Usage: $progname [OPTION]... [MODE-ARG]... # # Provide generalized library-building support services. # # --config show all configuration variables # --debug enable verbose shell tracing # -n, --dry-run display commands without modifying any files # --features display basic configuration information and exit # --mode=MODE use operation mode MODE # --preserve-dup-deps don't remove duplicate dependency libraries # --quiet, --silent don't print informational messages # --no-quiet, --no-silent # print informational messages (default) # --no-warn don't display warning messages # --tag=TAG use configuration variables from tag TAG # -v, --verbose print more informational messages than default # --no-verbose don't print the extra informational messages # --version print version information # -h, --help, --help-all print short, long, or detailed help message # # MODE must be one of the following: # # clean remove files from the build directory # compile compile a source file into a libtool object # execute automatically set library path, then run a program # finish complete the installation of libtool libraries # install install libraries or executables # link create a library or an executable # uninstall remove libraries from an installed directory # # MODE-ARGS vary depending on the MODE. When passed as first option, # `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that. # Try `$progname --help --mode=MODE' for a more detailed description of MODE. # # When reporting a bug, please describe a test case to reproduce it and # include the following information: # # host-triplet: $host # shell: $SHELL # compiler: $LTCC # compiler flags: $LTCFLAGS # linker: $LD (gnu? $with_gnu_ld) # $progname: (GNU libtool) 2.4.2 # automake: $automake_version # autoconf: $autoconf_version # # Report bugs to <bug-libtool@gnu.org>. # GNU libtool home page: <http://www.gnu.org/software/libtool/>. # General help using GNU software: <http://www.gnu.org/gethelp/>. PROGRAM=libtool PACKAGE=libtool VERSION=2.4.2 TIMESTAMP="" package_revision=1.3337 # Be Bourne compatible if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } # NLS nuisances: We save the old values to restore during execute mode. lt_user_locale= lt_safe_locale= for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${$lt_var+set}\" = set; then save_$lt_var=\$$lt_var $lt_var=C export $lt_var lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" fi" done LC_ALL=C LANGUAGE=C export LANGUAGE LC_ALL $lt_unset CDPATH # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath="$0" : ${CP="cp -f"} test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} : ${Xsed="$SED -e 1s/^X//"} # Global variables: EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. exit_status=$EXIT_SUCCESS # Make sure IFS has a sensible default lt_nl=' ' IFS=" $lt_nl" dirname="s,/[^/]*$,," basename="s,^.*/,," # func_dirname file append nondir_replacement # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. func_dirname () { case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac } # Extended-shell func_dirname implementation # func_basename file func_basename () { func_basename_result="${1##*/}" } # Extended-shell func_basename implementation # func_dirname_and_basename file append nondir_replacement # perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value returned in "$func_basename_result" # Implementation must be kept synchronized with func_dirname # and func_basename. For efficiency, we do not delegate to # those functions but instead duplicate the functionality here. func_dirname_and_basename () { case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac func_basename_result="${1##*/}" } # Extended-shell func_dirname_and_basename implementation # func_stripname prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # func_strip_suffix prefix name func_stripname () { # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary parameter first. func_stripname_result=${3} func_stripname_result=${func_stripname_result#"${1}"} func_stripname_result=${func_stripname_result%"${2}"} } # Extended-shell func_stripname implementation # These SED scripts presuppose an absolute path with a trailing slash. pathcar='s,^/\([^/]*\).*$,\1,' pathcdr='s,^/[^/]*,,' removedotparts=':dotsl s@/\./@/@g t dotsl s,/\.$,/,' collapseslashes='s@/\{1,\}@/@g' finalslash='s,/*$,/,' # func_normal_abspath PATH # Remove doubled-up and trailing slashes, "." path components, # and cancel out any ".." path components in PATH after making # it an absolute path. # value returned in "$func_normal_abspath_result" func_normal_abspath () { # Start from root dir and reassemble the path. func_normal_abspath_result= func_normal_abspath_tpath=$1 func_normal_abspath_altnamespace= case $func_normal_abspath_tpath in "") # Empty path, that just means $cwd. func_stripname '' '/' "`pwd`" func_normal_abspath_result=$func_stripname_result return ;; # The next three entries are used to spot a run of precisely # two leading slashes without using negated character classes; # we take advantage of case's first-match behaviour. ///*) # Unusual form of absolute path, do nothing. ;; //*) # Not necessarily an ordinary path; POSIX reserves leading '//' # and for example Cygwin uses it to access remote file shares # over CIFS/SMB, so we conserve a leading double slash if found. func_normal_abspath_altnamespace=/ ;; /*) # Absolute path, do nothing. ;; *) # Relative path, prepend $cwd. func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath ;; esac # Cancel out all the simple stuff to save iterations. We also want # the path to end with a slash for ease of parsing, so make sure # there is one (and only one) here. func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"` while :; do # Processed it all yet? if test "$func_normal_abspath_tpath" = / ; then # If we ascended to the root using ".." the result may be empty now. if test -z "$func_normal_abspath_result" ; then func_normal_abspath_result=/ fi break fi func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$pathcar"` func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$pathcdr"` # Figure out what to do with it case $func_normal_abspath_tcomponent in "") # Trailing empty path component, ignore it. ;; ..) # Parent dir; strip last assembled component from result. func_dirname "$func_normal_abspath_result" func_normal_abspath_result=$func_dirname_result ;; *) # Actual path component, append it. func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent ;; esac done # Restore leading double-slash if one was found on entry. func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result } # func_relative_path SRCDIR DSTDIR # generates a relative path from SRCDIR to DSTDIR, with a trailing # slash if non-empty, suitable for immediately appending a filename # without needing to append a separator. # value returned in "$func_relative_path_result" func_relative_path () { func_relative_path_result= func_normal_abspath "$1" func_relative_path_tlibdir=$func_normal_abspath_result func_normal_abspath "$2" func_relative_path_tbindir=$func_normal_abspath_result # Ascend the tree starting from libdir while :; do # check if we have found a prefix of bindir case $func_relative_path_tbindir in $func_relative_path_tlibdir) # found an exact match func_relative_path_tcancelled= break ;; $func_relative_path_tlibdir*) # found a matching prefix func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" func_relative_path_tcancelled=$func_stripname_result if test -z "$func_relative_path_result"; then func_relative_path_result=. fi break ;; *) func_dirname $func_relative_path_tlibdir func_relative_path_tlibdir=${func_dirname_result} if test "x$func_relative_path_tlibdir" = x ; then # Have to descend all the way to the root! func_relative_path_result=../$func_relative_path_result func_relative_path_tcancelled=$func_relative_path_tbindir break fi func_relative_path_result=../$func_relative_path_result ;; esac done # Now calculate path; take care to avoid doubling-up slashes. func_stripname '' '/' "$func_relative_path_result" func_relative_path_result=$func_stripname_result func_stripname '/' '/' "$func_relative_path_tcancelled" if test "x$func_stripname_result" != x ; then func_relative_path_result=${func_relative_path_result}/${func_stripname_result} fi # Normalisation. If bindir is libdir, return empty string, # else relative path ending with a slash; either way, target # file name can be directly appended. if test ! -z "$func_relative_path_result"; then func_stripname './' '' "$func_relative_path_result/" func_relative_path_result=$func_stripname_result fi } # The name of this program: func_dirname_and_basename "$progpath" progname=$func_basename_result # Make sure we have an absolute path for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=$func_dirname_result progdir=`cd "$progdir" && pwd` progpath="$progdir/$progname" ;; *) save_IFS="$IFS" IFS=${PATH_SEPARATOR-:} for progdir in $PATH; do IFS="$save_IFS" test -x "$progdir/$progname" && break done IFS="$save_IFS" test -n "$progdir" || progdir=`pwd` progpath="$progdir/$progname" ;; esac # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. Xsed="${SED}"' -e 1s/^X//' sed_quote_subst='s/\([`"$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution that turns a string into a regex matching for the # string literally. sed_make_literal_regex='s,[].[^$\\*\/],\\&,g' # Sed substitution that converts a w32 file name or path # which contains forward slashes, into one that contains # (escaped) backslashes. A very naive implementation. lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Re-`\' parameter expansions in output of double_quote_subst that were # `\'-ed in input to the same. If an odd number of `\' preceded a '$' # in input to double_quote_subst, that '$' was protected from expansion. # Since each input `\' is now two `\'s, look for any number of runs of # four `\'s followed by two `\'s and then a '$'. `\' that '$'. bs='\\' bs2='\\\\' bs4='\\\\\\\\' dollar='\$' sed_double_backslash="\ s/$bs4/&\\ /g s/^$bs2$dollar/$bs&/ s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g s/\n//g" # Standard options: opt_dry_run=false opt_help=false opt_quiet=false opt_verbose=false opt_warning=: # func_echo arg... # Echo program name prefixed message, along with the current mode # name if it has been set yet. func_echo () { $ECHO "$progname: ${opt_mode+$opt_mode: }$*" } # func_verbose arg... # Echo program name prefixed message in verbose mode only. func_verbose () { $opt_verbose && func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } # func_error arg... # Echo program name prefixed message to standard error. func_error () { $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2 } # func_warning arg... # Echo program name prefixed warning message to standard error. func_warning () { $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2 # bash bug again: : } # func_fatal_error arg... # Echo program name prefixed message to standard error, and exit. func_fatal_error () { func_error ${1+"$@"} exit $EXIT_FAILURE } # func_fatal_help arg... # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { func_error ${1+"$@"} func_fatal_error "$help" } help="Try \`$progname --help' for more information." ## default # func_grep expression filename # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $GREP "$1" "$2" >/dev/null 2>&1 } # func_mkdir_p directory-path # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { my_directory_path="$1" my_dir_list= if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then # Protect directory names starting with `-' case $my_directory_path in -*) my_directory_path="./$my_directory_path" ;; esac # While some portion of DIR does not yet exist... while test ! -d "$my_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. my_dir_list="$my_directory_path:$my_dir_list" # If the last portion added has no slash in it, the list is done case $my_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"` done my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'` save_mkdir_p_IFS="$IFS"; IFS=':' for my_dir in $my_dir_list; do IFS="$save_mkdir_p_IFS" # mkdir can fail with a `File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$my_dir" 2>/dev/null || : done IFS="$save_mkdir_p_IFS" # Bail out if we (or some other process) failed to create a directory. test -d "$my_directory_path" || \ func_fatal_error "Failed to create \`$1'" fi } # func_mktempdir [string] # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, STRING is the basename for that directory. func_mktempdir () { my_template="${TMPDIR-/tmp}/${1-$progname}" if test "$opt_dry_run" = ":"; then # Return a directory name, but don't create it in dry-run mode my_tmpdir="${my_template}-$$" else # If mktemp works, use that first and foremost my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` if test ! -d "$my_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race my_tmpdir="${my_template}-${RANDOM-0}$$" save_mktempdir_umask=`umask` umask 0077 $MKDIR "$my_tmpdir" umask $save_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$my_tmpdir" || \ func_fatal_error "cannot create temporary directory \`$my_tmpdir'" fi $ECHO "$my_tmpdir" } # func_quote_for_eval arg # Aesthetically quote ARG to be evaled later. # This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT # is double-quoted, suitable for a subsequent eval, whereas # FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters # which are still active within double quotes backslashified. func_quote_for_eval () { case $1 in *[\\\`\"\$]*) func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;; *) func_quote_for_eval_unquoted_result="$1" ;; esac case $func_quote_for_eval_unquoted_result in # Double-quote args containing shell metacharacters to delay # word splitting, command substitution and and variable # expansion for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" ;; *) func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" esac } # func_quote_for_expand arg # Aesthetically quote ARG to be evaled later; same as above, # but do not quote variable references. func_quote_for_expand () { case $1 in *[\\\`\"]*) my_arg=`$ECHO "$1" | $SED \ -e "$double_quote_subst" -e "$sed_double_backslash"` ;; *) my_arg="$1" ;; esac case $my_arg in # Double-quote args containing shell metacharacters to delay # word splitting and command substitution for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") my_arg="\"$my_arg\"" ;; esac func_quote_for_expand_result="$my_arg" } # func_show_eval cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$my_cmd" my_status=$? if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_show_eval_locale cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$lt_user_locale $my_cmd" my_status=$? eval "$lt_safe_locale" if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_tr_sh # Turn $1 into a string suitable for a shell variable name. # Result is stored in $func_tr_sh_result. All characters # not in the set a-zA-Z0-9_ are replaced with '_'. Further, # if $1 begins with a digit, a '_' is prepended as well. func_tr_sh () { case $1 in [0-9]* | *[!a-zA-Z0-9_]*) func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'` ;; * ) func_tr_sh_result=$1 ;; esac } # func_version # Echo version message to standard output and exit. func_version () { $opt_debug $SED -n '/(C)/!b go :more /\./!{ N s/\n# / / b more } :go /^# '$PROGRAM' (GNU /,/# warranty; / { s/^# // s/^# *$// s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ p }' < "$progpath" exit $? } # func_usage # Echo short help message to standard output and exit. func_usage () { $opt_debug $SED -n '/^# Usage:/,/^# *.*--help/ { s/^# // s/^# *$// s/\$progname/'$progname'/ p }' < "$progpath" echo $ECHO "run \`$progname --help | more' for full usage" exit $? } # func_help [NOEXIT] # Echo long help message to standard output and exit, # unless 'noexit' is passed as argument. func_help () { $opt_debug $SED -n '/^# Usage:/,/# Report bugs to/ { :print s/^# // s/^# *$// s*\$progname*'$progname'* s*\$host*'"$host"'* s*\$SHELL*'"$SHELL"'* s*\$LTCC*'"$LTCC"'* s*\$LTCFLAGS*'"$LTCFLAGS"'* s*\$LD*'"$LD"'* s/\$with_gnu_ld/'"$with_gnu_ld"'/ s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/ s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/ p d } /^# .* home page:/b print /^# General help using/b print ' < "$progpath" ret=$? if test -z "$1"; then exit $ret fi } # func_missing_arg argname # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { $opt_debug func_error "missing argument for $1." exit_cmd=exit } # func_split_short_opt shortopt # Set func_split_short_opt_name and func_split_short_opt_arg shell # variables after splitting SHORTOPT after the 2nd character. func_split_short_opt () { func_split_short_opt_arg=${1#??} func_split_short_opt_name=${1%"$func_split_short_opt_arg"} } # Extended-shell func_split_short_opt implementation # func_split_long_opt longopt # Set func_split_long_opt_name and func_split_long_opt_arg shell # variables after splitting LONGOPT at the `=' sign. func_split_long_opt () { func_split_long_opt_name=${1%%=*} func_split_long_opt_arg=${1#*=} } # Extended-shell func_split_long_opt implementation exit_cmd=: magic="%%%MAGIC variable%%%" magic_exe="%%%MAGIC EXE variable%%%" # Global variables. nonopt= preserve_args= lo2o="s/\\.lo\$/.${objext}/" o2lo="s/\\.${objext}\$/.lo/" extracted_archives= extracted_serial=0 # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # func_append var value # Append VALUE to the end of shell variable VAR. func_append () { eval "${1}+=\${2}" } # Extended-shell func_append implementation # func_append_quoted var value # Quote VALUE and append to the end of shell variable VAR, separated # by a space. func_append_quoted () { func_quote_for_eval "${2}" eval "${1}+=\\ \$func_quote_for_eval_result" } # Extended-shell func_append_quoted implementation # func_arith arithmetic-term... func_arith () { func_arith_result=$(( $* )) } # Extended-shell func_arith implementation # func_len string # STRING may not start with a hyphen. func_len () { func_len_result=${#1} } # Extended-shell func_len implementation # func_lo2o object func_lo2o () { case ${1} in *.lo) func_lo2o_result=${1%.lo}.${objext} ;; *) func_lo2o_result=${1} ;; esac } # Extended-shell func_lo2o implementation # func_xform libobj-or-source func_xform () { func_xform_result=${1%.*}.lo } # Extended-shell func_xform implementation # func_fatal_configuration arg... # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func_error ${1+"$@"} func_error "See the $PACKAGE documentation for more information." func_fatal_error "Fatal configuration error." } # func_config # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # Display the features supported by this script. func_features () { echo "host: $host" if test "$build_libtool_libs" = yes; then echo "enable shared libraries" else echo "disable shared libraries" fi if test "$build_old_libs" = yes; then echo "enable static libraries" else echo "disable static libraries" fi exit $? } # func_enable_tag tagname # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname="$1" re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf="/$re_begincf/,/$re_endcf/p" # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # func_check_version_match # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; esac # Option defaults: opt_debug=: opt_dry_run=false opt_config=false opt_preserve_dup_deps=false opt_features=false opt_finish=false opt_help=false opt_help_all=false opt_silent=: opt_warning=: opt_verbose=: opt_silent=false opt_verbose=false # Parse options once, thoroughly. This comes as soon as possible in the # script to make things like `--version' happen as quickly as we can. { # this just eases exit handling while test $# -gt 0; do opt="$1" shift case $opt in --debug|-x) opt_debug='set -x' func_echo "enabling shell trace mode" $opt_debug ;; --dry-run|--dryrun|-n) opt_dry_run=: ;; --config) opt_config=: func_config ;; --dlopen|-dlopen) optarg="$1" opt_dlopen="${opt_dlopen+$opt_dlopen }$optarg" shift ;; --preserve-dup-deps) opt_preserve_dup_deps=: ;; --features) opt_features=: func_features ;; --finish) opt_finish=: set dummy --mode finish ${1+"$@"}; shift ;; --help) opt_help=: ;; --help-all) opt_help_all=: opt_help=': help-all' ;; --mode) test $# = 0 && func_missing_arg $opt && break optarg="$1" opt_mode="$optarg" case $optarg in # Valid mode arguments: clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $opt" exit_cmd=exit break ;; esac shift ;; --no-silent|--no-quiet) opt_silent=false preserve_args+=" $opt" ;; --no-warning|--no-warn) opt_warning=false preserve_args+=" $opt" ;; --no-verbose) opt_verbose=false preserve_args+=" $opt" ;; --silent|--quiet) opt_silent=: preserve_args+=" $opt" opt_verbose=false ;; --verbose|-v) opt_verbose=: preserve_args+=" $opt" opt_silent=false ;; --tag) test $# = 0 && func_missing_arg $opt && break optarg="$1" opt_tag="$optarg" preserve_args+=" $opt $optarg" func_enable_tag "$optarg" shift ;; -\?|-h) func_usage ;; --help) func_help ;; --version) func_version ;; # Separate optargs to long options: --*=*) func_split_long_opt "$opt" set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"} shift ;; # Separate non-argument short options: -\?*|-h*|-n*|-v*) func_split_short_opt "$opt" set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"} shift ;; --) break ;; -*) func_fatal_help "unrecognized option \`$opt'" ;; *) set dummy "$opt" ${1+"$@"}; shift; break ;; esac done # Validate options: # save first non-option argument if test "$#" -gt 0; then nonopt="$opt" shift fi # preserve --debug test "$opt_debug" = : || preserve_args+=" --debug" case $host in *cygwin* | *mingw* | *pw32* | *cegcc*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps ;; esac $opt_help || { # Sanity checks first: func_check_version_match if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then func_fatal_configuration "not configured to build any kind of library" fi # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$opt_dlopen" && test "$opt_mode" != execute; then func_error "unrecognized option \`-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help="$help" help="Try \`$progname --help --mode=$opt_mode' for more information." } # Bail if the options were screwed $exit_cmd $EXIT_FAILURE } ## ----------- ## ## Main. ## ## ----------- ## # func_lalib_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null \ | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_unsafe_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if `file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case "$lalib_p_line" in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test "$lalib_p" = yes } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { func_lalib_p "$1" } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $opt_debug save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$save_ifs eval cmd=\"$cmd\" func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # `FILE.' does not work on cygwin managed mounts. func_source () { $opt_debug case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_resolve_sysroot PATH # Replace a leading = in PATH with a sysroot. Store the result into # func_resolve_sysroot_result func_resolve_sysroot () { func_resolve_sysroot_result=$1 case $func_resolve_sysroot_result in =*) func_stripname '=' '' "$func_resolve_sysroot_result" func_resolve_sysroot_result=$lt_sysroot$func_stripname_result ;; esac } # func_replace_sysroot PATH # If PATH begins with the sysroot, replace it with = and # store the result into func_replace_sysroot_result. func_replace_sysroot () { case "$lt_sysroot:$1" in ?*:"$lt_sysroot"*) func_stripname "$lt_sysroot" '' "$1" func_replace_sysroot_result="=$func_stripname_result" ;; *) # Including no sysroot. func_replace_sysroot_result=$1 ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $opt_debug if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case "$@ " in " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with \`--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=${1} if test "$build_libtool_libs" = yes; then write_lobj=\'${2}\' else write_lobj=none fi if test "$build_old_libs" = yes; then write_oldobj=\'${3}\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T <<EOF # $write_libobj - a libtool object file # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # Name of the PIC object. pic_object=$write_lobj # Name of the non-PIC object non_pic_object=$write_oldobj EOF $MV "${write_libobj}T" "${write_libobj}" } } ################################################## # FILE NAME AND PATH CONVERSION HELPER FUNCTIONS # ################################################## # func_convert_core_file_wine_to_w32 ARG # Helper function used by file name conversion functions when $build is *nix, # and $host is mingw, cygwin, or some other w32 environment. Relies on a # correctly configured wine environment available, with the winepath program # in $build's $PATH. # # ARG is the $build file name to be converted to w32 format. # Result is available in $func_convert_core_file_wine_to_w32_result, and will # be empty on error (or when ARG is empty) func_convert_core_file_wine_to_w32 () { $opt_debug func_convert_core_file_wine_to_w32_result="$1" if test -n "$1"; then # Unfortunately, winepath does not exit with a non-zero error code, so we # are forced to check the contents of stdout. On the other hand, if the # command is not found, the shell will set an exit code of 127 and print # *an error message* to stdout. So we must check for both error code of # zero AND non-empty stdout, which explains the odd construction: func_convert_core_file_wine_to_w32_tmp=`winepath -w "$1" 2>/dev/null` if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | $SED -e "$lt_sed_naive_backslashify"` else func_convert_core_file_wine_to_w32_result= fi fi } # end: func_convert_core_file_wine_to_w32 # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and # $host is mingw, cygwin, or some other w32 environment. Relies on a correctly # configured wine environment available, with the winepath program in $build's # $PATH. Assumes ARG has no leading or trailing path separator characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. # Unconvertible file (directory) names in ARG are skipped; if no directory names # are convertible, then the result may be empty. func_convert_core_path_wine_to_w32 () { $opt_debug # unfortunately, winepath doesn't convert paths, only file names func_convert_core_path_wine_to_w32_result="" if test -n "$1"; then oldIFS=$IFS IFS=: for func_convert_core_path_wine_to_w32_f in $1; do IFS=$oldIFS func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" if test -n "$func_convert_core_file_wine_to_w32_result" ; then if test -z "$func_convert_core_path_wine_to_w32_result"; then func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result" else func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" fi fi done IFS=$oldIFS fi } # end: func_convert_core_path_wine_to_w32 # func_cygpath ARGS... # Wrapper around calling the cygpath program via LT_CYGPATH. This is used when # when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) # $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or # (2), returns the Cygwin file name or path in func_cygpath_result (input # file name or path is assumed to be in w32 format, as previously converted # from $build's *nix or MSYS format). In case (3), returns the w32 file name # or path in func_cygpath_result (input file name or path is assumed to be in # Cygwin format). Returns an empty string on error. # # ARGS are passed to cygpath, with the last one being the file name or path to # be converted. # # Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH # environment variable; do not put it in $PATH. func_cygpath () { $opt_debug if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` if test "$?" -ne 0; then # on failure, ensure result is empty func_cygpath_result= fi else func_cygpath_result= func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'" fi } #end: func_cygpath # func_convert_core_msys_to_w32 ARG # Convert file name or path ARG from MSYS format to w32 format. Return # result in func_convert_core_msys_to_w32_result. func_convert_core_msys_to_w32 () { $opt_debug # awkward: cmd appends spaces to result func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"` } #end: func_convert_core_msys_to_w32 # func_convert_file_check ARG1 ARG2 # Verify that ARG1 (a file name in $build format) was converted to $host # format in ARG2. Otherwise, emit an error message, but continue (resetting # func_to_host_file_result to ARG1). func_convert_file_check () { $opt_debug if test -z "$2" && test -n "$1" ; then func_error "Could not determine host file name corresponding to" func_error " \`$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_file_result="$1" fi } # end func_convert_file_check # func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH # Verify that FROM_PATH (a path in $build format) was converted to $host # format in TO_PATH. Otherwise, emit an error message, but continue, resetting # func_to_host_file_result to a simplistic fallback value (see below). func_convert_path_check () { $opt_debug if test -z "$4" && test -n "$3"; then func_error "Could not determine the host path corresponding to" func_error " \`$3'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This is a deliberately simplistic "conversion" and # should not be "improved". See libtool.info. if test "x$1" != "x$2"; then lt_replace_pathsep_chars="s|$1|$2|g" func_to_host_path_result=`echo "$3" | $SED -e "$lt_replace_pathsep_chars"` else func_to_host_path_result="$3" fi fi } # end func_convert_path_check # func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG # Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT # and appending REPL if ORIG matches BACKPAT. func_convert_path_front_back_pathsep () { $opt_debug case $4 in $1 ) func_to_host_path_result="$3$func_to_host_path_result" ;; esac case $4 in $2 ) func_to_host_path_result+="$3" ;; esac } # end func_convert_path_front_back_pathsep ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## # invoked via `$to_host_file_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # Result will be available in $func_to_host_file_result. # func_to_host_file ARG # Converts the file name ARG from $build format to $host format. Return result # in func_to_host_file_result. func_to_host_file () { $opt_debug $to_host_file_cmd "$1" } # end func_to_host_file # func_to_tool_file ARG LAZY # converts the file name ARG from $build format to toolchain format. Return # result in func_to_tool_file_result. If the conversion in use is listed # in (the comma separated) LAZY, no conversion takes place. func_to_tool_file () { $opt_debug case ,$2, in *,"$to_tool_file_cmd",*) func_to_tool_file_result=$1 ;; *) $to_tool_file_cmd "$1" func_to_tool_file_result=$func_to_host_file_result ;; esac } # end func_to_tool_file # func_convert_file_noop ARG # Copy ARG to func_to_host_file_result. func_convert_file_noop () { func_to_host_file_result="$1" } # end func_convert_file_noop # func_convert_file_msys_to_w32 ARG # Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_file_result. func_convert_file_msys_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_to_host_file_result="$func_convert_core_msys_to_w32_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_w32 # func_convert_file_cygwin_to_w32 ARG # Convert file name ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_file_cygwin_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then # because $build is cygwin, we call "the" cygpath in $PATH; no need to use # LT_CYGPATH in this case. func_to_host_file_result=`cygpath -m "$1"` fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_cygwin_to_w32 # func_convert_file_nix_to_w32 ARG # Convert file name ARG from *nix to w32 format. Requires a wine environment # and a working winepath. Returns result in func_to_host_file_result. func_convert_file_nix_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_file_wine_to_w32 "$1" func_to_host_file_result="$func_convert_core_file_wine_to_w32_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_w32 # func_convert_file_msys_to_cygwin ARG # Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_file_msys_to_cygwin () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_cygpath -u "$func_convert_core_msys_to_w32_result" func_to_host_file_result="$func_cygpath_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_cygwin # func_convert_file_nix_to_cygwin ARG # Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed # in a wine environment, working winepath, and LT_CYGPATH set. Returns result # in func_to_host_file_result. func_convert_file_nix_to_cygwin () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. func_convert_core_file_wine_to_w32 "$1" func_cygpath -u "$func_convert_core_file_wine_to_w32_result" func_to_host_file_result="$func_cygpath_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_cygwin ############################################# # $build to $host PATH CONVERSION FUNCTIONS # ############################################# # invoked via `$to_host_path_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # The result will be available in $func_to_host_path_result. # # Path separators are also converted from $build format to $host format. If # ARG begins or ends with a path separator character, it is preserved (but # converted to $host format) on output. # # All path conversion functions are named using the following convention: # file name conversion function : func_convert_file_X_to_Y () # path conversion function : func_convert_path_X_to_Y () # where, for any given $build/$host combination the 'X_to_Y' value is the # same. If conversion functions are added for new $build/$host combinations, # the two new functions must follow this pattern, or func_init_to_host_path_cmd # will break. # func_init_to_host_path_cmd # Ensures that function "pointer" variable $to_host_path_cmd is set to the # appropriate value, based on the value of $to_host_file_cmd. to_host_path_cmd= func_init_to_host_path_cmd () { $opt_debug if test -z "$to_host_path_cmd"; then func_stripname 'func_convert_file_' '' "$to_host_file_cmd" to_host_path_cmd="func_convert_path_${func_stripname_result}" fi } # func_to_host_path ARG # Converts the path ARG from $build format to $host format. Return result # in func_to_host_path_result. func_to_host_path () { $opt_debug func_init_to_host_path_cmd $to_host_path_cmd "$1" } # end func_to_host_path # func_convert_path_noop ARG # Copy ARG to func_to_host_path_result. func_convert_path_noop () { func_to_host_path_result="$1" } # end func_convert_path_noop # func_convert_path_msys_to_w32 ARG # Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_path_result. func_convert_path_msys_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # Remove leading and trailing path separator characters from ARG. MSYS # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; # and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result="$func_convert_core_msys_to_w32_result" func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_msys_to_w32 # func_convert_path_cygwin_to_w32 ARG # Convert path ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_path_cygwin_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_cygwin_to_w32 # func_convert_path_nix_to_w32 ARG # Convert path ARG from *nix to w32 format. Requires a wine environment and # a working winepath. Returns result in func_to_host_file_result. func_convert_path_nix_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result="$func_convert_core_path_wine_to_w32_result" func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_nix_to_w32 # func_convert_path_msys_to_cygwin ARG # Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_path_msys_to_cygwin () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_msys_to_w32_result" func_to_host_path_result="$func_cygpath_result" func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_msys_to_cygwin # func_convert_path_nix_to_cygwin ARG # Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a # a wine environment, working winepath, and LT_CYGPATH set. Returns result in # func_to_host_file_result. func_convert_path_nix_to_cygwin () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" func_to_host_path_result="$func_cygpath_result" func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_nix_to_cygwin # func_mode_compile arg... func_mode_compile () { $opt_debug # Get the compilation command and the source file. base_compile= srcfile="$nonopt" # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg="$arg" arg_mode=normal ;; target ) libobj="$arg" arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify \`-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) pie_flag+=" $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) later+=" $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs="$IFS"; IFS=',' for arg in $args; do IFS="$save_ifs" func_append_quoted lastarg "$arg" done IFS="$save_ifs" func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. base_compile+=" $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg="$srcfile" srcfile="$arg" ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_append_quoted base_compile "$lastarg" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with \`-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj="$func_basename_result" } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from \`$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_for_eval "$libobj" test "X$libobj" != "X$func_quote_for_eval_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name \`$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname="$func_basename_result" xdir="$func_dirname_result" lobj=${xdir}$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test "$build_old_libs" = yes; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test "$compiler_c_o" = no; then output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext} lockfile="$output_obj.lock" else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test "$need_locks" = yes; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test "$need_locks" = warn; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi removelist+=" $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist removelist+=" $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 srcfile=$func_to_tool_file_result func_quote_for_eval "$srcfile" qsrcfile=$func_quote_for_eval_result # Only build a PIC object if we are building libtool libraries. if test "$build_libtool_libs" = yes; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test "$pic_mode" != no; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir command+=" -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test "$suppress_opt" = yes; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test "$build_old_libs" = yes; then if test "$pic_mode" != yes; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test "$compiler_c_o" = yes; then command+=" -o $obj" fi # Suppress compiler output if we already did a PIC compilation. command+="$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test "$need_locks" != no; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test "$opt_mode" = compile && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $opt_mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to build PIC objects only -prefer-non-pic try to build non-PIC objects only -shared do not build a \`.o' file suitable for static linking -static only build a \`.o' file suitable for static linking -Wc,FLAG pass FLAG directly to the compiler COMPILE-COMMAND is a command to be used in creating a \`standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix \`.c' with the library object suffix, \`.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to \`-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the \`--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the \`install' or \`cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -bindir BINDIR specify path to binaries directory (for systems where libraries must be found in the PATH setting at runtime) -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE Use a list of object files found in FILE to specify objects -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface -Wc,FLAG -Xcompiler FLAG pass linker-specific FLAG directly to the compiler -Wl,FLAG -Xlinker FLAG pass linker-specific FLAG directly to the linker -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) All other options (arguments beginning with \`-') are ignored. Every other argument is treated as a filename. Files ending in \`.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in \`.la', then a libtool library is created, only library objects (\`.lo' files) may be specified, and \`-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created using \`ar' and \`ranlib', or on Windows using \`lib'. If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode \`$opt_mode'" ;; esac echo $ECHO "Try \`$progname --help' for more information about other modes." } # Now that we've collected a possible --mode arg, show help if necessary if $opt_help; then if test "$opt_help" = :; then func_mode_help else { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do func_mode_help done } | sed -n '1p; 2,$s/^Usage:/ or: /p' { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do echo func_mode_help done } | sed '1d /^When reporting/,/^Report/{ H d } $x /information about other modes/d /more detailed .*MODE/d s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' fi exit $? fi # func_mode_execute arg... func_mode_execute () { $opt_debug # The first argument is the command name. cmd="$nonopt" test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $opt_dlopen; do test -f "$file" \ || func_fatal_help "\`$file' is not a file" dir= case $file in *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "\`$file' was not linked with \`-export-dynamic'" continue fi func_dirname "$file" "" "." dir="$func_dirname_result" if test -f "$dir/$objdir/$dlname"; then dir+="/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir="$func_dirname_result" ;; *) func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir="$absdir" # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic="$magic" # Check if any of the arguments is a wrapper script. args= for file do case $file in -* | *.la | *.lo ) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file="$progdir/$program" elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file="$progdir/$program" fi ;; esac # Quote arguments (to preserve shell metacharacters). func_append_quoted args "$file" done if test "X$opt_dry_run" = Xfalse; then if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd="\$cmd$args" else # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" echo "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS fi } test "$opt_mode" = execute && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $opt_debug libs= libdirs= admincmds= for opt in "$nonopt" ${1+"$@"} do if test -d "$opt"; then libdirs+=" $opt" elif test -f "$opt"; then if func_lalib_unsafe_p "$opt"; then libs+=" $opt" else func_warning "\`$opt' is not a valid libtool archive" fi else func_fatal_error "invalid argument \`$opt'" fi done if test -n "$libs"; then if test -n "$lt_sysroot"; then sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" else sysroot_cmd= fi # Remove sysroot references if $opt_dry_run; then for lib in $libs; do echo "removing references to $lt_sysroot and \`=' prefixes from $lib" done else tmpdir=`func_mktempdir` for lib in $libs; do sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ > $tmpdir/tmp-la mv -f $tmpdir/tmp-la $lib done ${RM}r "$tmpdir" fi fi if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || admincmds+=" $cmds" fi done fi # Exit here if they wanted silent mode. $opt_silent && exit $EXIT_SUCCESS if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then echo "----------------------------------------------------------------------" echo "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" echo "specify the full pathname of the library, or use the \`-LLIBDIR'" echo "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then echo " - add LIBDIR to the \`$shlibpath_var' environment variable" echo " during execution" fi if test -n "$runpath_var"; then echo " - add LIBDIR to the \`$runpath_var' environment variable" echo " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the \`$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" fi echo echo "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" echo "pages." ;; *) echo "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac echo "----------------------------------------------------------------------" fi exit $EXIT_SUCCESS } test "$opt_mode" = finish && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $opt_debug # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || # Allow the use of GNU shtool's install command. case $nonopt in *shtool*) :;; *) false;; esac; then # Aesthetically quote it. func_quote_for_eval "$nonopt" install_prog="$func_quote_for_eval_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_for_eval "$arg" install_prog+="$func_quote_for_eval_result" install_shared_prog=$install_prog case " $install_prog " in *[\\\ /]cp\ *) install_cp=: ;; *) install_cp=false ;; esac # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=no stripme= no_mode=: for arg do arg2= if test -n "$dest"; then files+=" $dest" dest=$arg continue fi case $arg in -d) isdir=yes ;; -f) if $install_cp; then :; else prev=$arg fi ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then if test "x$prev" = x-m && test -n "$install_override_mode"; then arg2=$install_override_mode no_mode=false fi prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_for_eval "$arg" install_prog+=" $func_quote_for_eval_result" if test -n "$arg2"; then func_quote_for_eval "$arg2" fi install_shared_prog+=" $func_quote_for_eval_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the \`$prev' option requires an argument" if test -n "$install_override_mode" && $no_mode; then if $install_cp; then :; else func_quote_for_eval "$install_override_mode" install_shared_prog+=" -m $func_quote_for_eval_result" fi fi if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=yes if test "$isdir" = yes; then destdir="$dest" destname= else func_dirname_and_basename "$dest" "" "." destdir="$func_dirname_result" destname="$func_basename_result" # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "\`$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "\`$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. staticlibs+=" $file" ;; *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) current_libdirs+=" $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) future_libdirs+=" $libdir" ;; esac fi func_dirname "$file" "/" "" dir="$func_dirname_result" dir+="$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi func_warning "relinking \`$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname="$1" shift srcname="$realname" test -n "$relink_command" && srcname="$realname"T # Install the shared library and build the symlinks. func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme="$stripme" case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme="" ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try `ln -sf' first, because the `ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib="$destdir/$realname" func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name="$func_basename_result" instname="$dir/$name"i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && staticlibs+=" $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest="$destfile" destfile= ;; *) func_fatal_help "cannot copy a libtool object to \`$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test "$build_old_libs" = yes; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext="" case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=".exe" fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script \`$wrapper'" finalize=yes for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test if test -n "$libdir" && test ! -f "$libfile"; then func_warning "\`$lib' has not been installed in \`$libdir'" finalize=no fi done relink_command= func_source "$wrapper" outputname= if test "$fast_install" = no && test -n "$relink_command"; then $opt_dry_run || { if test "$finalize" = yes; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file="$func_basename_result" outputname="$tmpdir/$file" # Replace the output file specification. relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` $opt_silent || { func_quote_for_expand "$relink_command" eval "func_echo $func_quote_for_expand_result" } if eval "$relink_command"; then : else func_error "error: relink \`$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file="$outputname" else func_warning "cannot relink \`$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name="$func_basename_result" # Set up the ranlib parameters. oldlib="$destdir/$name" func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $tool_oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run \`$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test "$opt_mode" = install && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $opt_debug my_outputname="$1" my_originator="$2" my_pic_p="${3-no}" my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms="${my_outputname}S.c" else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist="$output_objdir/${my_outputname}.nm" func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif #if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) #pragma GCC diagnostic ignored \"-Wstrict-prototypes\" #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 can't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif /* External symbol declarations for the compiler. */\ " if test "$dlself" = yes; then func_verbose "generating symbol list for \`$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` for progfile in $progfiles; do func_to_tool_file "$progfile" func_convert_file_msys_to_w32 func_verbose "extracting global C symbols from \`$func_to_tool_file_result'" $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols="$output_objdir/$outputname.exp" $opt_dry_run || { $RM $export_symbols eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from \`$dlprefile'" func_basename "$dlprefile" name="$func_basename_result" case $host in *cygwin* | *mingw* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" eval "curr_lafile=\$libfile_$func_tr_sh_result" dlprefile_dlbasename="" if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then # Use subshell, to avoid clobbering current variable values dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` if test -n "$dlprefile_dlname" ; then func_basename "$dlprefile_dlname" dlprefile_dlbasename="$func_basename_result" else # no lafile. user explicitly requested -dlpreopen <import library>. $sharedlib_from_linklib_cmd "$dlprefile" dlprefile_dlbasename=$sharedlib_from_linklib_result fi fi $opt_dry_run || { if test -n "$dlprefile_dlbasename" ; then eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' else func_warning "Could not compute DLL name from $name" eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" } else # not an import lib $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } fi ;; *) $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } ;; esac done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 </dev/null >/dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else echo '/* NONE */' >> "$output_objdir/$my_dlsyms" fi echo >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; extern LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[]; LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = {\ { \"$my_originator\", (void *) 0 }," case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac echo >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) if test "X$my_pic_p" != Xno; then pic_flag_for_symtable=" $pic_flag" fi ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) symtab_cflags+=" $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' # Transform the symbol file into the correct name. symfileobj="$output_objdir/${my_outputname}S.$objext" case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for \`$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` fi } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. # Despite the name, also deal with 64 bit binaries. func_win32_libid () { $opt_debug win32_libid_type="unknown" win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then func_to_tool_file "$1" func_convert_file_msys_to_w32 win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | $SED -n -e ' 1,100{ / I /{ s,.*,import, p q } }'` case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_cygming_dll_for_implib ARG # # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib () { $opt_debug sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` } # func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs # # The is the core of a fallback implementation of a # platform-specific function to extract the name of the # DLL associated with the specified import library LIBNAME. # # SECTION_NAME is either .idata$6 or .idata$7, depending # on the platform and compiler that created the implib. # # Echos the name of the DLL associated with the # specified import library. func_cygming_dll_for_implib_fallback_core () { $opt_debug match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` $OBJDUMP -s --section "$1" "$2" 2>/dev/null | $SED '/^Contents of section '"$match_literal"':/{ # Place marker at beginning of archive member dllname section s/.*/====MARK====/ p d } # These lines can sometimes be longer than 43 characters, but # are always uninteresting /:[ ]*file format pe[i]\{,1\}-/d /^In archive [^:]*:/d # Ensure marker is printed /^====MARK====/p # Remove all lines with less than 43 characters /^.\{43\}/!d # From remaining lines, remove first 43 characters s/^.\{43\}//' | $SED -n ' # Join marker and all lines until next marker into a single line /^====MARK====/ b para H $ b para b :para x s/\n//g # Remove the marker s/^====MARK====// # Remove trailing dots and whitespace s/[\. \t]*$// # Print /./p' | # we now have a list, one entry per line, of the stringified # contents of the appropriate section of all members of the # archive which possess that section. Heuristic: eliminate # all those which have a first or second character that is # a '.' (that is, objdump's representation of an unprintable # character.) This should work for all archives with less than # 0x302f exports -- but will fail for DLLs whose name actually # begins with a literal '.' or a single character followed by # a '.'. # # Of those that remain, print the first one. $SED -e '/^\./d;/^.\./d;q' } # func_cygming_gnu_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is a GNU/binutils-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_gnu_implib_p () { $opt_debug func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` test -n "$func_cygming_gnu_implib_tmp" } # func_cygming_ms_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is an MS-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_ms_implib_p () { $opt_debug func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` test -n "$func_cygming_ms_implib_tmp" } # func_cygming_dll_for_implib_fallback ARG # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # # This fallback implementation is for use when $DLLTOOL # does not support the --identify-strict option. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib_fallback () { $opt_debug if func_cygming_gnu_implib_p "$1" ; then # binutils import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` elif func_cygming_ms_implib_p "$1" ; then # ms-generated import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` else # unknown sharedlib_from_linklib_result="" fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { $opt_debug f_ex_an_ar_dir="$1"; shift f_ex_an_ar_oldlib="$1" if test "$lock_old_archive_extraction" = yes; then lockfile=$f_ex_an_ar_oldlib.lock until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done fi func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ 'stat=$?; rm -f "$lockfile"; exit $stat' if test "$lock_old_archive_extraction" = yes; then $opt_dry_run || rm -f "$lockfile" fi if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $opt_debug my_gentop="$1"; shift my_oldlibs=${1+"$@"} my_oldobjs="" my_xlib="" my_xabs="" my_xdir="" for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib="$func_basename_result" my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir="$my_gentop/$my_xlib_u" func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` darwin_base_archive=`basename "$darwin_archive"` darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches ; do func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" func_extract_an_archive "`pwd`" "${darwin_base_archive}" cd "$darwin_curdir" $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` done func_extract_archives_result="$my_oldobjs" } # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory in which it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=${1-no} $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then file=\"\$0\"" qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"` $ECHO "\ # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } ECHO=\"$qECHO\" fi # Very basic option parsing. These options are (a) specific to # the libtool wrapper, (b) are identical between the wrapper # /script/ and the wrapper /executable/ which is used only on # windows platforms, and (c) all begin with the string "--lt-" # (application programs are unlikely to have options which match # this pattern). # # There are only two supported options: --lt-debug and # --lt-dump-script. There is, deliberately, no --lt-help. # # The first argument to this parsing function should be the # script's $0 value, followed by "$@". lt_option_debug= func_parse_lt_options () { lt_script_arg0=\$0 shift for lt_opt do case \"\$lt_opt\" in --lt-debug) lt_option_debug=1 ;; --lt-dump-script) lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` cat \"\$lt_dump_D/\$lt_dump_F\" exit 0 ;; --lt-*) \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 exit 1 ;; esac done # Print the debug banner immediately: if test -n \"\$lt_option_debug\"; then echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2 fi } # Used when --lt-debug. Prints its arguments to stdout # (redirection is the responsibility of the caller) func_lt_dump_args () { lt_dump_args_N=1; for lt_arg do \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\" lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` done } # Core function for launching the target application func_exec_program_core () { " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 } # A function to encapsulate launching the target application # Strips options in the --lt-* namespace from \$@ and # launches target application with the remaining arguments. func_exec_program () { case \" \$* \" in *\\ --lt-*) for lt_wr_arg do case \$lt_wr_arg in --lt-*) ;; *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; esac shift done ;; esac func_exec_program_core \${1+\"\$@\"} } # Parse options func_parse_lt_options \"\$0\" \${1+\"\$@\"} # Find the directory that this script lives in. thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test "$fast_install" = yes; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else $ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # fixup the dll searchpath if we need to. # # Fix the DLL searchpath if we need to. Do this before prepending # to shlibpath, because on Windows, both are PATH and uninstalled # libraries must come first. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi # Export our shlibpath_var if we have one. if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` export $shlibpath_var " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. func_exec_program \${1+\"\$@\"} fi else # The program doesn't exist. \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat <<EOF /* $cwrappersource - temporary wrapper executable for $objdir/$outputname Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION The $output program cannot be directly executed until all the libtool libraries that it depends on are installed. This wrapper executable should never be moved out of the build directory. If it is, it will not operate correctly. */ EOF cat <<"EOF" #ifdef _MSC_VER # define _CRT_SECURE_NO_DEPRECATE 1 #endif #include <stdio.h> #include <stdlib.h> #ifdef _MSC_VER # include <direct.h> # include <process.h> # include <io.h> #else # include <unistd.h> # include <stdint.h> # ifdef __CYGWIN__ # include <io.h> # endif #endif #include <malloc.h> #include <stdarg.h> #include <assert.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> /* declarations of non-ANSI functions */ #if defined(__MINGW32__) # ifdef __STRICT_ANSI__ int _putenv (const char *); # endif #elif defined(__CYGWIN__) # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif /* #elif defined (other platforms) ... */ #endif /* portability defines, excluding path handling macros */ #if defined(_MSC_VER) # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv # define S_IXUSR _S_IEXEC # ifndef _INTPTR_T_DEFINED # define _INTPTR_T_DEFINED # define intptr_t int # endif #elif defined(__MINGW32__) # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv #elif defined(__CYGWIN__) # define HAVE_SETENV # define FOPEN_WB "wb" /* #elif defined (other platforms) ... */ #endif #if defined(PATH_MAX) # define LT_PATHMAX PATH_MAX #elif defined(MAXPATHLEN) # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif /* path handling portability macros */ #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ defined (__OS2__) # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free ((void *) stale); stale = 0; } \ } while (0) #if defined(LT_DEBUGWRAPPER) static int lt_debug = 1; #else static int lt_debug = 0; #endif const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_debugprintf (const char *file, int line, const char *fmt, ...); void lt_fatal (const char *file, int line, const char *message, ...); static const char *nonnull (const char *s); static const char *nonempty (const char *s); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); char **prepare_spawn (char **argv); void lt_dump_script (FILE *f); EOF cat <<EOF volatile const char * MAGIC_EXE = "$magic_exe"; const char * LIB_PATH_VARNAME = "$shlibpath_var"; EOF if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then func_to_host_path "$temp_rpath" cat <<EOF const char * LIB_PATH_VALUE = "$func_to_host_path_result"; EOF else cat <<"EOF" const char * LIB_PATH_VALUE = ""; EOF fi if test -n "$dllsearchpath"; then func_to_host_path "$dllsearchpath:" cat <<EOF const char * EXE_PATH_VARNAME = "PATH"; const char * EXE_PATH_VALUE = "$func_to_host_path_result"; EOF else cat <<"EOF" const char * EXE_PATH_VARNAME = ""; const char * EXE_PATH_VALUE = ""; EOF fi if test "$fast_install" = yes; then cat <<EOF const char * TARGET_PROGRAM_NAME = "lt-$outputname"; /* hopefully, no .exe */ EOF else cat <<EOF const char * TARGET_PROGRAM_NAME = "$outputname"; /* hopefully, no .exe */ EOF fi cat <<"EOF" #define LTWRAPPER_OPTION_PREFIX "--lt-" static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX; static const char *dumpscript_opt = LTWRAPPER_OPTION_PREFIX "dump-script"; static const char *debug_opt = LTWRAPPER_OPTION_PREFIX "debug"; int main (int argc, char *argv[]) { char **newargz; int newargc; char *tmp_pathspec; char *actual_cwrapper_path; char *actual_cwrapper_name; char *target_name; char *lt_argv_zero; intptr_t rval = 127; int i; program_name = (char *) xstrdup (base_name (argv[0])); newargz = XMALLOC (char *, argc + 1); /* very simple arg parsing; don't want to rely on getopt * also, copy all non cwrapper options to newargz, except * argz[0], which is handled differently */ newargc=0; for (i = 1; i < argc; i++) { if (strcmp (argv[i], dumpscript_opt) == 0) { EOF case "$host" in *mingw* | *cygwin* ) # make stdout use "unix" line endings echo " setmode(1,_O_BINARY);" ;; esac cat <<"EOF" lt_dump_script (stdout); return 0; } if (strcmp (argv[i], debug_opt) == 0) { lt_debug = 1; continue; } if (strcmp (argv[i], ltwrapper_option_prefix) == 0) { /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX namespace, but it is not one of the ones we know about and have already dealt with, above (including dump-script), then report an error. Otherwise, targets might begin to believe they are allowed to use options in the LTWRAPPER_OPTION_PREFIX namespace. The first time any user complains about this, we'll need to make LTWRAPPER_OPTION_PREFIX a configure-time option or a configure.ac-settable value. */ lt_fatal (__FILE__, __LINE__, "unrecognized %s option: '%s'", ltwrapper_option_prefix, argv[i]); } /* otherwise ... */ newargz[++newargc] = xstrdup (argv[i]); } newargz[++newargc] = NULL; EOF cat <<EOF /* The GNU banner must be the first non-error debug message */ lt_debugprintf (__FILE__, __LINE__, "libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\n"); EOF cat <<"EOF" lt_debugprintf (__FILE__, __LINE__, "(main) argv[0]: %s\n", argv[0]); lt_debugprintf (__FILE__, __LINE__, "(main) program_name: %s\n", program_name); tmp_pathspec = find_executable (argv[0]); if (tmp_pathspec == NULL) lt_fatal (__FILE__, __LINE__, "couldn't find %s", argv[0]); lt_debugprintf (__FILE__, __LINE__, "(main) found exe (before symlink chase) at: %s\n", tmp_pathspec); actual_cwrapper_path = chase_symlinks (tmp_pathspec); lt_debugprintf (__FILE__, __LINE__, "(main) found exe (after symlink chase) at: %s\n", actual_cwrapper_path); XFREE (tmp_pathspec); actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path)); strendzap (actual_cwrapper_path, actual_cwrapper_name); /* wrapper name transforms */ strendzap (actual_cwrapper_name, ".exe"); tmp_pathspec = lt_extend_str (actual_cwrapper_name, ".exe", 1); XFREE (actual_cwrapper_name); actual_cwrapper_name = tmp_pathspec; tmp_pathspec = 0; /* target_name transforms -- use actual target program name; might have lt- prefix */ target_name = xstrdup (base_name (TARGET_PROGRAM_NAME)); strendzap (target_name, ".exe"); tmp_pathspec = lt_extend_str (target_name, ".exe", 1); XFREE (target_name); target_name = tmp_pathspec; tmp_pathspec = 0; lt_debugprintf (__FILE__, __LINE__, "(main) libtool target name: %s\n", target_name); EOF cat <<EOF newargz[0] = XMALLOC (char, (strlen (actual_cwrapper_path) + strlen ("$objdir") + 1 + strlen (actual_cwrapper_name) + 1)); strcpy (newargz[0], actual_cwrapper_path); strcat (newargz[0], "$objdir"); strcat (newargz[0], "/"); EOF cat <<"EOF" /* stop here, and copy so we don't have to do this twice */ tmp_pathspec = xstrdup (newargz[0]); /* do NOT want the lt- prefix here, so use actual_cwrapper_name */ strcat (newargz[0], actual_cwrapper_name); /* DO want the lt- prefix here if it exists, so use target_name */ lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1); XFREE (tmp_pathspec); tmp_pathspec = NULL; EOF case $host_os in mingw*) cat <<"EOF" { char* p; while ((p = strchr (newargz[0], '\\')) != NULL) { *p = '/'; } while ((p = strchr (lt_argv_zero, '\\')) != NULL) { *p = '/'; } } EOF ;; esac cat <<"EOF" XFREE (target_name); XFREE (actual_cwrapper_path); XFREE (actual_cwrapper_name); lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */ lt_setenv ("DUALCASE", "1"); /* for MSK sh */ /* Update the DLL searchpath. EXE_PATH_VALUE ($dllsearchpath) must be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath) because on Windows, both *_VARNAMEs are PATH but uninstalled libraries must come first. */ lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE); lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE); lt_debugprintf (__FILE__, __LINE__, "(main) lt_argv_zero: %s\n", nonnull (lt_argv_zero)); for (i = 0; i < newargc; i++) { lt_debugprintf (__FILE__, __LINE__, "(main) newargz[%d]: %s\n", i, nonnull (newargz[i])); } EOF case $host_os in mingw*) cat <<"EOF" /* execv doesn't actually work on mingw as expected on unix */ newargz = prepare_spawn (newargz); rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz); if (rval == -1) { /* failed to start process */ lt_debugprintf (__FILE__, __LINE__, "(main) failed to launch target \"%s\": %s\n", lt_argv_zero, nonnull (strerror (errno))); return 127; } return rval; EOF ;; *) cat <<"EOF" execv (lt_argv_zero, newargz); return rval; /* =127, but avoids unused variable warning */ EOF ;; esac cat <<"EOF" } void * xmalloc (size_t num) { void *p = (void *) malloc (num); if (!p) lt_fatal (__FILE__, __LINE__, "memory exhausted"); return p; } char * xstrdup (const char *string) { return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL; } const char * base_name (const char *name) { const char *base; #if defined (HAVE_DOS_BASED_FILE_SYSTEM) /* Skip over the disk name in MSDOS pathnames. */ if (isalpha ((unsigned char) name[0]) && name[1] == ':') name += 2; #endif for (base = name; *name; name++) if (IS_DIR_SEPARATOR (*name)) base = name + 1; return base; } int check_executable (const char *path) { struct stat st; lt_debugprintf (__FILE__, __LINE__, "(check_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if ((stat (path, &st) >= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; int tmp_len; char *concat_name; lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", nonempty (wrapper)); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined (HAVE_DOS_BASED_FILE_SYSTEM) if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined (HAVE_DOS_BASED_FILE_SYSTEM) } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = q - p; p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { lt_debugprintf (__FILE__, __LINE__, "checking path component for symlinks: %s\n", tmp_pathspec); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { lt_fatal (__FILE__, __LINE__, "error accessing file \"%s\": %s", tmp_pathspec, nonnull (strerror (errno))); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal (__FILE__, __LINE__, "could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (strcmp (str, pat) == 0) *str = '\0'; } return str; } void lt_debugprintf (const char *file, int line, const char *fmt, ...) { va_list args; if (lt_debug) { (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } } static void lt_error_core (int exit_status, const char *file, int line, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *file, int line, const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); va_end (ap); } static const char * nonnull (const char *s) { return s ? s : "(null)"; } static const char * nonempty (const char *s) { return (s && !*s) ? "(empty)" : nonnull (s); } void lt_setenv (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_setenv) setting '%s' to '%s'\n", nonnull (name), nonnull (value)); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else int len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { int orig_value_len = strlen (orig_value); int add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } void lt_update_exe_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ int len = strlen (new_value); while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[len-1] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF case $host_os in mingw*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). Note that spawn() does not by itself call the command interpreter (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&v); v.dwPlatformId == VER_PLATFORM_WIN32_NT; }) ? "cmd.exe" : "command.com"). Instead it simply concatenates the arguments, separated by ' ', and calls CreateProcess(). We must quote the arguments since Win32 CreateProcess() interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a special way: - Space and tab are interpreted as delimiters. They are not treated as delimiters if they are surrounded by double quotes: "...". - Unescaped double quotes are removed from the input. Their only effect is that within double quotes, space and tab are treated like normal characters. - Backslashes not followed by double quotes are not special. - But 2*n+1 backslashes followed by a double quote become n backslashes followed by a double quote (n >= 0): \" -> " \\\" -> \" \\\\\" -> \\" */ #define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" #define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" char ** prepare_spawn (char **argv) { size_t argc; char **new_argv; size_t i; /* Count number of arguments. */ for (argc = 0; argv[argc] != NULL; argc++) ; /* Allocate new argument vector. */ new_argv = XMALLOC (char *, argc + 1); /* Put quoted arguments into the new argument vector. */ for (i = 0; i < argc; i++) { const char *string = argv[i]; if (string[0] == '\0') new_argv[i] = xstrdup ("\"\""); else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) { int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); size_t length; unsigned int backslashes; const char *s; char *quoted_string; char *p; length = 0; backslashes = 0; if (quote_around) length++; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') length += backslashes + 1; length++; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) length += backslashes + 1; quoted_string = XMALLOC (char, length + 1); p = quoted_string; backslashes = 0; if (quote_around) *p++ = '"'; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') { unsigned int j; for (j = backslashes + 1; j > 0; j--) *p++ = '\\'; } *p++ = c; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) { unsigned int j; for (j = backslashes; j > 0; j--) *p++ = '\\'; *p++ = '"'; } *p = '\0'; new_argv[i] = quoted_string; } else new_argv[i] = (char *) string; } new_argv[argc] = NULL; return new_argv; } EOF ;; esac cat <<"EOF" void lt_dump_script (FILE* f) { EOF func_emit_wrapper yes | $SED -n -e ' s/^\(.\{79\}\)\(..*\)/\1\ \2/ h s/\([\\"]\)/\\\1/g s/$/\\n/ s/\([^\n]*\).*/ fputs ("\1", f);/p g D' cat <<"EOF" } EOF } # end: func_emit_cwrapperexe_src # func_win32_import_lib_p ARG # True if ARG is an import lib, as indicated by $file_magic_cmd func_win32_import_lib_p () { $opt_debug case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in *import*) : ;; *) false ;; esac } # func_mode_link arg... func_mode_link () { $opt_debug case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # which system we are compiling for in order to pass an extra # flag for every libtool invocation. allow_undefined=no ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no bindir= dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=no prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module="${wl}-single_module" func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg="$1" shift func_quote_for_eval "$arg" qarg=$func_quote_for_eval_unquoted_result libtool_args+=" $func_quote_for_eval_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) compile_command+=" @OUTPUT@" finalize_command+=" @OUTPUT@" ;; esac case $prev in bindir) bindir="$arg" prev= continue ;; dlfiles|dlprefiles) if test "$preload" = no; then # Add the symbol object into the linking commands. compile_command+=" @SYMFILE@" finalize_command+=" @SYMFILE@" preload=yes fi case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test "$dlself" = no; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test "$prev" = dlprefiles; then dlself=yes elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test "$prev" = dlfiles; then dlfiles+=" $arg" else dlprefiles+=" $arg" fi prev= continue ;; esac ;; expsyms) export_symbols="$arg" test -f "$arg" \ || func_fatal_error "symbol file \`$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex="$arg" prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) deplibs+=" $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir="$arg" prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # moreargs+=" $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then dlfiles+=" $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. dlprefiles+=" $pic_object" prev= fi # A PIC object. libobjs+=" $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object non_pic_objects+=" $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" non_pic_objects+=" $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result libobjs+=" $pic_object" non_pic_objects+=" $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file \`$arg' does not exist" fi arg=$save_arg prev= continue ;; precious_regex) precious_files_regex="$arg" prev= continue ;; release) release="-$arg" prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test "$prev" = rpath; then case "$rpath " in *" $arg "*) ;; *) rpath+=" $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) xrpath+=" $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds="$arg" prev= continue ;; weak) weak_libs+=" $arg" prev= continue ;; xcclinker) linker_flags+=" $qarg" compiler_flags+=" $qarg" prev= compile_command+=" $qarg" finalize_command+=" $qarg" continue ;; xcompiler) compiler_flags+=" $qarg" prev= compile_command+=" $qarg" finalize_command+=" $qarg" continue ;; xlinker) linker_flags+=" $qarg" compiler_flags+=" $wl$qarg" prev= compile_command+=" $wl$qarg" finalize_command+=" $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg="$arg" case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. compile_command+=" $link_static_flag" finalize_command+=" $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "\`-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -bindir) prev=bindir continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test "X$arg" = "X-export-symbols"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) compile_command+=" $arg" finalize_command+=" $arg" ;; esac continue ;; -L*) func_stripname "-L" '' "$arg" if test -z "$func_stripname_result"; then if test "$#" -gt 0; then func_fatal_error "require no space between \`-L' and \`$1'" else func_fatal_error "need path for \`-L' option" fi fi func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of \`$dir'" dir="$absdir" ;; esac case "$deplibs " in *" -L$dir "* | *" $arg "*) # Will only happen for absolute or sysroot arguments ;; *) # Preserve sysroot, but never include relative directories case $dir in [\\/]* | [A-Za-z]:[\\/]* | =*) deplibs+=" $arg" ;; *) deplibs+=" -L$dir" ;; esac lib_search_path+=" $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) dllsearchpath+=":$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) dllsearchpath+=":$testbindir";; esac ;; esac continue ;; -l*) if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test "X$arg" = "X-lc" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. test "X$arg" = "X-lc" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework deplibs+=" System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test "X$arg" = "X-lc" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test "X$arg" = "X-lc" && continue ;; esac elif test "X$arg" = "X-lc_r"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi deplibs+=" $arg" continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot|--sysroot) compiler_flags+=" $arg" compile_command+=" $arg" finalize_command+=" $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) compiler_flags+=" $arg" compile_command+=" $arg" finalize_command+=" $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) new_inherited_linker_flags+=" $arg" ;; esac continue ;; -multi_module) single_module="${wl}-multi_module" continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "\`-no-install' is ignored for $host" func_warning "assuming \`-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; =*) func_stripname '=' '' "$dir" dir=$lt_sysroot$func_stripname_result ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) xrpath+=" $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" arg+=" $func_quote_for_eval_result" compiler_flags+=" $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" arg+=" $wl$func_quote_for_eval_result" compiler_flags+=" $wl$func_quote_for_eval_result" linker_flags+=" $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; # Flags to be passed through unchanged, with rationale: # -64, -mips[0-9] enable 64-bit mode for the SGI compiler # -r[0-9][0-9]* specify processor for the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler # +DA*, +DD* enable 64-bit mode for the HP compiler # -q* compiler args for the IBM compiler # -m*, -t[45]*, -txscale* architecture-specific flags for GCC # -F/path path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* profiling flags for GCC # @file GCC response files # -tp=* Portland pgcc target processor selection # --sysroot=* for sysroot support # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ -O*|-flto*|-fwhopr*|-fuse-linker-plugin) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" compile_command+=" $arg" finalize_command+=" $arg" compiler_flags+=" $arg" continue ;; # Some other compiler flag. -* | +*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; *.$objext) # A standard object. objs+=" $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then dlfiles+=" $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. dlprefiles+=" $pic_object" prev= fi # A PIC object. libobjs+=" $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object non_pic_objects+=" $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" non_pic_objects+=" $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result libobjs+=" $pic_object" non_pic_objects+=" $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. deplibs+=" $arg" old_deplibs+=" $arg" continue ;; *.la) # A libtool-controlled library. func_resolve_sysroot "$arg" if test "$prev" = dlfiles; then # This library was specified with -dlopen. dlfiles+=" $func_resolve_sysroot_result" prev= elif test "$prev" = dlprefiles; then # The library was specified with -dlpreopen. dlprefiles+=" $func_resolve_sysroot_result" prev= else deplibs+=" $func_resolve_sysroot_result" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then compile_command+=" $arg" finalize_command+=" $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the \`$prevarg' option requires an argument" if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" compile_command+=" $arg" finalize_command+=" $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname="$func_basename_result" libobjs_save="$libobjs" if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" func_dirname "$output" "/" "" output_objdir="$func_dirname_result$objdir" func_to_tool_file "$output_objdir/" tool_output_objdir=$func_to_tool_file_result # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_preserve_dup_deps ; then case "$libs " in *" $deplib "*) specialdeplibs+=" $deplib" ;; esac fi libs+=" $deplib" done if test "$linkmode" = lib; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) specialdeplibs+=" $pre_post_deps" ;; esac pre_post_deps+=" $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=no newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test "$linkmode,$pass" = "lib,link"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs="$tmp_deplibs" fi if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan"; then libs="$deplibs" deplibs= fi if test "$linkmode" = prog; then case $pass in dlopen) libs="$dlfiles" ;; dlpreopen) libs="$dlprefiles" ;; link) libs="$deplibs %DEPLIBS% $dependency_libs" ;; esac fi if test "$linkmode,$pass" = "lib,dlpreopen"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= func_resolve_sysroot "$lib" case $lib in *.la) func_source "$func_resolve_sysroot_result" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do func_basename "$deplib" deplib_base=$func_basename_result case " $weak_libs " in *" $deplib_base "*) ;; *) deplibs+=" $deplib" ;; esac done done libs="$dlprefiles" fi if test "$pass" = dlopen; then # Collect dlpreopened libraries save_deplibs="$deplibs" deplibs= fi for deplib in $libs; do lib= found=no case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else compiler_flags+=" $deplib" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) new_inherited_linker_flags+=" $deplib" ;; esac fi fi continue ;; -l*) if test "$linkmode" != lib && test "$linkmode" != prog; then func_warning "\`-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test "$linkmode" = lib; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib="$searchdir/lib${name}${search_ext}" if test -f "$lib"; then if test "$search_ext" = ".la"; then found=yes else found=no fi break 2 fi done done if test "$found" != yes; then # deplib doesn't seem to be a libtool library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue else # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll="$l" done if test "X$ll" = "X$old_library" ; then # only static version available found=no func_dirname "$lib" "" "." ladir="$func_dirname_result" lib=$ladir/$old_library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi fi ;; # -l *.ltframework) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) new_inherited_linker_flags+=" $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test "$pass" = conv && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" newlib_search_path+=" $func_resolve_sysroot_result" ;; prog) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi if test "$pass" = scan; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" newlib_search_path+=" $func_resolve_sysroot_result" ;; *) func_warning "\`-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test "$pass" = link; then func_stripname '-R' '' "$deplib" func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) xrpath+=" $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) func_resolve_sysroot "$deplib" lib=$func_resolve_sysroot_result ;; *.$libext) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=no case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=yes fi ;; pass_all) valid_a_lib=yes ;; esac if test "$valid_a_lib" != yes; then echo $ECHO "*** Warning: Trying to link with static lib archive $deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because the file extensions .$libext of this argument makes me believe" echo "*** that it is just a static archive that I should not use here." else echo $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" fi ;; esac continue ;; prog) if test "$pass" != link; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test "$pass" = conv; then deplibs="$deplib $deplibs" elif test "$linkmode" = prog; then if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlopen support or we're linking statically, # we need to preload. newdlprefiles+=" $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else newdlfiles+=" $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=yes continue ;; esac # case $deplib if test "$found" = yes || test -f "$lib"; then : else func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" fi # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "\`$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir="$func_dirname_result" dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) new_inherited_linker_flags+=" $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan" || { test "$linkmode" != prog && test "$linkmode" != lib; }; then test -n "$dlopen" && dlfiles+=" $dlopen" test -n "$dlpreopen" && dlprefiles+=" $dlpreopen" fi if test "$pass" = conv; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # It is a libtool convenience library, so add in its objects. convenience+=" $ladir/$objdir/$old_library" old_convenience+=" $ladir/$objdir/$old_library" elif test "$linkmode" != prog && test "$linkmode" != lib; then func_fatal_error "\`$lib' is not a convenience library" fi tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $deplib "*) specialdeplibs+=" $deplib" ;; esac fi tmp_libs+=" $deplib" done continue fi # $pass = conv # Get the name of the library we link against. linklib= if test -n "$old_library" && { test "$prefer_static_libs" = yes || test "$prefer_static_libs,$installed" = "built,no"; }; then linklib=$old_library else for l in $old_library $library_names; do linklib="$l" done fi if test -z "$linklib"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # This library was specified with -dlopen. if test "$pass" = dlopen; then if test -z "$libdir"; then func_fatal_error "cannot -dlopen a convenience library: \`$lib'" fi if test -z "$dlname" || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. dlprefiles+=" $lib $dependency_libs" else newdlfiles+=" $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of \`$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir="$ladir" fi ;; esac func_basename "$lib" laname="$func_basename_result" # Find the relevant object directory and library name. if test "X$installed" = Xyes; then if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library \`$lib' was moved." dir="$ladir" absdir="$abs_ladir" libdir="$abs_ladir" else dir="$lt_sysroot$libdir" absdir="$lt_sysroot$libdir" fi test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir="$ladir" absdir="$abs_ladir" # Remove this search path later notinst_path+=" $abs_ladir" else dir="$ladir/$objdir" absdir="$abs_ladir/$objdir" # Remove this search path later notinst_path+=" $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test "$pass" = dlpreopen; then if test -z "$libdir" && test "$linkmode" = prog; then func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" fi case "$host" in # special handling for platforms with PE-DLLs. *cygwin* | *mingw* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present # (otherwise, the dlopen module name will be incorrect). We do # this by putting the import library name into $newdlprefiles. # We recover the dlopen module name by 'saving' the la file # name in a special purpose variable, and (later) extracting the # dlname from the la file. if test -n "$dlname"; then func_tr_sh "$dir/$linklib" eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" newdlprefiles+=" $dir/$linklib" else newdlprefiles+=" $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ dlpreconveniencelibs+=" $dir/$old_library" fi ;; * ) # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then newdlprefiles+=" $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ dlpreconveniencelibs+=" $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then newdlprefiles+=" $dir/$dlname" else newdlprefiles+=" $dir/$linklib" fi ;; esac fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test "$linkmode" = lib; then deplibs="$dir/$old_library $deplibs" elif test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test "$linkmode" = prog && test "$pass" != link; then newlib_search_path+=" $ladir" deplibs="$lib $deplibs" linkalldeplibs=no if test "$link_all_deplibs" != no || test -z "$library_names" || test "$build_libtool_libs" = no; then linkalldeplibs=yes fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" newlib_search_path+=" $func_resolve_sysroot_result" ;; esac # Need to link against all dependency_libs? if test "$linkalldeplibs" = yes; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $deplib "*) specialdeplibs+=" $deplib" ;; esac fi tmp_libs+=" $deplib" done # for deplib continue fi # $linkmode = prog... if test "$linkmode,$pass" = "prog,link"; then if test -n "$library_names" && { { test "$prefer_static_libs" = no || test "$prefer_static_libs,$installed" = "built,yes"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then # Make sure the rpath contains only unique directories. case "$temp_rpath:" in *"$absdir:"*) ;; *) temp_rpath+="$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) compile_rpath+=" $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath+=" $libdir" ;; esac ;; esac fi # $linkmode,$pass = prog,link... if test "$alldeplibs" = yes && { test "$deplibs_check_method" = pass_all || { test "$build_libtool_libs" = yes && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test "$use_static_libs" = built && test "$installed" = yes; then use_static_libs=no fi if test -n "$library_names" && { test "$use_static_libs" = no || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc*) # No point in relinking DLLs because paths are not encoded notinst_deplibs+=" $lib" need_relink=no ;; *) if test "$installed" = no; then notinst_deplibs+=" $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule="" for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule="$dlpremoduletest" break fi done if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then echo if test "$linkmode" = prog; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test "$linkmode" = lib && test "$hardcode_into_libs" = yes; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) compile_rpath+=" $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath+=" $libdir" ;; esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname="$1" shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname="$dlname" elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc*) func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; esac eval soname=\"$soname_spec\" else soname="$realname" fi # Make a new name for the extract_expsyms_cmds to use soroot="$soname" func_basename "$soroot" soname="$func_basename_result" func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from \`$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for \`$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test "$linkmode" = prog || test "$opt_mode" != relink; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test "$hardcode_direct" = no; then add="$dir/$linklib" case $host in *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; *-*-sysv4*uw2*) add_dir="-L$dir" ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir="-L$dir" ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we can not # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null ; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library" ; then echo echo "*** And there doesn't seem to be a static archive available" echo "*** The link will probably fail, sorry" else add="$dir/$old_library" fi elif test -n "$old_library"; then add="$dir/$old_library" fi fi esac elif test "$hardcode_minus_L" = no; then case $host in *-*-sunos*) add_shlibpath="$dir" ;; esac add_dir="-L$dir" add="-l$name" elif test "$hardcode_shlibpath_var" = no; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; relink) if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$dir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$absdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) add_dir+=" -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; *) lib_linked=no ;; esac if test "$lib_linked" != yes; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) compile_shlibpath+="$add_shlibpath:" ;; esac fi if test "$linkmode" = prog; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test "$hardcode_direct" != yes && test "$hardcode_minus_L" != yes && test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) finalize_shlibpath+="$libdir:" ;; esac fi fi fi if test "$linkmode" = prog || test "$opt_mode" = relink; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$libdir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$libdir" add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) finalize_shlibpath+="$libdir:" ;; esac add="-l$name" elif test "$hardcode_automatic" = yes; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib" ; then add="$inst_prefix_dir$libdir/$linklib" else add="$libdir/$linklib" fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir="-L$libdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) add_dir+=" -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" fi if test "$linkmode" = prog; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test "$linkmode" = prog; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test "$hardcode_direct" != unsupported; then test -n "$old_library" && linklib="$old_library" compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test "$build_libtool_libs" = yes; then # Not a shared library if test "$deplibs_check_method" != pass_all; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. echo $ECHO "*** Warning: This system can not link to static lib archive $lib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have." if test "$module" = yes; then echo "*** But as you try to build a module library, libtool will still create " echo "*** a static module, that should work as long as the dlopening application" echo "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using \`nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test "$linkmode" = lib; then if test -n "$dependency_libs" && { test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes || test "$link_static" = yes; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) xrpath+=" $temp_xrpath";; esac;; *) temp_deplibs+=" $libdir";; esac done dependency_libs="$temp_deplibs" fi newlib_search_path+=" $absdir" # Link against this library test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result";; *) func_resolve_sysroot "$deplib" ;; esac if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $func_resolve_sysroot_result "*) specialdeplibs+=" $func_resolve_sysroot_result" ;; esac fi tmp_libs+=" $func_resolve_sysroot_result" done if test "$link_all_deplibs" != no; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do path= case $deplib in -L*) path="$deplib" ;; *.la) func_resolve_sysroot "$deplib" deplib=$func_resolve_sysroot_result func_dirname "$deplib" "" "." dir=$func_dirname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of \`$dir'" absdir="$dir" fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names" ; then for tmp in $deplibrary_names ; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl" ; then depdepl="$absdir/$objdir/$depdepl" darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi compiler_flags+=" ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" linker_flags+=" -dylib_file ${darwin_install_name}:${depdepl}" path= fi fi ;; *) path="-L$absdir/$objdir" ;; esac else eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "\`$deplib' seems to be moved" path="-L$absdir" fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test "$pass" = link; then if test "$linkmode" = "prog"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs="$newdependency_libs" if test "$pass" = dlpreopen; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test "$pass" != dlopen; then if test "$pass" != conv; then # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) lib_search_path+=" $dir" ;; esac done newlib_search_path= fi if test "$linkmode,$pass" != "prog,link"; then vars="deplibs" else vars="compile_deplibs finalize_deplibs" fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) tmp_libs+=" $deplib" ;; esac ;; *) tmp_libs+=" $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs ; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i="" ;; esac if test -n "$i" ; then tmp_libs+=" $i" fi done dependency_libs=$tmp_libs done # for pass if test "$linkmode" = prog; then dlfiles="$newdlfiles" fi if test "$linkmode" = prog || test "$linkmode" = lib; then dlprefiles="$newdlprefiles" fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "\`-R' is ignored for archives" test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "\`-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "\`-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs="$output" objs+="$old_deplibs" ;; lib) # Make sure we only generate libraries of the form `libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test "$module" = no && \ func_fatal_help "libtool library \`$output' must begin with \`lib'" if test "$need_lib_prefix" != no; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test "$deplibs_check_method" != pass_all; then func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" else echo $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" libobjs+=" $objs" fi fi test "$dlself" != no && \ func_warning "\`-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test "$#" -gt 1 && \ func_warning "ignoring multiple \`-rpath's for a libtool library" install_libdir="$1" oldlibs= if test -z "$rpath"; then if test "$build_libtool_libs" = yes; then # Building a libtool convenience library. # Some compilers have problems with a `.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "\`-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs="$IFS"; IFS=':' set dummy $vinfo 0 0 0 shift IFS="$save_ifs" test -n "$7" && \ func_fatal_help "too many parameters to \`-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major="$1" number_minor="$2" number_revision="$3" # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # which has an extra 1 added just for fun # case $version_type in # correct linux to gnu/linux during the next big refactor darwin|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_revision" ;; freebsd-aout|freebsd-elf|qnx|sunos) current="$number_major" revision="$number_minor" age="0" ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_minor" lt_irix_increment=no ;; esac ;; no) current="$1" revision="$2" age="$3" ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT \`$current' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION \`$revision' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE \`$age' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE \`$age' is greater than the current interface number \`$current'" func_fatal_error "\`$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; freebsd-aout) major=".$current" versuffix=".$current.$revision"; ;; freebsd-elf) major=".$current" versuffix=".$current" ;; irix | nonstopux) if test "X$lt_irix_increment" = "Xno"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring="$verstring_prefix$major.$revision" # Add in all the interfaces that we are compatible with. loop=$revision while test "$loop" -ne 0; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring_prefix$major.$iface:$verstring" done # Before this point, $major must not contain `.'. major=.$major versuffix="$major.$revision" ;; linux) # correct to gnu/linux during the next big refactor func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=".$current.$age.$revision" verstring="$current.$age.$revision" # Add in all the interfaces that we are compatible with. loop=$age while test "$loop" -ne 0; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring:${iface}.0" done # Make executables depend on our current version. verstring+=":${current}.0" ;; qnx) major=".$current" versuffix=".$current" ;; sunos) major=".$current" versuffix=".$current.$revision" ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 filesystems. func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; *) func_fatal_configuration "unknown library version type \`$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring="0.0" ;; esac if test "$need_version" = no; then versuffix= else versuffix=".0.0" fi fi # Remove version info from name if versioning should be avoided if test "$avoid_version" = yes && test "$need_version" = no; then major= versuffix= verstring="" fi # Check to see if the archive will have undefined symbols. if test "$allow_undefined" = yes; then if test "$allow_undefined_flag" = unsupported; then func_warning "undefined symbols not allowed in $host shared libraries" build_libtool_libs=no build_old_libs=yes fi else # Don't allow undefined symbols. allow_undefined_flag="$no_undefined_flag" fi fi func_generate_dlsyms "$libname" "$libname" "yes" libobjs+=" $symfileobj" test "X$libobjs" = "X " && libobjs= if test "$opt_mode" != relink; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) if test "X$precious_files_regex" != "X"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi removelist+=" $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then oldlibs+=" $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do func_replace_sysroot "$libdir" temp_xrpath+=" -R$func_replace_sysroot_result" case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath+=" $libdir" ;; esac done if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles="$dlfiles" dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) dlfiles+=" $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles="$dlprefiles" dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) dlprefiles+=" $lib" ;; esac done if test "$build_libtool_libs" = yes; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework deplibs+=" System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test "$build_libtool_need_lc" = "yes"; then deplibs+=" -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release="" versuffix="" major="" newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c <<EOF int main() { return 0; } EOF $opt_dry_run || $RM conftest if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then ldd_output=`ldd conftest` for i in $deplibs; do case $i in -l*) func_stripname -l '' "$i" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $i "*) newdeplibs+=" $i" i="" ;; esac fi if test -n "$i" ; then libname=`eval "\\$ECHO \"$libname_spec\""` deplib_matches=`eval "\\$ECHO \"$library_names_spec\""` set dummy $deplib_matches; shift deplib_match=$1 if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then newdeplibs+=" $i" else droppeddeps=yes echo $ECHO "*** Warning: dynamic linker does not accept needed library $i." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which I believe you do not have" echo "*** because a test_compile did reveal that the linker did not use it for" echo "*** its dynamic dependency list that programs get resolved with at runtime." fi fi ;; *) newdeplibs+=" $i" ;; esac done else # Error occurred in the first compile. Let's try to salvage # the situation: Compile a separate program for each library. for i in $deplibs; do case $i in -l*) func_stripname -l '' "$i" name=$func_stripname_result $opt_dry_run || $RM conftest if $LTCC $LTCFLAGS -o conftest conftest.c $i; then ldd_output=`ldd conftest` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $i "*) newdeplibs+=" $i" i="" ;; esac fi if test -n "$i" ; then libname=`eval "\\$ECHO \"$libname_spec\""` deplib_matches=`eval "\\$ECHO \"$library_names_spec\""` set dummy $deplib_matches; shift deplib_match=$1 if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0 ; then newdeplibs+=" $i" else droppeddeps=yes echo $ECHO "*** Warning: dynamic linker does not accept needed library $i." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because a test_compile did reveal that the linker did not use this one" echo "*** as a dynamic dependency that programs can get resolved with at runtime." fi fi else droppeddeps=yes echo $ECHO "*** Warning! Library $i is needed by this library but I was not able to" echo "*** make it link in! You will probably need to install it or some" echo "*** library that it depends on before this library will be fully" echo "*** functional. Installing it before continuing would be even better." fi ;; *) newdeplibs+=" $i" ;; esac done fi ;; file_magic*) set dummy $deplibs_check_method; shift file_magic_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $a_deplib "*) newdeplibs+=" $a_deplib" a_deplib="" ;; esac fi if test -n "$a_deplib" ; then libname=`eval "\\$ECHO \"$libname_spec\""` if test -n "$file_magic_glob"; then libnameglob=`func_echo_all "$libname" | $SED -e $file_magic_glob` else libnameglob=$libname fi test "$want_nocaseglob" = yes && nocaseglob=`shopt -p nocaseglob` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do if test "$want_nocaseglob" = yes; then shopt -s nocaseglob potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` $nocaseglob else potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` fi for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib="$potent_lib" while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; *) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then newdeplibs+=" $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. newdeplibs+=" $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $a_deplib "*) newdeplibs+=" $a_deplib" a_deplib="" ;; esac fi if test -n "$a_deplib" ; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib="$potent_lib" # see symlink-check above in file_magic test if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then newdeplibs+=" $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. newdeplibs+=" $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs="" tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then for i in $predeps $postdeps ; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"` done fi case $tmp_deplibs in *[!\ \ ]*) echo if test "X$deplibs_check_method" = "Xnone"; then echo "*** Warning: inter-library dependencies are not supported in this platform." else echo "*** Warning: inter-library dependencies are not known to be supported." fi echo "*** All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac if test "$droppeddeps" = yes; then if test "$module" = yes; then echo echo "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" echo "*** a static module, that should work as long as the dlopening" echo "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using \`nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else echo "*** The inter-library dependencies that have been dropped here will be" echo "*** automatically added whenever a program is linked with this library" echo "*** or is declared to -dlopen it." if test "$allow_undefined" = no; then echo echo "*** Since this library must not contain undefined symbols," echo "*** because either the platform does not support them or" echo "*** it was explicitly requested with -no-undefined," echo "*** libtool will only create a static version of it." if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) new_libs+=" -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) new_libs+=" $deplib" ;; esac ;; *) new_libs+=" $deplib" ;; esac done deplibs="$new_libs" # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test "$build_libtool_libs" = yes; then # Remove ${wl} instances when linking with ld. # FIXME: should test the right _cmds variable. case $archive_cmds in *\$LD\ *) wl= ;; esac if test "$hardcode_into_libs" = yes; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath="$finalize_rpath" test "$opt_mode" != relink && rpath="$compile_rpath$rpath" for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then func_replace_sysroot "$libdir" libdir=$func_replace_sysroot_result if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) hardcode_libdirs+="$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" dep_rpath+=" $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) perm_rpath+=" $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do rpath+="$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath="$finalize_shlibpath" test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath" if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname="$1" shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname="$realname" fi if test -z "$dlname"; then dlname=$soname fi lib="$output_objdir/$realname" linknames= for link do linknames+=" $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols="$output_objdir/$libname.uexp" delfiles+=" $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile if test "x`$SED 1q $export_symbols`" != xEXPORTS; then # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols="$export_symbols" export_symbols= always_export_symbols=yes fi fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs="$IFS"; IFS='~' for cmd1 in $cmds; do IFS="$save_ifs" # Take the normal branch if the nm_file_list_spec branch # doesn't work or if tool conversion is not needed. case $nm_file_list_spec~$to_tool_file_cmd in *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) try_normal_branch=yes eval cmd=\"$cmd1\" func_len " $cmd" len=$func_len_result ;; *) try_normal_branch=no ;; esac if test "$try_normal_branch" = yes \ && { test "$len" -lt "$max_cmd_len" \ || test "$max_cmd_len" -le -1; } then func_show_eval "$cmd" 'exit $?' skipped_export=false elif test -n "$nm_file_list_spec"; then func_basename "$output" output_la=$func_basename_result save_libobjs=$libobjs save_output=$output output=${output_objdir}/${output_la}.nm func_to_tool_file "$output" libobjs=$nm_file_list_spec$func_to_tool_file_result delfiles+=" $output" func_verbose "creating $NM input file list: $output" for obj in $save_libobjs; do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > "$output" eval cmd=\"$cmd1\" func_show_eval "$cmd" 'exit $?' output=$save_output libobjs=$save_libobjs skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS="$save_ifs" if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter delfiles+=" $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) tmp_deplibs+=" $test_deplib" ;; esac done deplibs="$tmp_deplibs" if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test "$compiler_needs_object" = yes && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop="$output_objdir/${outputname}x" generated+=" $gentop" func_extract_archives $gentop $convenience libobjs+=" $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" linker_flags+=" $flag" fi # Make a backup of the uninstalled library when relinking if test "$opt_mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test "X$skipped_export" != "X:" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output func_basename "$output" output_la=$func_basename_result # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then output=${output_objdir}/${output_la}.lnkscript func_verbose "creating GNU ld script: $output" echo 'INPUT (' > $output for obj in $save_libobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done echo ')' >> $output delfiles+=" $output" func_to_tool_file "$output" output=$func_to_tool_file_result elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then output=${output_objdir}/${output_la}.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test "$compiler_needs_object" = yes; then firstobj="$1 " shift fi for obj do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done delfiles+=" $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-${k}.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test "X$objlist" = X || test "$len" -lt "$max_cmd_len"; then objlist+=" $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test "$k" -eq 1 ; then # The first file doesn't have a previous command to add. reload_objs=$objlist eval concat_cmds=\"$reload_cmds\" else # All subsequent reloadable object files will link in # the last one created. reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-${k}.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-${k}.$objext objlist=" $obj" func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ reload_objs="$objlist $last_robj" eval concat_cmds=\"\${concat_cmds}$reload_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" fi delfiles+=" $output" else output= fi if ${skipped_export-false}; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi fi test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs="$IFS"; IFS='~' for cmd in $concat_cmds; do IFS="$save_ifs" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$opt_mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi if ${skipped_export-false}; then if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter delfiles+=" $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi fi libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" generated+=" $gentop" func_extract_archives $gentop $dlprefiles libobjs+=" $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs="$IFS"; IFS='~' for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$opt_mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" # Restore the uninstalled library and exit if test "$opt_mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test "$module" = yes || test "$export_dynamic" = yes; then # On all known operating systems, these are identical. dlname="$soname" fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "\`-R' is ignored for objects" test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for objects" test -n "$release" && \ func_warning "\`-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object \`$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj="$output" ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # reload_cmds runs $LD directly, so let us get rid of # -Wl from whole_archive_flag_spec and hope we can get by with # turning comma into space.. wl= if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` else gentop="$output_objdir/${obj}x" generated+=" $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # If we're not building shared, we need to use non_pic_objs test "$build_libtool_libs" != yes && libobjs="$non_pic_objects" # Create the old-style object. reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test output="$obj" func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi if test "$build_libtool_libs" != yes; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS fi if test -n "$pic_flag" || test "$pic_mode" != default; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output="$libobj" func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for programs" test -n "$release" && \ func_warning "\`-release' is ignored for programs" test "$preload" = yes \ && test "$dlopen_support" = unknown \ && test "$dlopen_self" = unknown \ && test "$dlopen_self_static" = unknown && \ func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test "$tagname" = CXX ; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) compile_command+=" ${wl}-bind_at_load" finalize_command+=" ${wl}-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) new_libs+=" -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) new_libs+=" $deplib" ;; esac ;; *) new_libs+=" $deplib" ;; esac done compile_deplibs="$new_libs" compile_command+=" $compile_deplibs" finalize_command+=" $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) finalize_rpath+=" $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) hardcode_libdirs+="$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" rpath+=" $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) perm_rpath+=" $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) dllsearchpath+=":$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) dllsearchpath+=":$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath="$rpath" rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) hardcode_libdirs+="$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" rpath+=" $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) finalize_perm_rpath+=" $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath="$rpath" if test -n "$libobjs" && test "$build_old_libs" = yes; then # Transform all the library objects into standard objects. compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" "no" # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=yes case $host in *cegcc* | *mingw32ce*) # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=no ;; *cygwin* | *mingw* ) if test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; *) if test "$need_relink" = no || test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; esac if test "$wrappers_required" = no; then # Replace the output file specification. compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` link_command="$compile_command$compile_rpath" # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Delete the generated files. if test -f "$output_objdir/${outputname}S.${objext}"; then func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' fi exit $exit_status fi if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do rpath+="$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do rpath+="$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test "$no_install" = yes; then # We don't need to create a wrapper script. link_command="$compile_var$compile_command$compile_rpath" # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi exit $EXIT_SUCCESS fi if test "$hardcode_action" = relink; then # Fast installation is not supported link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" func_warning "this platform does not like uninstalled shared libraries" func_warning "\`$output' will be relinked during installation" else if test "$fast_install" != no; then link_command="$finalize_var$compile_command$finalize_rpath" if test "$fast_install" = yes; then relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` else # fast_install is set to needless relink_command= fi else link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" fi fi # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output_objdir/$outputname" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done relink_command="(cd `pwd`; $relink_command)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource="$output_path/$objdir/lt-$output_name.c" cwrapper="$output_path/$output_name.exe" $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host" ; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do if test "$build_libtool_libs" = convenience; then oldobjs="$libobjs_save $symfileobj" addlibs="$convenience" build_libtool_libs=no else if test "$build_libtool_libs" = module; then oldobjs="$libobjs_save" build_libtool_libs=no else oldobjs="$old_deplibs $non_pic_objects" if test "$preload" = yes && test -f "$symfileobj"; then oldobjs+=" $symfileobj" fi fi addlibs="$old_convenience" fi if test -n "$addlibs"; then gentop="$output_objdir/${outputname}x" generated+=" $gentop" func_extract_archives $gentop $addlibs oldobjs+=" $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" generated+=" $gentop" func_extract_archives $gentop $dlprefiles oldobjs+=" $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else echo "copying selected object files to avoid basename conflicts..." gentop="$output_objdir/${outputname}x" generated+=" $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase="$func_basename_result" case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" oldobjs+=" $gentop/$newobj" ;; *) oldobjs+=" $obj" ;; esac done fi func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds elif test -n "$archiver_list_spec"; then func_verbose "using command file archive linking..." for obj in $oldobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > $output_objdir/$libname.libcmd func_to_tool_file "$output_objdir/$libname.libcmd" oldobjs=" $archiver_list_spec$func_to_tool_file_result" cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result objlist+=" $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj" ; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test "X$oldobjs" = "X" ; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test "$build_old_libs" = yes && old_library="$libname.$libext" func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` if test "$hardcode_automatic" = yes ; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test "$installed" = yes; then if test -z "$install_libdir"; then break fi output="$output_objdir/$outputname"i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name="$func_basename_result" func_resolve_sysroot "$deplib" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" newdependency_libs+=" ${lt_sysroot:+=}$libdir/$name" ;; -L*) func_stripname -L '' "$deplib" func_replace_sysroot "$func_stripname_result" newdependency_libs+=" -L$func_replace_sysroot_result" ;; -R*) func_stripname -R '' "$deplib" func_replace_sysroot "$func_stripname_result" newdependency_libs+=" -R$func_replace_sysroot_result" ;; *) newdependency_libs+=" $deplib" ;; esac done dependency_libs="$newdependency_libs" newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" newdlfiles+=" ${lt_sysroot:+=}$libdir/$name" ;; *) newdlfiles+=" $lib" ;; esac done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" newdlprefiles+=" ${lt_sysroot:+=}$libdir/$name" ;; esac done dlprefiles="$newdlprefiles" else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac newdlfiles+=" $abs" done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac newdlprefiles+=" $abs" done dlprefiles="$newdlprefiles" fi $RM $output # place dlname in correct position for cygwin # In fact, it would be nice if we could use this code for all target # systems that can't hard-code library paths into their executables # and that have no shared library path variable independent of PATH, # but it turns out we can't easily determine that from inspecting # libtool variables, so we have to hard-code the OSs to which it # applies here; at the moment, that means platforms that use the PE # object format with DLL files. See the long comment at the top of # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test "x$bindir" != x ; then func_relative_path "$install_libdir" "$bindir" tdlname=$func_relative_path_result$dlname else # Otherwise fall back on heuristic. tdlname=../bin/$dlname fi ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that can not go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test "$installed" = no && test "$need_relink" = yes; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } { test "$opt_mode" = link || test "$opt_mode" = relink; } && func_mode_link ${1+"$@"} # func_mode_uninstall arg... func_mode_uninstall () { $opt_debug RM="$nonopt" files= rmforce= exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" for arg do case $arg in -f) RM+=" $arg"; rmforce=yes ;; -*) RM+=" $arg" ;; *) files+=" $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= for file in $files; do func_dirname "$file" "" "." dir="$func_dirname_result" if test "X$dir" = X.; then odir="$objdir" else odir="$dir/$objdir" fi func_basename "$file" name="$func_basename_result" test "$opt_mode" = uninstall && odir="$dir" # Remember odir for removal later, being careful to avoid duplicates if test "$opt_mode" = clean; then case " $rmdirs " in *" $odir "*) ;; *) rmdirs+=" $odir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif test "$rmforce" = yes; then continue fi rmfiles="$file" case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do rmfiles+=" $odir/$n" done test -n "$old_library" && rmfiles+=" $odir/$old_library" case "$opt_mode" in clean) case " $library_names " in *" $dlname "*) ;; *) test -n "$dlname" && rmfiles+=" $odir/$dlname" ;; esac test -n "$libdir" && rmfiles+=" $odir/$name $odir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test "$pic_object" != none; then rmfiles+=" $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test "$non_pic_object" != none; then rmfiles+=" $dir/$non_pic_object" fi fi ;; *) if test "$opt_mode" = clean ; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe rmfiles+=" $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result rmfiles+=" $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles rmfiles+=" $odir/$name $odir/${name}S.${objext}" if test "$fast_install" = yes && test -n "$relink_command"; then rmfiles+=" $odir/lt-$name" fi if test "X$noexename" != "X$name" ; then rmfiles+=" $odir/lt-${noexename}.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done # Try to remove the ${objdir}s in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } { test "$opt_mode" = uninstall || test "$opt_mode" = clean; } && func_mode_uninstall ${1+"$@"} test -z "$opt_mode" && { help="$generic_help" func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode \`$opt_mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # in which we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: # vi:sw=2 # ### BEGIN LIBTOOL TAG CONFIG: RC # The linker used to build libraries. LD="" # How to create reloadable object files. reload_flag="" reload_cmds="" # Commands used to build an old-style archive. old_archive_cmds="" # A language specific compiler. CC="" # Is the compiler the GNU compiler? with_gcc= # Compiler flag to turn off builtin functions. no_builtin_flag="" # Additional compiler flags for building library objects. pic_flag="" # How to pass a linker flag through the compiler. wl="" # Compiler flag to prevent dynamic linking. link_static_flag="" # Does compiler simultaneously support -c and -o options? compiler_c_o="yes" # Whether or not to add -lc for building shared libraries. build_libtool_need_lc= # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes= # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec="" # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec="" # Whether the compiler copes with passing no objects directly. compiler_needs_object="" # Create an old-style archive from a shared archive. old_archive_from_new_cmds="" # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds="" # Commands used to build a shared archive. archive_cmds="" archive_expsym_cmds="" # Commands used to build a loadable module if different from building # a shared archive. module_cmds="" module_expsym_cmds="" # Whether we are building with GNU ld or not. with_gnu_ld="" # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag="" # Flag that enforces no undefined symbols. no_undefined_flag="" # Flag to hardcode $libdir into a binary during linking. # This must work even if $libdir does not exist hardcode_libdir_flag_spec="" # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator="" # Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct= # Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting ${shlibpath_var} if the # library is relocated. hardcode_direct_absolute= # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L= # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var= # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic= # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath= # Whether libtool must link a program against all its dependency libraries. link_all_deplibs= # Set to "yes" if exported symbols are required. always_export_symbols= # The commands to list exported symbols. export_symbols_cmds="" # Symbols that should not be listed in the preloaded symbols. exclude_expsyms="" # Symbols that must always be exported. include_expsyms="" # Commands necessary for linking programs (against libraries) with templates. prelink_cmds="" # Commands necessary for finishing linking programs. postlink_cmds="" # Specify filename containing input files. file_list_spec="" # How to hardcode a shared library path into an executable. hardcode_action= # The directories searched by this compiler when creating a shared library. compiler_lib_search_dirs="" # Dependencies to place before and after the objects being linked to # create a shared library. predep_objects="" postdep_objects="" predeps="" postdeps="" # The library search path used internally by the compiler when linking # a shared library. compiler_lib_search_path="" # ### END LIBTOOL TAG CONFIG: RC # ### BEGIN LIBTOOL TAG CONFIG: CXX # The linker used to build libraries. LD="/usr/bin/ld -m elf_x86_64" # How to create reloadable object files. reload_flag=" -r" reload_cmds="\$LD\$reload_flag -o \$output\$reload_objs" # Commands used to build an old-style archive. old_archive_cmds="\$AR \$AR_FLAGS \$oldlib\$oldobjs~\$RANLIB \$tool_oldlib" # A language specific compiler. CC="g++" # Is the compiler the GNU compiler? with_gcc=yes # Compiler flag to turn off builtin functions. no_builtin_flag=" -fno-builtin" # Additional compiler flags for building library objects. pic_flag=" -fPIC -DPIC" # How to pass a linker flag through the compiler. wl="-Wl," # Compiler flag to prevent dynamic linking. link_static_flag="-static" # Does compiler simultaneously support -c and -o options? compiler_c_o="yes" # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=no # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=no # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec="\${wl}--export-dynamic" # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec="\${wl}--whole-archive\$convenience \${wl}--no-whole-archive" # Whether the compiler copes with passing no objects directly. compiler_needs_object="no" # Create an old-style archive from a shared archive. old_archive_from_new_cmds="" # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds="" # Commands used to build a shared archive. archive_cmds="\$CC \$pic_flag -shared -nostdlib \$predep_objects \$libobjs \$deplibs \$postdep_objects \$compiler_flags \${wl}-soname \$wl\$soname -o \$lib" archive_expsym_cmds="\$CC \$pic_flag -shared -nostdlib \$predep_objects \$libobjs \$deplibs \$postdep_objects \$compiler_flags \${wl}-soname \$wl\$soname \${wl}-retain-symbols-file \$wl\$export_symbols -o \$lib" # Commands used to build a loadable module if different from building # a shared archive. module_cmds="" module_expsym_cmds="" # Whether we are building with GNU ld or not. with_gnu_ld="yes" # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag="" # Flag that enforces no undefined symbols. no_undefined_flag="" # Flag to hardcode $libdir into a binary during linking. # This must work even if $libdir does not exist hardcode_libdir_flag_spec="\${wl}-rpath \${wl}\$libdir" # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator="" # Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=no # Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting ${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=no # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=no # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=unsupported # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=no # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=no # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=unknown # Set to "yes" if exported symbols are required. always_export_symbols=no # The commands to list exported symbols. export_symbols_cmds="\$NM \$libobjs \$convenience | \$global_symbol_pipe | \$SED 's/.* //' | sort | uniq > \$export_symbols" # Symbols that should not be listed in the preloaded symbols. exclude_expsyms="_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*" # Symbols that must always be exported. include_expsyms="" # Commands necessary for linking programs (against libraries) with templates. prelink_cmds="" # Commands necessary for finishing linking programs. postlink_cmds="" # Specify filename containing input files. file_list_spec="" # How to hardcode a shared library path into an executable. hardcode_action=immediate # The directories searched by this compiler when creating a shared library. compiler_lib_search_dirs="/usr/lib/gcc/x86_64-linux-gnu/5 /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu /usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib /lib/x86_64-linux-gnu /lib/../lib /usr/lib/x86_64-linux-gnu /usr/lib/../lib /usr/lib/gcc/x86_64-linux-gnu/5/../../.." # Dependencies to place before and after the objects being linked to # create a shared library. predep_objects="/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/5/crtbeginS.o" postdep_objects="/usr/lib/gcc/x86_64-linux-gnu/5/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crtn.o" predeps="" postdeps="-lstdc++ -lm -lgcc_s -lc -lgcc_s" # The library search path used internally by the compiler when linking # a shared library. compiler_lib_search_path="-L/usr/lib/gcc/x86_64-linux-gnu/5 -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/5/../../.." # ### END LIBTOOL TAG CONFIG: CXX
YifuLiu/AliOS-Things
components/SDL2/libtool
Shell
apache-2.0
302,911
#!/bin/sh prefix=/usr/local exec_prefix=${prefix} exec_prefix_set=no libdir=${exec_prefix}/lib #usage="\ #Usage: $0 [--prefix[=DIR]] [--exec-prefix[=DIR]] [--version] [--cflags] [--libs]" usage="\ Usage: $0 [--prefix[=DIR]] [--exec-prefix[=DIR]] [--version] [--cflags] [--libs] [--static-libs]" if test $# -eq 0; then echo "${usage}" 1>&2 exit 1 fi while test $# -gt 0; do case "$1" in -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;; *) optarg= ;; esac case $1 in --prefix=*) prefix=$optarg if test $exec_prefix_set = no ; then exec_prefix=$optarg fi ;; --prefix) echo $prefix ;; --exec-prefix=*) exec_prefix=$optarg exec_prefix_set=yes ;; --exec-prefix) echo $exec_prefix ;; --version) echo 2.0.13 ;; --cflags) echo -I${prefix}/include/SDL2 -D_REENTRANT ;; --libs) echo -L${exec_prefix}/lib -Wl,-rpath,${libdir} -Wl,--enable-new-dtags -lSDL2 ;; --static-libs) # --libs|--static-libs) echo -L${exec_prefix}/lib -lSDL2 -Wl,--no-undefined -lm -ldl -lpthread -lrt ;; *) echo "${usage}" 1>&2 exit 1 ;; esac shift done
YifuLiu/AliOS-Things
components/SDL2/sdl2-config
Shell
apache-2.0
1,234
set(PACKAGE_VERSION "2.0.13") if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION) set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION) set(PACKAGE_VERSION_EXACT TRUE) endif() endif()
YifuLiu/AliOS-Things
components/SDL2/sdl2-config-version.cmake
CMake
apache-2.0
278
set(PACKAGE_VERSION "@SDL_VERSION@") if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION) set(PACKAGE_VERSION_COMPATIBLE FALSE) else() set(PACKAGE_VERSION_COMPATIBLE TRUE) if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION) set(PACKAGE_VERSION_EXACT TRUE) endif() endif()
YifuLiu/AliOS-Things
components/SDL2/sdl2-config-version.cmake.in
CMake
apache-2.0
285
# sdl2 cmake project-config input for ./configure scripts set(prefix "/usr/local") set(exec_prefix "${prefix}") set(libdir "${exec_prefix}/lib") set(SDL2_PREFIX "/usr/local") set(SDL2_EXEC_PREFIX "/usr/local") set(SDL2_LIBDIR "${exec_prefix}/lib") set(SDL2_INCLUDE_DIRS "${prefix}/include/SDL2") set(SDL2_LIBRARIES "-L${SDL2_LIBDIR} -Wl,-rpath,${libdir} -Wl,--enable-new-dtags -lSDL2") string(STRIP "${SDL2_LIBRARIES}" SDL2_LIBRARIES) if(NOT TARGET SDL2::SDL2) # Remove -lSDL2 as that is handled by CMake, note the space at the end so it does not replace e.g. -lSDL2main # This may require "libdir" beeing set (from above) string(REPLACE "-lSDL2 " "" SDL2_EXTRA_LINK_FLAGS "-Wl,-rpath,${libdir} -Wl,--enable-new-dtags -lSDL2 ") string(STRIP "${SDL2_EXTRA_LINK_FLAGS}" SDL2_EXTRA_LINK_FLAGS) string(REPLACE "-lSDL2 " "" SDL2_EXTRA_LINK_FLAGS_STATIC " -Wl,--no-undefined -lm -ldl -lpthread -lrt ") string(STRIP "${SDL2_EXTRA_LINK_FLAGS_STATIC}" SDL2_EXTRA_LINK_FLAGS_STATIC) add_library(SDL2::SDL2 SHARED IMPORTED) set_target_properties(SDL2::SDL2 PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${prefix}/include/SDL2" IMPORTED_LINK_INTERFACE_LANGUAGES "C" IMPORTED_LOCATION "${exec_prefix}/lib/${CMAKE_SHARED_LIBRARY_PREFIX}SDL2${CMAKE_SHARED_LIBRARY_SUFFIX}" INTERFACE_LINK_LIBRARIES "${SDL2_EXTRA_LINK_FLAGS}") add_library(SDL2::SDL2-static STATIC IMPORTED) set_target_properties(SDL2::SDL2-static PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${prefix}/include/SDL2" IMPORTED_LINK_INTERFACE_LANGUAGES "C" IMPORTED_LOCATION "${exec_prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}SDL2${CMAKE_STATIC_LIBRARY_SUFFIX}" INTERFACE_LINK_LIBRARIES "${SDL2_EXTRA_LINK_FLAGS_STATIC}") add_library(SDL2::SDL2main STATIC IMPORTED) set_target_properties(SDL2::SDL2main PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES "C" IMPORTED_LOCATION "${exec_prefix}/lib/${CMAKE_STATIC_LIBRARY_PREFIX}SDL2main${CMAKE_STATIC_LIBRARY_SUFFIX}") endif()
YifuLiu/AliOS-Things
components/SDL2/sdl2-config.cmake
CMake
apache-2.0
1,979
# sdl2 cmake project-config input for ./configure scripts set(prefix "@prefix@") set(exec_prefix "@exec_prefix@") set(libdir "@libdir@") set(SDL2_PREFIX "@prefix@") set(SDL2_EXEC_PREFIX "@prefix@") set(SDL2_LIBDIR "@libdir@") set(SDL2_INCLUDE_DIRS "@includedir@/SDL2") set(SDL2_LIBRARIES "-L${SDL2_LIBDIR} @SDL_RLD_FLAGS@ @SDL_LIBS@") string(STRIP "${SDL2_LIBRARIES}" SDL2_LIBRARIES) if(NOT TARGET SDL2::SDL2) # Remove -lSDL2 as that is handled by CMake, note the space at the end so it does not replace e.g. -lSDL2main # This may require "libdir" beeing set (from above) string(REPLACE "-lSDL2 " "" SDL2_EXTRA_LINK_FLAGS "@SDL_RLD_FLAGS@ @SDL_LIBS@ ") string(STRIP "${SDL2_EXTRA_LINK_FLAGS}" SDL2_EXTRA_LINK_FLAGS) string(REPLACE "-lSDL2 " "" SDL2_EXTRA_LINK_FLAGS_STATIC "@SDL_STATIC_LIBS@ ") string(STRIP "${SDL2_EXTRA_LINK_FLAGS_STATIC}" SDL2_EXTRA_LINK_FLAGS_STATIC) add_library(SDL2::SDL2 SHARED IMPORTED) set_target_properties(SDL2::SDL2 PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "@includedir@/SDL2" IMPORTED_LINK_INTERFACE_LANGUAGES "C" IMPORTED_LOCATION "@libdir@/${CMAKE_SHARED_LIBRARY_PREFIX}SDL2${CMAKE_SHARED_LIBRARY_SUFFIX}" INTERFACE_LINK_LIBRARIES "${SDL2_EXTRA_LINK_FLAGS}") add_library(SDL2::SDL2-static STATIC IMPORTED) set_target_properties(SDL2::SDL2-static PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "@includedir@/SDL2" IMPORTED_LINK_INTERFACE_LANGUAGES "C" IMPORTED_LOCATION "@libdir@/${CMAKE_STATIC_LIBRARY_PREFIX}SDL2${CMAKE_STATIC_LIBRARY_SUFFIX}" INTERFACE_LINK_LIBRARIES "${SDL2_EXTRA_LINK_FLAGS_STATIC}") add_library(SDL2::SDL2main STATIC IMPORTED) set_target_properties(SDL2::SDL2main PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES "C" IMPORTED_LOCATION "@libdir@/${CMAKE_STATIC_LIBRARY_PREFIX}SDL2main${CMAKE_STATIC_LIBRARY_SUFFIX}") endif()
YifuLiu/AliOS-Things
components/SDL2/sdl2-config.cmake.in
CMake
apache-2.0
1,838
#!/bin/sh prefix=@prefix@ exec_prefix=@exec_prefix@ exec_prefix_set=no libdir=@libdir@ @ENABLE_STATIC_FALSE@usage="\ @ENABLE_STATIC_FALSE@Usage: $0 [--prefix[=DIR]] [--exec-prefix[=DIR]] [--version] [--cflags] [--libs]" @ENABLE_STATIC_TRUE@usage="\ @ENABLE_STATIC_TRUE@Usage: $0 [--prefix[=DIR]] [--exec-prefix[=DIR]] [--version] [--cflags] [--libs] [--static-libs]" if test $# -eq 0; then echo "${usage}" 1>&2 exit 1 fi while test $# -gt 0; do case "$1" in -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;; *) optarg= ;; esac case $1 in --prefix=*) prefix=$optarg if test $exec_prefix_set = no ; then exec_prefix=$optarg fi ;; --prefix) echo $prefix ;; --exec-prefix=*) exec_prefix=$optarg exec_prefix_set=yes ;; --exec-prefix) echo $exec_prefix ;; --version) echo @SDL_VERSION@ ;; --cflags) echo -I@includedir@/SDL2 @SDL_CFLAGS@ ;; @ENABLE_SHARED_TRUE@ --libs) @ENABLE_SHARED_TRUE@ echo -L@libdir@ @SDL_RLD_FLAGS@ @SDL_LIBS@ @ENABLE_SHARED_TRUE@ ;; @ENABLE_STATIC_TRUE@@ENABLE_SHARED_TRUE@ --static-libs) @ENABLE_STATIC_TRUE@@ENABLE_SHARED_FALSE@ --libs|--static-libs) @ENABLE_STATIC_TRUE@ echo -L@libdir@ @SDL_LIBS@ @SDL_STATIC_LIBS@ @ENABLE_STATIC_TRUE@ ;; *) echo "${usage}" 1>&2 exit 1 ;; esac shift done
YifuLiu/AliOS-Things
components/SDL2/sdl2-config.in
Shell
apache-2.0
1,421
# Configure paths for SDL # Sam Lantinga 9/21/99 # stolen from Manish Singh # stolen back from Frank Belew # stolen from Manish Singh # Shamelessly stolen from Owen Taylor # # Changelog: # * also look for SDL2.framework under Mac OS X # serial 1 dnl AM_PATH_SDL2([MINIMUM-VERSION, [ACTION-IF-FOUND [, ACTION-IF-NOT-FOUND]]]) dnl Test for SDL, and define SDL_CFLAGS and SDL_LIBS dnl AC_DEFUN([AM_PATH_SDL2], [dnl dnl Get the cflags and libraries from the sdl2-config script dnl AC_ARG_WITH(sdl-prefix,[ --with-sdl-prefix=PFX Prefix where SDL is installed (optional)], sdl_prefix="$withval", sdl_prefix="") AC_ARG_WITH(sdl-exec-prefix,[ --with-sdl-exec-prefix=PFX Exec prefix where SDL is installed (optional)], sdl_exec_prefix="$withval", sdl_exec_prefix="") AC_ARG_ENABLE(sdltest, [ --disable-sdltest Do not try to compile and run a test SDL program], , enable_sdltest=yes) AC_ARG_ENABLE(sdlframework, [ --disable-sdlframework Do not search for SDL2.framework], , search_sdl_framework=yes) AC_ARG_VAR(SDL2_FRAMEWORK, [Path to SDL2.framework]) min_sdl_version=ifelse([$1], ,2.0.0,$1) if test "x$sdl_prefix$sdl_exec_prefix" = x ; then PKG_CHECK_MODULES([SDL], [sdl2 >= $min_sdl_version], [sdl_pc=yes], [sdl_pc=no]) else sdl_pc=no if test x$sdl_exec_prefix != x ; then sdl_config_args="$sdl_config_args --exec-prefix=$sdl_exec_prefix" if test x${SDL2_CONFIG+set} != xset ; then SDL2_CONFIG=$sdl_exec_prefix/bin/sdl2-config fi fi if test x$sdl_prefix != x ; then sdl_config_args="$sdl_config_args --prefix=$sdl_prefix" if test x${SDL2_CONFIG+set} != xset ; then SDL2_CONFIG=$sdl_prefix/bin/sdl2-config fi fi fi if test "x$sdl_pc" = xyes ; then no_sdl="" SDL2_CONFIG="pkg-config sdl2" else as_save_PATH="$PATH" if test "x$prefix" != xNONE && test "$cross_compiling" != yes; then PATH="$prefix/bin:$prefix/usr/bin:$PATH" fi AC_PATH_PROG(SDL2_CONFIG, sdl2-config, no, [$PATH]) PATH="$as_save_PATH" no_sdl="" if test "$SDL2_CONFIG" = "no" -a "x$search_sdl_framework" = "xyes"; then AC_MSG_CHECKING(for SDL2.framework) if test "x$SDL2_FRAMEWORK" != x; then sdl_framework=$SDL2_FRAMEWORK else for d in / ~/ /System/; do if test -d "$dLibrary/Frameworks/SDL2.framework"; then sdl_framework="$dLibrary/Frameworks/SDL2.framework" fi done fi if test x"$sdl_framework" != x && test -d "$sdl_framework"; then AC_MSG_RESULT($sdl_framework) sdl_framework_dir=`dirname $sdl_framework` SDL_CFLAGS="-F$sdl_framework_dir -Wl,-framework,SDL2 -I$sdl_framework/include" SDL_LIBS="-F$sdl_framework_dir -Wl,-framework,SDL2" else no_sdl=yes fi fi if test "$SDL2_CONFIG" != "no"; then if test "x$sdl_pc" = "xno"; then AC_MSG_CHECKING(for SDL - version >= $min_sdl_version) SDL_CFLAGS=`$SDL2_CONFIG $sdl_config_args --cflags` SDL_LIBS=`$SDL2_CONFIG $sdl_config_args --libs` fi sdl_major_version=`$SDL2_CONFIG $sdl_config_args --version | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\1/'` sdl_minor_version=`$SDL2_CONFIG $sdl_config_args --version | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\2/'` sdl_micro_version=`$SDL2_CONFIG $sdl_config_args --version | \ sed 's/\([[0-9]]*\).\([[0-9]]*\).\([[0-9]]*\)/\3/'` if test "x$enable_sdltest" = "xyes" ; then ac_save_CFLAGS="$CFLAGS" ac_save_CXXFLAGS="$CXXFLAGS" ac_save_LIBS="$LIBS" CFLAGS="$CFLAGS $SDL_CFLAGS" CXXFLAGS="$CXXFLAGS $SDL_CFLAGS" LIBS="$LIBS $SDL_LIBS" dnl dnl Now check if the installed SDL is sufficiently new. (Also sanity dnl checks the results of sdl2-config to some extent dnl rm -f conf.sdltest AC_TRY_RUN([ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "SDL.h" char* my_strdup (char *str) { char *new_str; if (str) { new_str = (char *)malloc ((strlen (str) + 1) * sizeof(char)); strcpy (new_str, str); } else new_str = NULL; return new_str; } int main (int argc, char *argv[]) { int major, minor, micro; char *tmp_version; /* This hangs on some systems (?) system ("touch conf.sdltest"); */ { FILE *fp = fopen("conf.sdltest", "a"); if ( fp ) fclose(fp); } /* HP/UX 9 (%@#!) writes to sscanf strings */ tmp_version = my_strdup("$min_sdl_version"); if (sscanf(tmp_version, "%d.%d.%d", &major, &minor, &micro) != 3) { printf("%s, bad version string\n", "$min_sdl_version"); exit(1); } if (($sdl_major_version > major) || (($sdl_major_version == major) && ($sdl_minor_version > minor)) || (($sdl_major_version == major) && ($sdl_minor_version == minor) && ($sdl_micro_version >= micro))) { return 0; } else { printf("\n*** 'sdl2-config --version' returned %d.%d.%d, but the minimum version\n", $sdl_major_version, $sdl_minor_version, $sdl_micro_version); printf("*** of SDL required is %d.%d.%d. If sdl2-config is correct, then it is\n", major, minor, micro); printf("*** best to upgrade to the required version.\n"); printf("*** If sdl2-config was wrong, set the environment variable SDL2_CONFIG\n"); printf("*** to point to the correct copy of sdl2-config, and remove the file\n"); printf("*** config.cache before re-running configure\n"); return 1; } } ],, no_sdl=yes,[echo $ac_n "cross compiling; assumed OK... $ac_c"]) CFLAGS="$ac_save_CFLAGS" CXXFLAGS="$ac_save_CXXFLAGS" LIBS="$ac_save_LIBS" fi if test "x$sdl_pc" = "xno"; then if test "x$no_sdl" = "xyes"; then AC_MSG_RESULT(no) else AC_MSG_RESULT(yes) fi fi fi fi if test "x$no_sdl" = x ; then ifelse([$2], , :, [$2]) else if test "$SDL2_CONFIG" = "no" ; then echo "*** The sdl2-config script installed by SDL could not be found" echo "*** If SDL was installed in PREFIX, make sure PREFIX/bin is in" echo "*** your path, or set the SDL2_CONFIG environment variable to the" echo "*** full path to sdl2-config." else if test -f conf.sdltest ; then : else echo "*** Could not run SDL test program, checking why..." CFLAGS="$CFLAGS $SDL_CFLAGS" CXXFLAGS="$CXXFLAGS $SDL_CFLAGS" LIBS="$LIBS $SDL_LIBS" AC_TRY_LINK([ #include <stdio.h> #include "SDL.h" int main(int argc, char *argv[]) { return 0; } #undef main #define main K_and_R_C_main ], [ return 0; ], [ echo "*** The test program compiled, but did not run. This usually means" echo "*** that the run-time linker is not finding SDL or finding the wrong" echo "*** version of SDL. If it is not finding SDL, you'll need to set your" echo "*** LD_LIBRARY_PATH environment variable, or edit /etc/ld.so.conf to point" echo "*** to the installed location Also, make sure you have run ldconfig if that" echo "*** is required on your system" echo "***" echo "*** If you have an old version installed, it is best to remove it, although" echo "*** you may also be able to get things to work by modifying LD_LIBRARY_PATH"], [ echo "*** The test program failed to compile or link. See the file config.log for the" echo "*** exact error that occured. This usually means SDL was incorrectly installed" echo "*** or that you have moved SDL since it was installed. In the latter case, you" echo "*** may want to edit the sdl2-config script: $SDL2_CONFIG" ]) CFLAGS="$ac_save_CFLAGS" CXXFLAGS="$ac_save_CXXFLAGS" LIBS="$ac_save_LIBS" fi fi SDL_CFLAGS="" SDL_LIBS="" ifelse([$3], , :, [$3]) fi AC_SUBST(SDL_CFLAGS) AC_SUBST(SDL_LIBS) rm -f conf.sdltest ])
YifuLiu/AliOS-Things
components/SDL2/sdl2.m4
M4Sugar
apache-2.0
8,093
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if defined(__WIN32__) #include "core/windows/SDL_windows.h" #elif defined(__OS2__) #include <stdlib.h> /* For _exit() */ #elif !defined(__WINRT__) #include <unistd.h> /* For _exit(), etc. */ #endif #if defined(__EMSCRIPTEN__) #include <emscripten.h> #endif /* Initialization code for SDL */ #include "SDL.h" #include "SDL_bits.h" #include "SDL_revision.h" #include "SDL_assert_c.h" #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 # include "timer/SDL_timer_c.h" #endif #if SDL_VIDEO_DRIVER_WINDOWS extern int SDL_HelperWindowCreate(void); extern int SDL_HelperWindowDestroy(void); #endif /* This is not declared in any header, although it is shared between some parts of SDL, because we don't want anything calling it without an extremely good reason. */ extern SDL_NORETURN void SDL_ExitProcess(int exitcode); 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); /* MingW doesn't have TerminateProcess marked as noreturn, so add an ExitProcess here that will never be reached but make MingW happy. */ ExitProcess(exitcode); #elif defined(__EMSCRIPTEN__) emscripten_cancel_main_loop(); /* this should "kill" the app. */ emscripten_force_exit(exitcode); /* this should "kill" the app. */ exit(exitcode); #elif defined(__HAIKU__) /* Haiku has _Exit, but it's not marked noreturn. */ _exit(exitcode); #elif defined(HAVE__EXIT) /* Upper case _Exit() */ _Exit(exitcode); #else _exit(exitcode); #endif } /* The initialized subsystems */ #ifdef SDL_MAIN_NEEDED static SDL_bool SDL_MainIsReady = SDL_FALSE; #else static SDL_bool SDL_MainIsReady = SDL_TRUE; #endif static SDL_bool SDL_bInMainQuit = SDL_FALSE; static Uint8 SDL_SubsystemRefCount[ 32 ]; /* Private helper to increment a subsystem's ref counter. */ static void SDL_PrivateSubsystemRefCountIncr(Uint32 subsystem) { int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); SDL_assert(SDL_SubsystemRefCount[subsystem_index] < 255); ++SDL_SubsystemRefCount[subsystem_index]; } /* Private helper to decrement a subsystem's ref counter. */ static void SDL_PrivateSubsystemRefCountDecr(Uint32 subsystem) { int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); if (SDL_SubsystemRefCount[subsystem_index] > 0) { --SDL_SubsystemRefCount[subsystem_index]; } } /* Private helper to check if a system needs init. */ static SDL_bool SDL_PrivateShouldInitSubsystem(Uint32 subsystem) { int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); SDL_assert(SDL_SubsystemRefCount[subsystem_index] < 255); return (SDL_SubsystemRefCount[subsystem_index] == 0) ? SDL_TRUE : SDL_FALSE; } /* Private helper to check if a system needs to be quit. */ static SDL_bool SDL_PrivateShouldQuitSubsystem(Uint32 subsystem) { int subsystem_index = SDL_MostSignificantBitIndex32(subsystem); if (SDL_SubsystemRefCount[subsystem_index] == 0) { return SDL_FALSE; } /* If we're in SDL_Quit, we shut down every subsystem, even if refcount * isn't zero. */ return (SDL_SubsystemRefCount[subsystem_index] == 1 || SDL_bInMainQuit) ? SDL_TRUE : SDL_FALSE; } void SDL_SetMainReady(void) { SDL_MainIsReady = SDL_TRUE; } int SDL_InitSubSystem(Uint32 flags) { if (!SDL_MainIsReady) { SDL_SetError("Application didn't initialize properly, did you include SDL_main.h in the file containing your main() function?"); return -1; } /* Clear the error message */ SDL_ClearError(); if ((flags & SDL_INIT_GAMECONTROLLER)) { /* game controller implies joystick */ flags |= SDL_INIT_JOYSTICK; } if ((flags & (SDL_INIT_VIDEO|SDL_INIT_JOYSTICK))) { /* video or joystick implies events */ flags |= SDL_INIT_EVENTS; } #if SDL_VIDEO_DRIVER_WINDOWS if ((flags & (SDL_INIT_HAPTIC|SDL_INIT_JOYSTICK))) { if (SDL_HelperWindowCreate() < 0) { return -1; } } #endif #if !SDL_TIMERS_DISABLED SDL_TicksInit(); #endif /* Initialize the event subsystem */ if ((flags & SDL_INIT_EVENTS)) { #if !SDL_EVENTS_DISABLED if (SDL_PrivateShouldInitSubsystem(SDL_INIT_EVENTS)) { if (SDL_EventsInit() < 0) { return (-1); } } SDL_PrivateSubsystemRefCountIncr(SDL_INIT_EVENTS); #else return SDL_SetError("SDL not built with events support"); #endif } /* Initialize the timer subsystem */ if ((flags & SDL_INIT_TIMER)){ #if !SDL_TIMERS_DISABLED if (SDL_PrivateShouldInitSubsystem(SDL_INIT_TIMER)) { if (SDL_TimerInit() < 0) { return (-1); } } SDL_PrivateSubsystemRefCountIncr(SDL_INIT_TIMER); #else return SDL_SetError("SDL not built with timer support"); #endif } /* Initialize the video subsystem */ if ((flags & SDL_INIT_VIDEO)){ #if !SDL_VIDEO_DISABLED if (SDL_PrivateShouldInitSubsystem(SDL_INIT_VIDEO)) { if (SDL_VideoInit(NULL) < 0) { return (-1); } } SDL_PrivateSubsystemRefCountIncr(SDL_INIT_VIDEO); #else return SDL_SetError("SDL not built with video support"); #endif } /* Initialize the audio subsystem */ if ((flags & SDL_INIT_AUDIO)){ #if !SDL_AUDIO_DISABLED if (SDL_PrivateShouldInitSubsystem(SDL_INIT_AUDIO)) { if (SDL_AudioInit(NULL) < 0) { return (-1); } } SDL_PrivateSubsystemRefCountIncr(SDL_INIT_AUDIO); #else return SDL_SetError("SDL not built with audio support"); #endif } /* Initialize the joystick subsystem */ if ((flags & SDL_INIT_JOYSTICK)){ #if !SDL_JOYSTICK_DISABLED if (SDL_PrivateShouldInitSubsystem(SDL_INIT_JOYSTICK)) { if (SDL_JoystickInit() < 0) { return (-1); } } SDL_PrivateSubsystemRefCountIncr(SDL_INIT_JOYSTICK); #else return SDL_SetError("SDL not built with joystick support"); #endif } if ((flags & SDL_INIT_GAMECONTROLLER)){ #if !SDL_JOYSTICK_DISABLED if (SDL_PrivateShouldInitSubsystem(SDL_INIT_GAMECONTROLLER)) { if (SDL_GameControllerInit() < 0) { return (-1); } } SDL_PrivateSubsystemRefCountIncr(SDL_INIT_GAMECONTROLLER); #else return SDL_SetError("SDL not built with joystick support"); #endif } /* Initialize the haptic subsystem */ if ((flags & SDL_INIT_HAPTIC)){ #if !SDL_HAPTIC_DISABLED if (SDL_PrivateShouldInitSubsystem(SDL_INIT_HAPTIC)) { if (SDL_HapticInit() < 0) { return (-1); } } SDL_PrivateSubsystemRefCountIncr(SDL_INIT_HAPTIC); #else return SDL_SetError("SDL not built with haptic (force feedback) support"); #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); } int SDL_Init(Uint32 flags) { return SDL_InitSubSystem(flags); } 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 */ flags |= SDL_INIT_JOYSTICK; if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_GAMECONTROLLER)) { SDL_GameControllerQuit(); } SDL_PrivateSubsystemRefCountDecr(SDL_INIT_GAMECONTROLLER); } if ((flags & SDL_INIT_JOYSTICK)) { /* joystick implies events */ flags |= SDL_INIT_EVENTS; if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_JOYSTICK)) { SDL_JoystickQuit(); } SDL_PrivateSubsystemRefCountDecr(SDL_INIT_JOYSTICK); } #endif #if !SDL_HAPTIC_DISABLED if ((flags & SDL_INIT_HAPTIC)) { if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_HAPTIC)) { SDL_HapticQuit(); } SDL_PrivateSubsystemRefCountDecr(SDL_INIT_HAPTIC); } #endif #if !SDL_AUDIO_DISABLED if ((flags & SDL_INIT_AUDIO)) { if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_AUDIO)) { SDL_AudioQuit(); } SDL_PrivateSubsystemRefCountDecr(SDL_INIT_AUDIO); } #endif #if !SDL_VIDEO_DISABLED if ((flags & SDL_INIT_VIDEO)) { /* video implies events */ flags |= SDL_INIT_EVENTS; if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_VIDEO)) { SDL_VideoQuit(); } SDL_PrivateSubsystemRefCountDecr(SDL_INIT_VIDEO); } #endif #if !SDL_TIMERS_DISABLED if ((flags & SDL_INIT_TIMER)) { if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_TIMER)) { SDL_TimerQuit(); } SDL_PrivateSubsystemRefCountDecr(SDL_INIT_TIMER); } #endif #if !SDL_EVENTS_DISABLED if ((flags & SDL_INIT_EVENTS)) { if (SDL_PrivateShouldQuitSubsystem(SDL_INIT_EVENTS)) { SDL_EventsQuit(); } SDL_PrivateSubsystemRefCountDecr(SDL_INIT_EVENTS); } #endif } Uint32 SDL_WasInit(Uint32 flags) { int i; int num_subsystems = SDL_arraysize(SDL_SubsystemRefCount); Uint32 initialized = 0; /* Fast path for checking one flag */ if (SDL_HasExactlyOneBitSet32(flags)) { int subsystem_index = SDL_MostSignificantBitIndex32(flags); return SDL_SubsystemRefCount[subsystem_index] ? flags : 0; } if (!flags) { flags = SDL_INIT_EVERYTHING; } num_subsystems = SDL_min(num_subsystems, SDL_MostSignificantBitIndex32(flags) + 1); /* Iterate over each bit in flags, and check the matching subsystem. */ for (i = 0; i < num_subsystems; ++i) { if ((flags & 1) && SDL_SubsystemRefCount[i] > 0) { initialized |= (1 << i); } flags >>= 1; } return initialized; } void SDL_Quit(void) { SDL_bInMainQuit = SDL_TRUE; /* Quit all subsystems */ #if SDL_VIDEO_DRIVER_WINDOWS SDL_HelperWindowDestroy(); #endif SDL_QuitSubSystem(SDL_INIT_EVERYTHING); #if !SDL_TIMERS_DISABLED SDL_TicksQuit(); #endif SDL_ClearHints(); SDL_AssertionsQuit(); SDL_LogResetPriorities(); /* Now that every subsystem has been quit, we reset the subsystem refcount * and the list of initialized subsystems. */ SDL_memset( SDL_SubsystemRefCount, 0x0, sizeof(SDL_SubsystemRefCount) ); SDL_bInMainQuit = SDL_FALSE; } /* Get the library version number */ void SDL_GetVersion(SDL_version * ver) { SDL_VERSION(ver); } /* Get the library source revision */ const char * SDL_GetRevision(void) { return SDL_REVISION; } /* Get the library source revision number */ int SDL_GetRevisionNumber(void) { return SDL_REVISION_NUMBER; } /* Get the name of the platform */ const char * SDL_GetPlatform() { #if __AIX__ return "AIX"; #elif __ANDROID__ return "Android"; #elif __BSDI__ return "BSDI"; #elif __DREAMCAST__ return "Dreamcast"; #elif __EMSCRIPTEN__ return "Emscripten"; #elif __FREEBSD__ return "FreeBSD"; #elif __HAIKU__ return "Haiku"; #elif __HPUX__ return "HP-UX"; #elif __IRIX__ return "Irix"; #elif __LINUX__ return "Linux"; #elif __MINT__ return "Atari MiNT"; #elif __MACOS__ return "MacOS Classic"; #elif __MACOSX__ return "Mac OS X"; #elif __NACL__ return "NaCl"; #elif __NETBSD__ return "NetBSD"; #elif __OPENBSD__ return "OpenBSD"; #elif __OS2__ return "OS/2"; #elif __OSF__ return "OSF/1"; #elif __QNXNTO__ return "QNX Neutrino"; #elif __RISCOS__ return "RISC OS"; #elif __SOLARIS__ return "Solaris"; #elif __WIN32__ return "Windows"; #elif __WINRT__ return "WinRT"; #elif __TVOS__ return "tvOS"; #elif __IPHONEOS__ return "iOS"; #elif __PSP__ return "PlayStation Portable"; #else return "Unknown (see SDL_platform.h)"; #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) /* Need to include DllMain() on Watcom C for some reason.. */ BOOL APIENTRY _DllMainCRTStartup(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif /* Building DLL */ #endif /* __WIN32__ */ /* vi: set sts=4 ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL.c
C
apache-2.0
14,578
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if defined(__WIN32__) #include "core/windows/SDL_windows.h" #endif #include "SDL.h" #include "SDL_atomic.h" #include "SDL_messagebox.h" #include "SDL_video.h" #include "SDL_assert.h" #include "SDL_assert_c.h" #include "video/SDL_sysvideo.h" #ifdef __WIN32__ #ifndef WS_OVERLAPPEDWINDOW #define WS_OVERLAPPEDWINDOW 0 #endif #else /* fprintf, etc. */ #include <stdio.h> #include <stdlib.h> #endif #if defined(__EMSCRIPTEN__) #include <emscripten.h> #endif static SDL_assert_state SDLCALL SDL_PromptAssertion(const SDL_assert_data *data, void *userdata); /* * We keep all triggered assertions in a singly-linked list so we can * generate a report later. */ static SDL_assert_data *triggered_assertions = NULL; #ifndef SDL_THREADS_DISABLED static SDL_mutex *assertion_mutex = NULL; #endif static SDL_AssertionHandler assertion_handler = SDL_PromptAssertion; static void *assertion_userdata = NULL; #ifdef __GNUC__ static void debug_print(const char *fmt, ...) __attribute__((format (printf, 1, 2))); #endif static void debug_print(const char *fmt, ...) { va_list ap; va_start(ap, fmt); SDL_LogMessageV(SDL_LOG_CATEGORY_ASSERT, SDL_LOG_PRIORITY_WARN, fmt, ap); va_end(ap); } static void SDL_AddAssertionToReport(SDL_assert_data *data) { /* (data) is always a static struct defined with the assert macros, so we don't have to worry about copying or allocating them. */ data->trigger_count++; if (data->trigger_count == 1) { /* not yet added? */ data->next = triggered_assertions; triggered_assertions = data; } } static void SDL_GenerateAssertionReport(void) { const SDL_assert_data *item = triggered_assertions; /* only do this if the app hasn't assigned an assertion handler. */ if ((item != NULL) && (assertion_handler != SDL_PromptAssertion)) { debug_print("\n\nSDL assertion report.\n"); debug_print("All SDL assertions between last init/quit:\n\n"); while (item != NULL) { debug_print( "'%s'\n" " * %s (%s:%d)\n" " * triggered %u time%s.\n" " * always ignore: %s.\n", item->condition, item->function, item->filename, item->linenum, item->trigger_count, (item->trigger_count == 1) ? "" : "s", item->always_ignore ? "yes" : "no"); item = item->next; } debug_print("\n"); SDL_ResetAssertionReport(); } } /* This is not declared in any header, although it is shared between some parts of SDL, because we don't want anything calling it without an extremely good reason. */ #if defined(__WATCOMC__) extern void SDL_ExitProcess(int exitcode); #pragma aux SDL_ExitProcess aborts; #endif extern SDL_NORETURN void SDL_ExitProcess(int exitcode); #if defined(__WATCOMC__) static void SDL_AbortAssertion (void); #pragma aux SDL_AbortAssertion aborts; #endif static SDL_NORETURN void SDL_AbortAssertion(void) { SDL_Quit(); SDL_ExitProcess(42); } static SDL_assert_state SDLCALL SDL_PromptAssertion(const SDL_assert_data *data, void *userdata) { #ifdef __WIN32__ #define ENDLINE "\r\n" #else #define ENDLINE "\n" #endif const char *envr; SDL_assert_state state = SDL_ASSERTION_ABORT; SDL_Window *window; SDL_MessageBoxData messagebox; SDL_MessageBoxButtonData buttons[] = { { 0, SDL_ASSERTION_RETRY, "Retry" }, { 0, SDL_ASSERTION_BREAK, "Break" }, { 0, SDL_ASSERTION_ABORT, "Abort" }, { SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT, SDL_ASSERTION_IGNORE, "Ignore" }, { SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT, SDL_ASSERTION_ALWAYS_IGNORE, "Always Ignore" } }; char *message; int selected; (void) userdata; /* unused in default handler. */ /* !!! FIXME: why is this using SDL_stack_alloc and not just "char message[SDL_MAX_LOG_MESSAGE];" ? */ message = SDL_stack_alloc(char, SDL_MAX_LOG_MESSAGE); if (!message) { /* Uh oh, we're in real trouble now... */ return SDL_ASSERTION_ABORT; } SDL_snprintf(message, SDL_MAX_LOG_MESSAGE, "Assertion failure at %s (%s:%d), triggered %u %s:" ENDLINE " '%s'", data->function, data->filename, data->linenum, data->trigger_count, (data->trigger_count == 1) ? "time" : "times", data->condition); debug_print("\n\n%s\n\n", message); /* let env. variable override, so unit tests won't block in a GUI. */ envr = SDL_getenv("SDL_ASSERT"); if (envr != NULL) { SDL_stack_free(message); if (SDL_strcmp(envr, "abort") == 0) { return SDL_ASSERTION_ABORT; } else if (SDL_strcmp(envr, "break") == 0) { return SDL_ASSERTION_BREAK; } else if (SDL_strcmp(envr, "retry") == 0) { return SDL_ASSERTION_RETRY; } else if (SDL_strcmp(envr, "ignore") == 0) { return SDL_ASSERTION_IGNORE; } else if (SDL_strcmp(envr, "always_ignore") == 0) { return SDL_ASSERTION_ALWAYS_IGNORE; } else { return SDL_ASSERTION_ABORT; /* oh well. */ } } /* Leave fullscreen mode, if possible (scary!) */ window = SDL_GetFocusWindow(); if (window) { if (SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN) { SDL_MinimizeWindow(window); } else { /* !!! FIXME: ungrab the input if we're not fullscreen? */ /* No need to mess with the window */ window = NULL; } } /* Show a messagebox if we can, otherwise fall back to stdio */ SDL_zero(messagebox); messagebox.flags = SDL_MESSAGEBOX_WARNING; messagebox.window = window; messagebox.title = "Assertion Failed"; messagebox.message = message; messagebox.numbuttons = SDL_arraysize(buttons); messagebox.buttons = buttons; if (SDL_ShowMessageBox(&messagebox, &selected) == 0) { if (selected == -1) { state = SDL_ASSERTION_IGNORE; } else { state = (SDL_assert_state)selected; } } else { #if defined(__EMSCRIPTEN__) /* This is nasty, but we can't block on a custom UI. */ for ( ; ; ) { SDL_bool okay = SDL_TRUE; char *buf = (char *) EM_ASM_INT({ var str = UTF8ToString($0) + '\n\n' + 'Abort/Retry/Ignore/AlwaysIgnore? [ariA] :'; var reply = window.prompt(str, "i"); if (reply === null) { reply = "i"; } return allocate(intArrayFromString(reply), 'i8', ALLOC_NORMAL); }, message); if (SDL_strcmp(buf, "a") == 0) { state = SDL_ASSERTION_ABORT; /* (currently) no break functionality on Emscripten } else if (SDL_strcmp(buf, "b") == 0) { state = SDL_ASSERTION_BREAK; */ } else if (SDL_strcmp(buf, "r") == 0) { state = SDL_ASSERTION_RETRY; } else if (SDL_strcmp(buf, "i") == 0) { state = SDL_ASSERTION_IGNORE; } else if (SDL_strcmp(buf, "A") == 0) { state = SDL_ASSERTION_ALWAYS_IGNORE; } else { okay = SDL_FALSE; } free(buf); if (okay) { break; } } #elif defined(HAVE_STDIO_H) /* this is a little hacky. */ for ( ; ; ) { char buf[32]; fprintf(stderr, "Abort/Break/Retry/Ignore/AlwaysIgnore? [abriA] : "); fflush(stderr); if (fgets(buf, sizeof (buf), stdin) == NULL) { break; } if (SDL_strncmp(buf, "a", 1) == 0) { state = SDL_ASSERTION_ABORT; break; } else if (SDL_strncmp(buf, "b", 1) == 0) { state = SDL_ASSERTION_BREAK; break; } else if (SDL_strncmp(buf, "r", 1) == 0) { state = SDL_ASSERTION_RETRY; break; } else if (SDL_strncmp(buf, "i", 1) == 0) { state = SDL_ASSERTION_IGNORE; break; } else if (SDL_strncmp(buf, "A", 1) == 0) { state = SDL_ASSERTION_ALWAYS_IGNORE; break; } } #endif /* HAVE_STDIO_H */ } /* Re-enter fullscreen mode */ if (window) { SDL_RestoreWindow(window); } SDL_stack_free(message); return state; } SDL_assert_state SDL_ReportAssertion(SDL_assert_data *data, const char *func, const char *file, int line) { SDL_assert_state state = SDL_ASSERTION_IGNORE; static int assertion_running = 0; #ifndef SDL_THREADS_DISABLED static SDL_SpinLock spinlock = 0; SDL_AtomicLock(&spinlock); if (assertion_mutex == NULL) { /* never called SDL_Init()? */ assertion_mutex = SDL_CreateMutex(); if (assertion_mutex == NULL) { SDL_AtomicUnlock(&spinlock); return SDL_ASSERTION_IGNORE; /* oh well, I guess. */ } } SDL_AtomicUnlock(&spinlock); if (SDL_LockMutex(assertion_mutex) < 0) { return SDL_ASSERTION_IGNORE; /* oh well, I guess. */ } #endif /* doing this because Visual C is upset over assigning in the macro. */ if (data->trigger_count == 0) { data->function = func; data->filename = file; data->linenum = line; } SDL_AddAssertionToReport(data); assertion_running++; if (assertion_running > 1) { /* assert during assert! Abort. */ if (assertion_running == 2) { SDL_AbortAssertion(); } else if (assertion_running == 3) { /* Abort asserted! */ SDL_ExitProcess(42); } else { while (1) { /* do nothing but spin; what else can you do?! */ } } } if (!data->always_ignore) { state = assertion_handler(data, assertion_userdata); } switch (state) { case SDL_ASSERTION_ALWAYS_IGNORE: state = SDL_ASSERTION_IGNORE; data->always_ignore = 1; break; case SDL_ASSERTION_IGNORE: case SDL_ASSERTION_RETRY: case SDL_ASSERTION_BREAK: break; /* macro handles these. */ case SDL_ASSERTION_ABORT: SDL_AbortAssertion(); /*break; ...shouldn't return, but oh well. */ } assertion_running--; #ifndef SDL_THREADS_DISABLED SDL_UnlockMutex(assertion_mutex); #endif return state; } void SDL_AssertionsQuit(void) { SDL_GenerateAssertionReport(); #ifndef SDL_THREADS_DISABLED if (assertion_mutex != NULL) { SDL_DestroyMutex(assertion_mutex); assertion_mutex = NULL; } #endif } void SDL_SetAssertionHandler(SDL_AssertionHandler handler, void *userdata) { if (handler != NULL) { assertion_handler = handler; assertion_userdata = userdata; } else { assertion_handler = SDL_PromptAssertion; assertion_userdata = NULL; } } const SDL_assert_data *SDL_GetAssertionReport(void) { return triggered_assertions; } void SDL_ResetAssertionReport(void) { SDL_assert_data *next = NULL; SDL_assert_data *item; for (item = triggered_assertions; item != NULL; item = next) { next = (SDL_assert_data *) item->next; item->always_ignore = SDL_FALSE; item->trigger_count = 0; item->next = NULL; } triggered_assertions = NULL; } SDL_AssertionHandler SDL_GetDefaultAssertionHandler(void) { return SDL_PromptAssertion; } SDL_AssertionHandler SDL_GetAssertionHandler(void **userdata) { if (userdata != NULL) { *userdata = assertion_userdata; } return assertion_handler; } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL_assert.c
C
apache-2.0
12,997
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ #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: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL_assert_c.h
C
apache-2.0
1,093
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #include "SDL.h" #include "./SDL_dataqueue.h" #include "SDL_assert.h" typedef struct SDL_DataQueuePacket { size_t datalen; /* bytes currently in use in this packet. */ size_t startpos; /* bytes currently consumed in this packet. */ struct SDL_DataQueuePacket *next; /* next item in linked list. */ Uint8 data[SDL_VARIABLE_LENGTH_ARRAY]; /* packet data */ } SDL_DataQueuePacket; struct SDL_DataQueue { SDL_DataQueuePacket *head; /* device fed from here. */ SDL_DataQueuePacket *tail; /* queue fills to here. */ SDL_DataQueuePacket *pool; /* these are unused packets. */ size_t packet_size; /* size of new packets */ size_t queued_bytes; /* number of bytes of data in the queue. */ }; static void SDL_FreeDataQueueList(SDL_DataQueuePacket *packet) { while (packet) { SDL_DataQueuePacket *next = packet->next; SDL_free(packet); packet = next; } } /* this all expects that you managed thread safety elsewhere. */ SDL_DataQueue * SDL_NewDataQueue(const size_t _packetlen, const size_t initialslack) { SDL_DataQueue *queue = (SDL_DataQueue *) SDL_malloc(sizeof (SDL_DataQueue)); if (!queue) { SDL_OutOfMemory(); return NULL; } else { const size_t packetlen = _packetlen ? _packetlen : 1024; const size_t wantpackets = (initialslack + (packetlen - 1)) / packetlen; size_t i; SDL_zerop(queue); queue->packet_size = packetlen; for (i = 0; i < wantpackets; i++) { SDL_DataQueuePacket *packet = (SDL_DataQueuePacket *) SDL_malloc(sizeof (SDL_DataQueuePacket) + packetlen); if (packet) { /* don't care if this fails, we'll deal later. */ packet->datalen = 0; packet->startpos = 0; packet->next = queue->pool; queue->pool = packet; } } } return queue; } void SDL_FreeDataQueue(SDL_DataQueue *queue) { if (queue) { SDL_FreeDataQueueList(queue->head); SDL_FreeDataQueueList(queue->pool); SDL_free(queue); } } void SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack) { const size_t packet_size = queue ? queue->packet_size : 1; const size_t slackpackets = (slack + (packet_size-1)) / packet_size; SDL_DataQueuePacket *packet; SDL_DataQueuePacket *prev = NULL; size_t i; if (!queue) { return; } packet = queue->head; /* merge the available pool and the current queue into one list. */ if (packet) { queue->tail->next = queue->pool; } else { packet = queue->pool; } /* Remove the queued packets from the device. */ queue->tail = NULL; queue->head = NULL; queue->queued_bytes = 0; queue->pool = packet; /* Optionally keep some slack in the pool to reduce malloc pressure. */ for (i = 0; packet && (i < slackpackets); i++) { prev = packet; packet = packet->next; } if (prev) { prev->next = NULL; } else { queue->pool = NULL; } SDL_FreeDataQueueList(packet); /* free extra packets */ } static SDL_DataQueuePacket * AllocateDataQueuePacket(SDL_DataQueue *queue) { SDL_DataQueuePacket *packet; SDL_assert(queue != NULL); packet = queue->pool; if (packet != NULL) { /* we have one available in the pool. */ queue->pool = packet->next; } else { /* Have to allocate a new one! */ packet = (SDL_DataQueuePacket *) SDL_malloc(sizeof (SDL_DataQueuePacket) + queue->packet_size); if (packet == NULL) { return NULL; } } packet->datalen = 0; packet->startpos = 0; packet->next = NULL; SDL_assert((queue->head != NULL) == (queue->queued_bytes != 0)); if (queue->tail == NULL) { queue->head = packet; } else { queue->tail->next = packet; } queue->tail = packet; return packet; } int SDL_WriteToDataQueue(SDL_DataQueue *queue, const void *_data, const size_t _len) { size_t len = _len; const Uint8 *data = (const Uint8 *) _data; const size_t packet_size = queue ? queue->packet_size : 0; SDL_DataQueuePacket *orighead; SDL_DataQueuePacket *origtail; size_t origlen; size_t datalen; if (!queue) { return SDL_InvalidParamError("queue"); } orighead = queue->head; origtail = queue->tail; origlen = origtail ? origtail->datalen : 0; while (len > 0) { SDL_DataQueuePacket *packet = queue->tail; SDL_assert(!packet || (packet->datalen <= packet_size)); if (!packet || (packet->datalen >= packet_size)) { /* tail packet missing or completely full; we need a new packet. */ packet = AllocateDataQueuePacket(queue); if (!packet) { /* uhoh, reset so we've queued nothing new, free what we can. */ if (!origtail) { packet = queue->head; /* whole queue. */ } else { packet = origtail->next; /* what we added to existing queue. */ origtail->next = NULL; origtail->datalen = origlen; } queue->head = orighead; queue->tail = origtail; queue->pool = NULL; SDL_FreeDataQueueList(packet); /* give back what we can. */ return SDL_OutOfMemory(); } } datalen = SDL_min(len, packet_size - packet->datalen); SDL_memcpy(packet->data + packet->datalen, data, datalen); data += datalen; len -= datalen; packet->datalen += datalen; queue->queued_bytes += datalen; } return 0; } size_t SDL_PeekIntoDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len) { size_t len = _len; Uint8 *buf = (Uint8 *) _buf; Uint8 *ptr = buf; SDL_DataQueuePacket *packet; if (!queue) { return 0; } for (packet = queue->head; len && packet; packet = packet->next) { const size_t avail = packet->datalen - packet->startpos; const size_t cpy = SDL_min(len, avail); SDL_assert(queue->queued_bytes >= avail); SDL_memcpy(ptr, packet->data + packet->startpos, cpy); ptr += cpy; len -= cpy; } return (size_t) (ptr - buf); } size_t SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *_buf, const size_t _len) { size_t len = _len; Uint8 *buf = (Uint8 *) _buf; Uint8 *ptr = buf; SDL_DataQueuePacket *packet; if (!queue) { return 0; } while ((len > 0) && ((packet = queue->head) != NULL)) { const size_t avail = packet->datalen - packet->startpos; const size_t cpy = SDL_min(len, avail); SDL_assert(queue->queued_bytes >= avail); SDL_memcpy(ptr, packet->data + packet->startpos, cpy); packet->startpos += cpy; ptr += cpy; queue->queued_bytes -= cpy; len -= cpy; if (packet->startpos == packet->datalen) { /* packet is done, put it in the pool. */ queue->head = packet->next; SDL_assert((packet->next != NULL) || (packet == queue->tail)); packet->next = queue->pool; queue->pool = packet; } } SDL_assert((queue->head != NULL) == (queue->queued_bytes != 0)); if (queue->head == NULL) { queue->tail = NULL; /* in case we drained the queue entirely. */ } return (size_t) (ptr - buf); } size_t SDL_CountDataQueue(SDL_DataQueue *queue) { return queue ? queue->queued_bytes : 0; } void * SDL_ReserveSpaceInDataQueue(SDL_DataQueue *queue, const size_t len) { SDL_DataQueuePacket *packet; if (!queue) { SDL_InvalidParamError("queue"); return NULL; } else if (len == 0) { SDL_InvalidParamError("len"); return NULL; } else if (len > queue->packet_size) { SDL_SetError("len is larger than packet size"); return NULL; } packet = queue->head; if (packet) { const size_t avail = queue->packet_size - packet->datalen; if (len <= avail) { /* we can use the space at end of this packet. */ void *retval = packet->data + packet->datalen; packet->datalen += len; queue->queued_bytes += len; return retval; } } /* Need a fresh packet. */ packet = AllocateDataQueuePacket(queue); if (!packet) { SDL_OutOfMemory(); return NULL; } packet->datalen = len; queue->queued_bytes += len; return packet->data; } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL_dataqueue.c
C
apache-2.0
9,669
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ #ifndef SDL_dataqueue_h_ #define SDL_dataqueue_h_ /* this is not (currently) a public API. But maybe it should be! */ struct SDL_DataQueue; typedef struct SDL_DataQueue SDL_DataQueue; SDL_DataQueue *SDL_NewDataQueue(const size_t packetlen, const size_t initialslack); void SDL_FreeDataQueue(SDL_DataQueue *queue); void SDL_ClearDataQueue(SDL_DataQueue *queue, const size_t slack); int SDL_WriteToDataQueue(SDL_DataQueue *queue, const void *data, const size_t len); size_t SDL_ReadFromDataQueue(SDL_DataQueue *queue, void *buf, const size_t len); size_t SDL_PeekIntoDataQueue(SDL_DataQueue *queue, void *buf, const size_t len); size_t SDL_CountDataQueue(SDL_DataQueue *queue); /* this sets a section of the data queue aside (possibly allocating memory for it) as if it's been written to, but returns a pointer to that space. You may write to this space until a read would consume it. Writes (and other calls to this function) will safely append their data after this reserved space and can be in flight at the same time. There is no thread safety. If there isn't an existing block of memory that can contain the reserved space, one will be allocated for it. You can not (currently) allocate a space larger than the packetlen requested in SDL_NewDataQueue. Returned buffer is uninitialized. This lets you avoid an extra copy in some cases, but it's safer to use SDL_WriteToDataQueue() unless you know what you're doing. Returns pointer to buffer of at least (len) bytes, NULL on error. */ void *SDL_ReserveSpaceInDataQueue(SDL_DataQueue *queue, const size_t len); #endif /* SDL_dataqueue_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL_dataqueue.h
C
apache-2.0
2,606
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" /* Simple error handling in SDL */ #include "SDL_error.h" #include "SDL_error_c.h" #define SDL_ERRBUFIZE 1024 int SDL_SetError(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { /* Ignore call if invalid format pointer was passed */ if (fmt != NULL) { va_list ap; SDL_error *error = SDL_GetErrBuf(); error->error = 1; /* mark error as valid */ va_start(ap, fmt); SDL_vsnprintf(error->str, ERR_MAX_STRLEN, fmt, ap); va_end(ap); if (SDL_LogGetPriority(SDL_LOG_CATEGORY_ERROR) <= SDL_LOG_PRIORITY_DEBUG) { /* If we are in debug mode, print out the error message */ SDL_LogDebug(SDL_LOG_CATEGORY_ERROR, "%s", error->str); } } return -1; } /* Available for backwards compatibility */ const char * SDL_GetError(void) { const SDL_error *error = SDL_GetErrBuf(); return error->error ? error->str : ""; } void SDL_ClearError(void) { SDL_GetErrBuf()->error = 0; } /* Very common errors go here */ int SDL_Error(SDL_errorcode code) { switch (code) { case SDL_ENOMEM: return SDL_SetError("Out of memory"); case SDL_EFREAD: return SDL_SetError("Error reading from datastream"); case SDL_EFWRITE: return SDL_SetError("Error writing to datastream"); case SDL_EFSEEK: return SDL_SetError("Error seeking in datastream"); case SDL_UNSUPPORTED: return SDL_SetError("That operation is not supported"); default: return SDL_SetError("Unknown SDL error"); } } #ifdef TEST_ERROR int main(int argc, char *argv[]) { char buffer[BUFSIZ + 1]; SDL_SetError("Hi there!"); printf("Error 1: %s\n", SDL_GetError()); SDL_ClearError(); SDL_memset(buffer, '1', BUFSIZ); buffer[BUFSIZ] = 0; SDL_SetError("This is the error: %s (%f)", buffer, 1.0); printf("Error 2: %s\n", SDL_GetError()); exit(0); } #endif char * SDL_GetErrorMsg(char *errstr, int maxlen) { const SDL_error *error = SDL_GetErrBuf(); if (error->error) { SDL_strlcpy(errstr, error->str, maxlen); } else { *errstr = '\0'; } return errstr; } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL_error.c
C
apache-2.0
3,157
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" /* This file defines a structure that carries language-independent error messages */ #ifndef SDL_error_c_h_ #define SDL_error_c_h_ #define ERR_MAX_STRLEN 128 typedef struct SDL_error { int error; /* This is a numeric value corresponding to the current error */ char str[ERR_MAX_STRLEN]; } SDL_error; /* Defined in SDL_thread.c */ extern SDL_error *SDL_GetErrBuf(void); #endif /* SDL_error_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL_error_c.h
C
apache-2.0
1,418
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #include "SDL_hints.h" #include "SDL_error.h" #include "SDL_hints_c.h" /* Assuming there aren't many hints set and they aren't being queried in critical performance paths, we'll just use linked lists here. */ typedef struct SDL_HintWatch { SDL_HintCallback callback; void *userdata; struct SDL_HintWatch *next; } SDL_HintWatch; typedef struct SDL_Hint { char *name; char *value; SDL_HintPriority priority; SDL_HintWatch *callbacks; struct SDL_Hint *next; } SDL_Hint; static SDL_Hint *SDL_hints; SDL_bool SDL_SetHintWithPriority(const char *name, const char *value, SDL_HintPriority priority) { const char *env; SDL_Hint *hint; SDL_HintWatch *entry; if (!name || !value) { return SDL_FALSE; } env = SDL_getenv(name); if (env && priority < SDL_HINT_OVERRIDE) { return SDL_FALSE; } for (hint = SDL_hints; hint; hint = hint->next) { if (SDL_strcmp(name, hint->name) == 0) { if (priority < hint->priority) { return SDL_FALSE; } if (!hint->value || !value || SDL_strcmp(hint->value, value) != 0) { for (entry = hint->callbacks; entry; ) { /* Save the next entry in case this one is deleted */ SDL_HintWatch *next = entry->next; entry->callback(entry->userdata, name, hint->value, value); entry = next; } SDL_free(hint->value); hint->value = value ? SDL_strdup(value) : NULL; } hint->priority = priority; return SDL_TRUE; } } /* Couldn't find the hint, add a new one */ hint = (SDL_Hint *)SDL_malloc(sizeof(*hint)); if (!hint) { return SDL_FALSE; } hint->name = SDL_strdup(name); hint->value = value ? SDL_strdup(value) : NULL; hint->priority = priority; hint->callbacks = NULL; hint->next = SDL_hints; SDL_hints = hint; return SDL_TRUE; } SDL_bool SDL_SetHint(const char *name, const char *value) { return SDL_SetHintWithPriority(name, value, SDL_HINT_NORMAL); } const char * SDL_GetHint(const char *name) { const char *env; SDL_Hint *hint; env = SDL_getenv(name); for (hint = SDL_hints; hint; hint = hint->next) { if (SDL_strcmp(name, hint->name) == 0) { if (!env || hint->priority == SDL_HINT_OVERRIDE) { return hint->value; } break; } } return env; } SDL_bool SDL_GetStringBoolean(const char *value, SDL_bool default_value) { if (!value || !*value) { return default_value; } if (*value == '0' || SDL_strcasecmp(value, "false") == 0) { return SDL_FALSE; } return SDL_TRUE; } SDL_bool SDL_GetHintBoolean(const char *name, SDL_bool default_value) { const char *hint = SDL_GetHint(name); return SDL_GetStringBoolean(hint, default_value); } void SDL_AddHintCallback(const char *name, SDL_HintCallback callback, void *userdata) { SDL_Hint *hint; SDL_HintWatch *entry; const char *value; if (!name || !*name) { SDL_InvalidParamError("name"); return; } if (!callback) { SDL_InvalidParamError("callback"); return; } SDL_DelHintCallback(name, callback, userdata); entry = (SDL_HintWatch *)SDL_malloc(sizeof(*entry)); if (!entry) { SDL_OutOfMemory(); return; } entry->callback = callback; entry->userdata = userdata; for (hint = SDL_hints; hint; hint = hint->next) { if (SDL_strcmp(name, hint->name) == 0) { break; } } if (!hint) { /* Need to add a hint entry for this watcher */ hint = (SDL_Hint *)SDL_malloc(sizeof(*hint)); if (!hint) { SDL_OutOfMemory(); SDL_free(entry); return; } hint->name = SDL_strdup(name); hint->value = NULL; hint->priority = SDL_HINT_DEFAULT; hint->callbacks = NULL; hint->next = SDL_hints; SDL_hints = hint; } /* Add it to the callbacks for this hint */ entry->next = hint->callbacks; hint->callbacks = entry; /* Now call it with the current value */ value = SDL_GetHint(name); callback(userdata, name, value, value); } void SDL_DelHintCallback(const char *name, SDL_HintCallback callback, void *userdata) { SDL_Hint *hint; SDL_HintWatch *entry, *prev; for (hint = SDL_hints; hint; hint = hint->next) { if (SDL_strcmp(name, hint->name) == 0) { prev = NULL; for (entry = hint->callbacks; entry; entry = entry->next) { if (callback == entry->callback && userdata == entry->userdata) { if (prev) { prev->next = entry->next; } else { hint->callbacks = entry->next; } SDL_free(entry); break; } prev = entry; } return; } } } void SDL_ClearHints(void) { SDL_Hint *hint; SDL_HintWatch *entry; while (SDL_hints) { hint = SDL_hints; SDL_hints = hint->next; SDL_free(hint->name); SDL_free(hint->value); for (entry = hint->callbacks; entry; ) { SDL_HintWatch *freeable = entry; entry = entry->next; SDL_free(freeable); } SDL_free(hint); } } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL_hints.c
C
apache-2.0
6,598
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" /* This file defines useful function for working with SDL hints */ #ifndef SDL_hints_c_h_ #define SDL_hints_c_h_ extern SDL_bool SDL_GetStringBoolean(const char *value, SDL_bool default_value); #endif /* SDL_hints_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL_hints_c.h
C
apache-2.0
1,229
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ #ifndef SDL_internal_h_ #define SDL_internal_h_ /* Many of SDL's features require _GNU_SOURCE on various platforms */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif /* This is for a variable-length array at the end of a struct: struct x { int y; char z[SDL_VARIABLE_LENGTH_ARRAY]; }; Use this because GCC 2 needs different magic than other compilers. */ #if (defined(__GNUC__) && (__GNUC__ <= 2)) || defined(__CC_ARM) || defined(__cplusplus) #define SDL_VARIABLE_LENGTH_ARRAY 1 #else #define SDL_VARIABLE_LENGTH_ARRAY #endif #define SDL_STEP_DEBUG printf("func: %s, line: %d excuted\n", __func__, __LINE__); #define SDL_MAX_SMALL_ALLOC_STACKSIZE 128 #define SDL_small_alloc(type, count, pisstack) ( (*(pisstack) = ((sizeof(type)*(count)) < SDL_MAX_SMALL_ALLOC_STACKSIZE)), (*(pisstack) ? SDL_stack_alloc(type, count) : (type*)SDL_malloc(sizeof(type)*(count))) ) #define SDL_small_free(ptr, isstack) if ((isstack)) { SDL_stack_free(ptr); } else { SDL_free(ptr); } #include "dynapi/SDL_dynapi.h" #if SDL_DYNAMIC_API #include "dynapi/SDL_dynapi_overrides.h" /* force DECLSPEC and SDLCALL off...it's all internal symbols now. These will have actual #defines during SDL_dynapi.c only */ #define DECLSPEC #define SDLCALL #endif #include "SDL_config.h" /* A few #defines to reduce SDL2 footprint. Only effective when library is statically linked. You have to manually edit this file. */ #ifndef SDL_LEAN_AND_MEAN #define SDL_LEAN_AND_MEAN 0 #endif /* Optimized functions from 'SDL_blit_0.c' - blit with source BitsPerPixel < 8, palette */ #ifndef SDL_HAVE_BLIT_0 #define SDL_HAVE_BLIT_0 !SDL_LEAN_AND_MEAN #endif /* Optimized functions from 'SDL_blit_1.c' - blit with source BytesPerPixel == 1, palette */ #ifndef SDL_HAVE_BLIT_1 #define SDL_HAVE_BLIT_1 !SDL_LEAN_AND_MEAN #endif /* Optimized functions from 'SDL_blit_A.c' - blit with 'SDL_BLENDMODE_BLEND' blending mode */ #ifndef SDL_HAVE_BLIT_A #define SDL_HAVE_BLIT_A !SDL_LEAN_AND_MEAN #endif /* Optimized functions from 'SDL_blit_N.c' - blit with COLORKEY mode, or nothing */ #ifndef SDL_HAVE_BLIT_N #define SDL_HAVE_BLIT_N !SDL_LEAN_AND_MEAN #endif /* Optimized functions from 'SDL_blit_N.c' - RGB565 conversion with Lookup tables */ #ifndef SDL_HAVE_BLIT_N_RGB565 #define SDL_HAVE_BLIT_N_RGB565 !SDL_LEAN_AND_MEAN #endif /* Optimized functions from 'SDL_blit_AUTO.c' - blit with modulate color, modulate alpha, any blending mode - scaling or not */ #ifndef SDL_HAVE_BLIT_AUTO #define SDL_HAVE_BLIT_AUTO !SDL_LEAN_AND_MEAN #endif /* Run-Length-Encoding - SDL_SetColorKey() called with SDL_RLEACCEL flag */ #ifndef SDL_HAVE_RLE #define SDL_HAVE_RLE !SDL_LEAN_AND_MEAN #endif /* Software SDL_Renderer - creation of software renderer - *not* general blitting functions - {blend,draw}{fillrect,line,point} internal functions */ #ifndef SDL_VIDEO_RENDER_SW #define SDL_VIDEO_RENDER_SW !SDL_LEAN_AND_MEAN #endif /* YUV formats - handling of YUV surfaces - blitting and conversion functions */ #ifndef SDL_HAVE_YUV #define SDL_HAVE_YUV !SDL_LEAN_AND_MEAN #endif #include "SDL_log.h" #endif /* SDL_internal_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL_internal.h
C
apache-2.0
4,252
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if defined(__WIN32__) || defined(__WINRT__) #include "core/windows/SDL_windows.h" #endif /* Simple log messages in SDL */ #include "SDL_error.h" #include "SDL_log.h" #if HAVE_STDIO_H #include <stdio.h> #endif #if defined(__ANDROID__) #include <android/log.h> #endif #define DEFAULT_PRIORITY SDL_LOG_PRIORITY_CRITICAL #define DEFAULT_ASSERT_PRIORITY SDL_LOG_PRIORITY_WARN #define DEFAULT_APPLICATION_PRIORITY SDL_LOG_PRIORITY_INFO #define DEFAULT_TEST_PRIORITY SDL_LOG_PRIORITY_VERBOSE typedef struct SDL_LogLevel { int category; SDL_LogPriority priority; struct SDL_LogLevel *next; } SDL_LogLevel; /* The default log output function */ static void SDLCALL SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority, const char *message); static SDL_LogLevel *SDL_loglevels; static SDL_LogPriority SDL_default_priority = DEFAULT_PRIORITY; static SDL_LogPriority SDL_assert_priority = DEFAULT_ASSERT_PRIORITY; static SDL_LogPriority SDL_application_priority = DEFAULT_APPLICATION_PRIORITY; static SDL_LogPriority SDL_test_priority = DEFAULT_TEST_PRIORITY; static SDL_LogOutputFunction SDL_log_function = SDL_LogOutput; static void *SDL_log_userdata = NULL; static const char *SDL_priority_prefixes[SDL_NUM_LOG_PRIORITIES] = { NULL, "VERBOSE", "DEBUG", "INFO", "WARN", "ERROR", "CRITICAL" }; #ifdef __ANDROID__ static const char *SDL_category_prefixes[SDL_LOG_CATEGORY_RESERVED1] = { "APP", "ERROR", "SYSTEM", "AUDIO", "VIDEO", "RENDER", "INPUT" }; static int SDL_android_priority[SDL_NUM_LOG_PRIORITIES] = { ANDROID_LOG_UNKNOWN, ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL }; #endif /* __ANDROID__ */ void SDL_LogSetAllPriority(SDL_LogPriority priority) { SDL_LogLevel *entry; for (entry = SDL_loglevels; entry; entry = entry->next) { entry->priority = priority; } SDL_default_priority = priority; SDL_assert_priority = priority; SDL_application_priority = priority; } void SDL_LogSetPriority(int category, SDL_LogPriority priority) { SDL_LogLevel *entry; for (entry = SDL_loglevels; entry; entry = entry->next) { if (entry->category == category) { entry->priority = priority; return; } } /* Create a new entry */ entry = (SDL_LogLevel *)SDL_malloc(sizeof(*entry)); if (entry) { entry->category = category; entry->priority = priority; entry->next = SDL_loglevels; SDL_loglevels = entry; } } SDL_LogPriority SDL_LogGetPriority(int category) { SDL_LogLevel *entry; for (entry = SDL_loglevels; entry; entry = entry->next) { if (entry->category == category) { return entry->priority; } } if (category == SDL_LOG_CATEGORY_TEST) { return SDL_test_priority; } else if (category == SDL_LOG_CATEGORY_APPLICATION) { return SDL_application_priority; } else if (category == SDL_LOG_CATEGORY_ASSERT) { return SDL_assert_priority; } else { return SDL_default_priority; } } void SDL_LogResetPriorities(void) { SDL_LogLevel *entry; while (SDL_loglevels) { entry = SDL_loglevels; SDL_loglevels = entry->next; SDL_free(entry); } SDL_default_priority = DEFAULT_PRIORITY; SDL_assert_priority = DEFAULT_ASSERT_PRIORITY; SDL_application_priority = DEFAULT_APPLICATION_PRIORITY; SDL_test_priority = DEFAULT_TEST_PRIORITY; } void SDL_Log(SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { va_list ap; va_start(ap, fmt); SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap); va_end(ap); } void SDL_LogVerbose(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { va_list ap; va_start(ap, fmt); SDL_LogMessageV(category, SDL_LOG_PRIORITY_VERBOSE, fmt, ap); va_end(ap); } void SDL_LogDebug(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { va_list ap; va_start(ap, fmt); SDL_LogMessageV(category, SDL_LOG_PRIORITY_DEBUG, fmt, ap); va_end(ap); } void SDL_LogInfo(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { va_list ap; va_start(ap, fmt); SDL_LogMessageV(category, SDL_LOG_PRIORITY_INFO, fmt, ap); va_end(ap); } void SDL_LogWarn(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { va_list ap; va_start(ap, fmt); SDL_LogMessageV(category, SDL_LOG_PRIORITY_WARN, fmt, ap); va_end(ap); } void SDL_LogError(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { va_list ap; va_start(ap, fmt); SDL_LogMessageV(category, SDL_LOG_PRIORITY_ERROR, fmt, ap); va_end(ap); } void SDL_LogCritical(int category, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { va_list ap; va_start(ap, fmt); SDL_LogMessageV(category, SDL_LOG_PRIORITY_CRITICAL, fmt, ap); va_end(ap); } void SDL_LogMessage(int category, SDL_LogPriority priority, SDL_PRINTF_FORMAT_STRING const char *fmt, ...) { va_list ap; va_start(ap, fmt); SDL_LogMessageV(category, priority, fmt, ap); va_end(ap); } #ifdef __ANDROID__ static const char * GetCategoryPrefix(int category) { if (category < SDL_LOG_CATEGORY_RESERVED1) { return SDL_category_prefixes[category]; } if (category < SDL_LOG_CATEGORY_CUSTOM) { return "RESERVED"; } return "CUSTOM"; } #endif /* __ANDROID__ */ void SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list ap) { char *message; size_t len; /* Nothing to do if we don't have an output function */ if (!SDL_log_function) { return; } /* Make sure we don't exceed array bounds */ if ((int)priority < 0 || priority >= SDL_NUM_LOG_PRIORITIES) { return; } /* See if we want to do anything with this message */ if (priority < SDL_LogGetPriority(category)) { return; } /* !!! FIXME: why not just "char message[SDL_MAX_LOG_MESSAGE];" ? */ message = SDL_stack_alloc(char, SDL_MAX_LOG_MESSAGE); if (!message) { return; } SDL_vsnprintf(message, SDL_MAX_LOG_MESSAGE, fmt, ap); /* Chop off final endline. */ len = SDL_strlen(message); if ((len > 0) && (message[len-1] == '\n')) { message[--len] = '\0'; if ((len > 0) && (message[len-1] == '\r')) { /* catch "\r\n", too. */ message[--len] = '\0'; } } SDL_log_function(SDL_log_userdata, category, priority, message); SDL_stack_free(message); } #if defined(__WIN32__) && !defined(HAVE_STDIO_H) && !defined(__WINRT__) /* Flag tracking the attachment of the console: 0=unattached, 1=attached to a console, 2=attached to a file, -1=error */ static int consoleAttached = 0; /* Handle to stderr output of console. */ static HANDLE stderrHandle = NULL; #endif static void SDLCALL SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority, const char *message) { #if defined(__WIN32__) || defined(__WINRT__) /* Way too many allocations here, urgh */ /* Note: One can't call SDL_SetError here, since that function itself logs. */ { char *output; size_t length; LPTSTR tstr; SDL_bool isstack; #if !defined(HAVE_STDIO_H) && !defined(__WINRT__) BOOL attachResult; DWORD attachError; unsigned long charsWritten; DWORD consoleMode; /* Maybe attach console and get stderr handle */ if (consoleAttached == 0) { attachResult = AttachConsole(ATTACH_PARENT_PROCESS); if (!attachResult) { attachError = GetLastError(); if (attachError == ERROR_INVALID_HANDLE) { /* This is expected when running from Visual Studio */ /*OutputDebugString(TEXT("Parent process has no console\r\n"));*/ consoleAttached = -1; } else if (attachError == ERROR_GEN_FAILURE) { OutputDebugString(TEXT("Could not attach to console of parent process\r\n")); consoleAttached = -1; } else if (attachError == ERROR_ACCESS_DENIED) { /* Already attached */ consoleAttached = 1; } else { OutputDebugString(TEXT("Error attaching console\r\n")); consoleAttached = -1; } } else { /* Newly attached */ consoleAttached = 1; } if (consoleAttached == 1) { stderrHandle = GetStdHandle(STD_ERROR_HANDLE); if (GetConsoleMode(stderrHandle, &consoleMode) == 0) { /* WriteConsole fails if the output is redirected to a file. Must use WriteFile instead. */ consoleAttached = 2; } } } #endif /* !defined(HAVE_STDIO_H) && !defined(__WINRT__) */ length = SDL_strlen(SDL_priority_prefixes[priority]) + 2 + SDL_strlen(message) + 1 + 1 + 1; output = SDL_small_alloc(char, length, &isstack); SDL_snprintf(output, length, "%s: %s\r\n", SDL_priority_prefixes[priority], message); tstr = WIN_UTF8ToString(output); /* Output to debugger */ OutputDebugString(tstr); #if !defined(HAVE_STDIO_H) && !defined(__WINRT__) /* Screen output to stderr, if console was attached. */ if (consoleAttached == 1) { if (!WriteConsole(stderrHandle, tstr, lstrlen(tstr), &charsWritten, NULL)) { OutputDebugString(TEXT("Error calling WriteConsole\r\n")); if (GetLastError() == ERROR_NOT_ENOUGH_MEMORY) { OutputDebugString(TEXT("Insufficient heap memory to write message\r\n")); } } } else if (consoleAttached == 2) { if (!WriteFile(stderrHandle, output, lstrlenA(output), &charsWritten, NULL)) { OutputDebugString(TEXT("Error calling WriteFile\r\n")); } } #endif /* !defined(HAVE_STDIO_H) && !defined(__WINRT__) */ SDL_free(tstr); SDL_small_free(output, isstack); } #elif defined(__ANDROID__) { char tag[32]; SDL_snprintf(tag, SDL_arraysize(tag), "SDL/%s", GetCategoryPrefix(category)); __android_log_write(SDL_android_priority[priority], tag, message); } #elif defined(__APPLE__) && (defined(SDL_VIDEO_DRIVER_COCOA) || defined(SDL_VIDEO_DRIVER_UIKIT)) /* Technically we don't need Cocoa/UIKit, but that's where this function is defined for now. */ extern void SDL_NSLog(const char *text); { char *text; /* !!! FIXME: why not just "char text[SDL_MAX_LOG_MESSAGE];" ? */ text = SDL_stack_alloc(char, SDL_MAX_LOG_MESSAGE); if (text) { SDL_snprintf(text, SDL_MAX_LOG_MESSAGE, "%s: %s", SDL_priority_prefixes[priority], message); SDL_NSLog(text); SDL_stack_free(text); return; } } #elif defined(__PSP__) { FILE* pFile; pFile = fopen ("SDL_Log.txt", "a"); fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message); fclose (pFile); } #endif #if HAVE_STDIO_H fprintf(stderr, "%s: %s\n", SDL_priority_prefixes[priority], message); #if __NACL__ fflush(stderr); #endif #endif } void SDL_LogGetOutputFunction(SDL_LogOutputFunction *callback, void **userdata) { if (callback) { *callback = SDL_log_function; } if (userdata) { *userdata = SDL_log_userdata; } } void SDL_LogSetOutputFunction(SDL_LogOutputFunction callback, void *userdata) { SDL_log_function = callback; SDL_log_userdata = userdata; } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/SDL_log.c
C
apache-2.0
13,091
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #include "SDL_atomic.h" #if defined(_MSC_VER) && (_MSC_VER >= 1500) #include <intrin.h> #define HAVE_MSC_ATOMICS 1 #endif #if defined(__MACOSX__) /* !!! FIXME: should we favor gcc atomics? */ #include <libkern/OSAtomic.h> #endif #if !defined(HAVE_GCC_ATOMICS) && defined(__SOLARIS__) #include <atomic.h> #endif /* The __atomic_load_n() intrinsic showed up in different times for different compilers. */ #if defined(HAVE_GCC_ATOMICS) # if defined(__clang__) # if __has_builtin(__atomic_load_n) /* !!! FIXME: this advertises as available in the NDK but uses an external symbol we don't have. It might be in a later NDK or we might need an extra library? --ryan. */ # if !defined(__ANDROID__) # define HAVE_ATOMIC_LOAD_N 1 # endif # endif # elif defined(__GNUC__) # if (__GNUC__ >= 5) # define HAVE_ATOMIC_LOAD_N 1 # endif # endif #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" \ parm [ecx] [eax] \ value [eax] \ modify exact [eax]; extern _inline unsigned char _SDL_cmpxchg_watcom(volatile int *a, int newval, int oldval); #pragma aux _SDL_cmpxchg_watcom = \ "lock cmpxchg [edx], ecx" \ "setz al" \ parm [edx] [ecx] [eax] \ value [al] \ modify exact [eax]; extern _inline int _SDL_xadd_watcom(volatile int *a, int v); #pragma aux _SDL_xadd_watcom = \ "lock xadd [ecx], eax" \ parm [ecx] [eax] \ value [eax] \ modify exact [eax]; #endif /* __WATCOMC__ && __386__ */ /* If any of the operations are not provided then we must emulate some of them. That means we need a nice implementation of spin locks that avoids the "one big lock" problem. We use a vector of spin locks and pick which one to use based on the address of the operand of the function. To generate the index of the lock we first shift by 3 bits to get rid on the zero bits that result from 32 and 64 bit allignment of data. We then mask off all but 5 bits and use those 5 bits as an index into the table. Picking the lock this way insures that accesses to the same data at the same time will go to the same lock. OTOH, accesses to different data have only a 1/32 chance of hitting the same lock. That should pretty much eliminate the chances of several atomic operations on different data from waiting on the same "big lock". If it isn't then the table of locks can be expanded to a new size so long as the new size is a power of two. Contributed by Bob Pendleton, bob@pendleton.com */ #if !defined(HAVE_MSC_ATOMICS) && !defined(HAVE_GCC_ATOMICS) && !defined(__MACOSX__) && !defined(__SOLARIS__) && !defined(HAVE_WATCOM_ATOMICS) #define EMULATE_CAS 1 #endif #if EMULATE_CAS static SDL_SpinLock locks[32]; static SDL_INLINE void enterLock(void *a) { uintptr_t index = ((((uintptr_t)a) >> 3) & 0x1f); SDL_AtomicLock(&locks[index]); } static SDL_INLINE void leaveLock(void *a) { uintptr_t index = ((((uintptr_t)a) >> 3) & 0x1f); SDL_AtomicUnlock(&locks[index]); } #endif SDL_bool SDL_AtomicCAS(SDL_atomic_t *a, int oldval, int newval) { #ifdef HAVE_MSC_ATOMICS return (_InterlockedCompareExchange((long*)&a->value, (long)newval, (long)oldval) == (long)oldval); #elif defined(HAVE_WATCOM_ATOMICS) return (SDL_bool) _SDL_cmpxchg_watcom(&a->value, newval, oldval); #elif defined(HAVE_GCC_ATOMICS) return (SDL_bool) __sync_bool_compare_and_swap(&a->value, oldval, newval); #elif defined(__MACOSX__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */ return (SDL_bool) OSAtomicCompareAndSwap32Barrier(oldval, newval, &a->value); #elif defined(__SOLARIS__) && defined(_LP64) return (SDL_bool) ((int) atomic_cas_64((volatile uint64_t*)&a->value, (uint64_t)oldval, (uint64_t)newval) == oldval); #elif defined(__SOLARIS__) && !defined(_LP64) return (SDL_bool) ((int) atomic_cas_32((volatile uint32_t*)&a->value, (uint32_t)oldval, (uint32_t)newval) == oldval); #elif EMULATE_CAS SDL_bool retval = SDL_FALSE; enterLock(a); if (a->value == oldval) { a->value = newval; retval = SDL_TRUE; } leaveLock(a); return retval; #else #error Please define your platform. #endif } SDL_bool SDL_AtomicCASPtr(void **a, void *oldval, void *newval) { #if defined(HAVE_MSC_ATOMICS) && (_M_IX86) return (_InterlockedCompareExchange((long*)a, (long)newval, (long)oldval) == (long)oldval); #elif defined(HAVE_MSC_ATOMICS) && (!_M_IX86) return (_InterlockedCompareExchangePointer(a, newval, oldval) == oldval); #elif defined(HAVE_WATCOM_ATOMICS) return (SDL_bool) _SDL_cmpxchg_watcom((int *)a, (long)newval, (long)oldval); #elif defined(HAVE_GCC_ATOMICS) return __sync_bool_compare_and_swap(a, oldval, newval); #elif defined(__MACOSX__) && defined(__LP64__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */ return (SDL_bool) OSAtomicCompareAndSwap64Barrier((int64_t)oldval, (int64_t)newval, (int64_t*) a); #elif defined(__MACOSX__) && !defined(__LP64__) /* this is deprecated in 10.12 sdk; favor gcc atomics. */ return (SDL_bool) OSAtomicCompareAndSwap32Barrier((int32_t)oldval, (int32_t)newval, (int32_t*) a); #elif defined(__SOLARIS__) return (SDL_bool) (atomic_cas_ptr(a, oldval, newval) == oldval); #elif EMULATE_CAS SDL_bool retval = SDL_FALSE; enterLock(a); if (*a == oldval) { *a = newval; retval = SDL_TRUE; } leaveLock(a); return retval; #else #error Please define your platform. #endif } int SDL_AtomicSet(SDL_atomic_t *a, int v) { #ifdef HAVE_MSC_ATOMICS return _InterlockedExchange((long*)&a->value, v); #elif defined(HAVE_WATCOM_ATOMICS) return _SDL_xchg_watcom(&a->value, v); #elif defined(HAVE_GCC_ATOMICS) return __sync_lock_test_and_set(&a->value, v); #elif defined(__SOLARIS__) && defined(_LP64) return (int) atomic_swap_64((volatile uint64_t*)&a->value, (uint64_t)v); #elif defined(__SOLARIS__) && !defined(_LP64) return (int) atomic_swap_32((volatile uint32_t*)&a->value, (uint32_t)v); #else int value; do { value = a->value; } while (!SDL_AtomicCAS(a, value, v)); return value; #endif } void* SDL_AtomicSetPtr(void **a, void *v) { #if defined(HAVE_MSC_ATOMICS) && (_M_IX86) return (void *) _InterlockedExchange((long *)a, (long) v); #elif defined(HAVE_MSC_ATOMICS) && (!_M_IX86) return _InterlockedExchangePointer(a, v); #elif defined(HAVE_WATCOM_ATOMICS) return (void *) _SDL_xchg_watcom((int *)a, (long)v); #elif defined(HAVE_GCC_ATOMICS) return __sync_lock_test_and_set(a, v); #elif defined(__SOLARIS__) return atomic_swap_ptr(a, v); #else void *value; do { value = *a; } while (!SDL_AtomicCASPtr(a, value, v)); return value; #endif } int SDL_AtomicAdd(SDL_atomic_t *a, int v) { #ifdef HAVE_MSC_ATOMICS return _InterlockedExchangeAdd((long*)&a->value, v); #elif defined(HAVE_WATCOM_ATOMICS) return _SDL_xadd_watcom(&a->value, v); #elif defined(HAVE_GCC_ATOMICS) return __sync_fetch_and_add(&a->value, v); #elif defined(__SOLARIS__) int pv = a->value; membar_consumer(); #if defined(_LP64) atomic_add_64((volatile uint64_t*)&a->value, v); #elif !defined(_LP64) atomic_add_32((volatile uint32_t*)&a->value, v); #endif return pv; #else int value; do { value = a->value; } while (!SDL_AtomicCAS(a, value, (value + v))); return value; #endif } int SDL_AtomicGet(SDL_atomic_t *a) { #ifdef HAVE_ATOMIC_LOAD_N return __atomic_load_n(&a->value, __ATOMIC_SEQ_CST); #else int value; do { value = a->value; } while (!SDL_AtomicCAS(a, value, value)); return value; #endif } void * SDL_AtomicGetPtr(void **a) { #ifdef HAVE_ATOMIC_LOAD_N return __atomic_load_n(a, __ATOMIC_SEQ_CST); #else void *value; do { value = *a; } while (!SDL_AtomicCASPtr(a, value, value)); return value; #endif } #ifdef SDL_MEMORY_BARRIER_USES_FUNCTION #error This file should be built in arm mode so the mcr instruction is available for memory barriers #endif void SDL_MemoryBarrierReleaseFunction(void) { SDL_MemoryBarrierRelease(); } void SDL_MemoryBarrierAcquireFunction(void) { SDL_MemoryBarrierAcquire(); } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/atomic/SDL_atomic.c
C
apache-2.0
9,345
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if defined(__WIN32__) || defined(__WINRT__) #include "../core/windows/SDL_windows.h" #endif #include "SDL_atomic.h" #include "SDL_mutex.h" #include "SDL_timer.h" #if !defined(HAVE_GCC_ATOMICS) && defined(__SOLARIS__) #include <atomic.h> #endif #if !defined(HAVE_GCC_ATOMICS) && defined(__RISCOS__) #include <unixlib/local.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" \ parm [ecx] [eax] \ value [eax] \ modify exact [eax]; #endif /* __WATCOMC__ && __386__ */ /* This function is where all the magic happens... */ SDL_bool SDL_AtomicTryLock(SDL_SpinLock *lock) { #if SDL_ATOMIC_DISABLED /* Terrible terrible damage */ static SDL_mutex *_spinlock_mutex; if (!_spinlock_mutex) { /* Race condition on first lock... */ _spinlock_mutex = SDL_CreateMutex(); } SDL_LockMutex(_spinlock_mutex); if (*lock == 0) { *lock = 1; SDL_UnlockMutex(_spinlock_mutex); return SDL_TRUE; } else { SDL_UnlockMutex(_spinlock_mutex); return SDL_FALSE; } #elif defined(_MSC_VER) SDL_COMPILE_TIME_ASSERT(locksize, sizeof(*lock) == sizeof(long)); return (InterlockedExchange((long*)lock, 1) == 0); #elif defined(__WATCOMC__) && defined(__386__) return _SDL_xchg_watcom(lock, 1) == 0; #elif HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET return (__sync_lock_test_and_set(lock, 1) == 0); #elif defined(__GNUC__) && defined(__arm__) && \ (defined(__ARM_ARCH_3__) || defined(__ARM_ARCH_3M__) || \ defined(__ARM_ARCH_4__) || defined(__ARM_ARCH_4T__) || \ defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5TE__) || \ defined(__ARM_ARCH_5TEJ__)) int result; #if defined(__RISCOS__) if (__cpucap_have_rex()) { __asm__ __volatile__ ( "ldrex %0, [%2]\nteq %0, #0\nstrexeq %0, %1, [%2]" : "=&r" (result) : "r" (1), "r" (lock) : "cc", "memory"); return (result == 0); } #endif __asm__ __volatile__ ( "swp %0, %1, [%2]\n" : "=&r,&r" (result) : "r,0" (1), "r,r" (lock) : "memory"); return (result == 0); #elif defined(__GNUC__) && defined(__arm__) int result; __asm__ __volatile__ ( "ldrex %0, [%2]\nteq %0, #0\nstrexeq %0, %1, [%2]" : "=&r" (result) : "r" (1), "r" (lock) : "cc", "memory"); return (result == 0); #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) int result; __asm__ __volatile__( "lock ; xchgl %0, (%1)\n" : "=r" (result) : "r" (lock), "0" (1) : "cc", "memory"); return (result == 0); #elif defined(__MACOSX__) || defined(__IPHONEOS__) /* Maybe used for PowerPC, but the Intel asm or gcc atomics are favored. */ return OSAtomicCompareAndSwap32Barrier(0, 1, lock); #elif defined(__SOLARIS__) && defined(_LP64) /* Used for Solaris with non-gcc compilers. */ return (SDL_bool) ((int) atomic_cas_64((volatile uint64_t*)lock, 0, 1) == 0); #elif defined(__SOLARIS__) && !defined(_LP64) /* Used for Solaris with non-gcc compilers. */ return (SDL_bool) ((int) atomic_cas_32((volatile uint32_t*)lock, 0, 1) == 0); #else #error Please implement for your platform. return SDL_FALSE; #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); } } } void SDL_AtomicUnlock(SDL_SpinLock *lock) { #if defined(_MSC_VER) _ReadWriteBarrier(); *lock = 0; #elif defined(__WATCOMC__) && defined(__386__) SDL_CompilerBarrier (); *lock = 0; #elif HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET __sync_lock_release(lock); #elif defined(__SOLARIS__) /* Used for Solaris when not using gcc. */ *lock = 0; membar_producer(); #else *lock = 0; #endif } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/atomic/SDL_spinlock.c
C
apache-2.0
6,176
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" /* Allow access to a raw mixing buffer */ #include "SDL.h" #include "SDL_audio.h" #include "SDL_audio_c.h" #include "SDL_sysaudio.h" #include "../thread/SDL_systhread.h" #define _THIS SDL_AudioDevice *_this static SDL_AudioDriver current_audio; static SDL_AudioDevice *open_devices[16]; /* Available audio drivers */ static const AudioBootStrap *const bootstrap[] = { #if SDL_AUDIO_DRIVER_PULSEAUDIO &PULSEAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_ALSA &ALSA_bootstrap, #endif #if SDL_AUDIO_DRIVER_SNDIO &SNDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_NETBSD &NETBSDAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_OSS &DSP_bootstrap, #endif #if SDL_AUDIO_DRIVER_QSA &QSAAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_SUNAUDIO &SUNAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_ARTS &ARTS_bootstrap, #endif #if SDL_AUDIO_DRIVER_ESD &ESD_bootstrap, #endif #if SDL_AUDIO_DRIVER_NACL &NACLAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_NAS &NAS_bootstrap, #endif #if SDL_AUDIO_DRIVER_WASAPI &WASAPI_bootstrap, #endif #if SDL_AUDIO_DRIVER_DSOUND &DSOUND_bootstrap, #endif #if SDL_AUDIO_DRIVER_WINMM &WINMM_bootstrap, #endif #if SDL_AUDIO_DRIVER_PAUDIO &PAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_HAIKU &HAIKUAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_COREAUDIO &COREAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_FUSIONSOUND &FUSIONSOUND_bootstrap, #endif #if SDL_AUDIO_DRIVER_OPENSLES &openslES_bootstrap, #endif #if SDL_AUDIO_DRIVER_ANDROID &ANDROIDAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_PSP &PSPAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_ALIOS &AOSAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_EMSCRIPTEN &EMSCRIPTENAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_JACK &JACK_bootstrap, #endif #if SDL_AUDIO_DRIVER_DISK &DISKAUDIO_bootstrap, #endif #if SDL_AUDIO_DRIVER_DUMMY &DUMMYAUDIO_bootstrap, #endif NULL }; #ifdef HAVE_LIBSAMPLERATE_H #ifdef SDL_LIBSAMPLERATE_DYNAMIC static void *SRC_lib = NULL; #endif SDL_bool SRC_available = SDL_FALSE; int SRC_converter = 0; SRC_STATE* (*SRC_src_new)(int converter_type, int channels, int *error) = NULL; int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data) = NULL; int (*SRC_src_reset)(SRC_STATE *state) = NULL; SRC_STATE* (*SRC_src_delete)(SRC_STATE *state) = NULL; const char* (*SRC_src_strerror)(int error) = NULL; static SDL_bool LoadLibSampleRate(void) { const char *hint = SDL_GetHint(SDL_HINT_AUDIO_RESAMPLING_MODE); SRC_available = SDL_FALSE; SRC_converter = 0; if (!hint || *hint == '0' || SDL_strcasecmp(hint, "default") == 0) { return SDL_FALSE; /* don't load anything. */ } else if (*hint == '1' || SDL_strcasecmp(hint, "fast") == 0) { SRC_converter = SRC_SINC_FASTEST; } else if (*hint == '2' || SDL_strcasecmp(hint, "medium") == 0) { SRC_converter = SRC_SINC_MEDIUM_QUALITY; } else if (*hint == '3' || SDL_strcasecmp(hint, "best") == 0) { SRC_converter = SRC_SINC_BEST_QUALITY; } else { return SDL_FALSE; /* treat it like "default", don't load anything. */ } #ifdef SDL_LIBSAMPLERATE_DYNAMIC SDL_assert(SRC_lib == NULL); SRC_lib = SDL_LoadObject(SDL_LIBSAMPLERATE_DYNAMIC); if (!SRC_lib) { SDL_ClearError(); return SDL_FALSE; } SRC_src_new = (SRC_STATE* (*)(int converter_type, int channels, int *error))SDL_LoadFunction(SRC_lib, "src_new"); SRC_src_process = (int (*)(SRC_STATE *state, SRC_DATA *data))SDL_LoadFunction(SRC_lib, "src_process"); SRC_src_reset = (int(*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_reset"); SRC_src_delete = (SRC_STATE* (*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_delete"); SRC_src_strerror = (const char* (*)(int error))SDL_LoadFunction(SRC_lib, "src_strerror"); if (!SRC_src_new || !SRC_src_process || !SRC_src_reset || !SRC_src_delete || !SRC_src_strerror) { SDL_UnloadObject(SRC_lib); SRC_lib = NULL; return SDL_FALSE; } #else SRC_src_new = src_new; SRC_src_process = src_process; SRC_src_reset = src_reset; SRC_src_delete = src_delete; SRC_src_strerror = src_strerror; #endif SRC_available = SDL_TRUE; return SDL_TRUE; } static void UnloadLibSampleRate(void) { #ifdef SDL_LIBSAMPLERATE_DYNAMIC if (SRC_lib != NULL) { SDL_UnloadObject(SRC_lib); } SRC_lib = NULL; #endif SRC_available = SDL_FALSE; SRC_src_new = NULL; SRC_src_process = NULL; SRC_src_reset = NULL; SRC_src_delete = NULL; SRC_src_strerror = NULL; } #endif static SDL_AudioDevice * get_audio_device(SDL_AudioDeviceID id) { id--; if ((id >= SDL_arraysize(open_devices)) || (open_devices[id] == NULL)) { SDL_SetError("Invalid audio device ID"); return NULL; } return open_devices[id]; } /* stubs for audio drivers that don't need a specific entry point... */ static void SDL_AudioDetectDevices_Default(void) { /* you have to write your own implementation if these assertions fail. */ SDL_assert(current_audio.impl.OnlyHasDefaultOutputDevice); SDL_assert(current_audio.impl.OnlyHasDefaultCaptureDevice || !current_audio.impl.HasCaptureSupport); SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, (void *) ((size_t) 0x1)); if (current_audio.impl.HasCaptureSupport) { SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, (void *) ((size_t) 0x2)); } } static void SDL_AudioThreadInit_Default(_THIS) { /* no-op. */ } static void SDL_AudioThreadDeinit_Default(_THIS) { /* no-op. */ } static void SDL_AudioBeginLoopIteration_Default(_THIS) { /* no-op. */ } static void SDL_AudioWaitDevice_Default(_THIS) { /* no-op. */ } static void SDL_AudioPlayDevice_Default(_THIS) { /* no-op. */ } static Uint8 * SDL_AudioGetDeviceBuf_Default(_THIS) { return NULL; } static int SDL_AudioCaptureFromDevice_Default(_THIS, void *buffer, int buflen) { return -1; /* just fail immediately. */ } static void SDL_AudioFlushCapture_Default(_THIS) { /* no-op. */ } static void SDL_AudioPrepareToClose_Default(_THIS) { /* no-op. */ } static void SDL_AudioCloseDevice_Default(_THIS) { /* no-op. */ } static void SDL_AudioDeinitialize_Default(void) { /* no-op. */ } static void SDL_AudioFreeDeviceHandle_Default(void *handle) { /* no-op. */ } static int SDL_AudioOpenDevice_Default(_THIS, void *handle, const char *devname, int iscapture) { return SDL_Unsupported(); } static SDL_INLINE SDL_bool is_in_audio_device_thread(SDL_AudioDevice * device) { /* The device thread locks the same mutex, but not through the public API. This check is in case the application, in the audio callback, tries to lock the thread that we've already locked from the device thread...just in case we only have non-recursive mutexes. */ if (device->thread && (SDL_ThreadID() == device->threadid)) { return SDL_TRUE; } return SDL_FALSE; } static void SDL_AudioLockDevice_Default(SDL_AudioDevice * device) { if (!is_in_audio_device_thread(device)) { SDL_LockMutex(device->mixer_lock); } } static void SDL_AudioUnlockDevice_Default(SDL_AudioDevice * device) { if (!is_in_audio_device_thread(device)) { SDL_UnlockMutex(device->mixer_lock); } } static void SDL_AudioLockOrUnlockDeviceWithNoMixerLock(SDL_AudioDevice * device) { } static void finish_audio_entry_points_init(void) { /* * Fill in stub functions for unused driver entry points. This lets us * blindly call them without having to check for validity first. */ if (current_audio.impl.SkipMixerLock) { if (current_audio.impl.LockDevice == NULL) { current_audio.impl.LockDevice = SDL_AudioLockOrUnlockDeviceWithNoMixerLock; } if (current_audio.impl.UnlockDevice == NULL) { current_audio.impl.UnlockDevice = SDL_AudioLockOrUnlockDeviceWithNoMixerLock; } } #define FILL_STUB(x) \ if (current_audio.impl.x == NULL) { \ current_audio.impl.x = SDL_Audio##x##_Default; \ } FILL_STUB(DetectDevices); FILL_STUB(OpenDevice); FILL_STUB(ThreadInit); FILL_STUB(ThreadDeinit); FILL_STUB(BeginLoopIteration); FILL_STUB(WaitDevice); FILL_STUB(PlayDevice); FILL_STUB(GetDeviceBuf); FILL_STUB(CaptureFromDevice); FILL_STUB(FlushCapture); FILL_STUB(PrepareToClose); FILL_STUB(CloseDevice); FILL_STUB(LockDevice); FILL_STUB(UnlockDevice); FILL_STUB(FreeDeviceHandle); FILL_STUB(Deinitialize); #undef FILL_STUB } /* device hotplug support... */ 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; 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_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 */ SDL_UnlockMutex(current_audio.detectionLock); return retval; } static SDL_INLINE int add_capture_device(const char *name, void *handle) { SDL_assert(current_audio.impl.HasCaptureSupport); return add_audio_device(name, handle, &current_audio.inputDevices, &current_audio.inputDeviceCount); } static SDL_INLINE int add_output_device(const char *name, void *handle) { return add_audio_device(name, handle, &current_audio.outputDevices, &current_audio.outputDeviceCount); } static void free_device_list(SDL_AudioDeviceItem **devices, int *devCount) { SDL_AudioDeviceItem *item, *next; for (item = *devices; item != NULL; item = next) { next = item->next; 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; *devCount = 0; } /* The audio backends call this when a new device is plugged in. */ void SDL_AddAudioDevice(const int iscapture, const char *name, void *handle) { const int device_index = iscapture ? add_capture_device(name, handle) : add_output_device(name, handle); if (device_index != -1) { /* Post the event, if desired */ if (SDL_GetEventState(SDL_AUDIODEVICEADDED) == SDL_ENABLE) { SDL_Event event; SDL_zero(event); event.adevice.type = SDL_AUDIODEVICEADDED; event.adevice.which = device_index; event.adevice.iscapture = iscapture; SDL_PushEvent(&event); } } } /* The audio backends call this when a currently-opened device is lost. */ 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. */ } /* Ends the audio callback and mark the device as STOPPED, but the app still needs to close the device to free resources. */ current_audio.impl.LockDevice(device); SDL_AtomicSet(&device->enabled, 0); current_audio.impl.UnlockDevice(device); /* Post the event, if desired */ if (SDL_GetEventState(SDL_AUDIODEVICEREMOVED) == SDL_ENABLE) { SDL_Event event; SDL_zero(event); event.adevice.type = SDL_AUDIODEVICEREMOVED; event.adevice.which = device->id; event.adevice.iscapture = device->iscapture ? 1 : 0; SDL_PushEvent(&event); } } static void mark_device_removed(void *handle, SDL_AudioDeviceItem *devices, SDL_bool *removedFlag) { SDL_AudioDeviceItem *item; SDL_assert(handle != NULL); for (item = devices; item != NULL; item = item->next) { if (item->handle == handle) { item->handle = NULL; *removedFlag = SDL_TRUE; return; } } } /* The audio backends call this when a device is removed from the system. */ void SDL_RemoveAudioDevice(const int iscapture, void *handle) { int device_index; SDL_AudioDevice *device = NULL; SDL_LockMutex(current_audio.detectionLock); if (iscapture) { mark_device_removed(handle, current_audio.inputDevices, &current_audio.captureDevicesRemoved); } else { mark_device_removed(handle, current_audio.outputDevices, &current_audio.outputDevicesRemoved); } for (device_index = 0; device_index < SDL_arraysize(open_devices); device_index++) { device = open_devices[device_index]; if (device != NULL && device->handle == handle) { SDL_OpenedAudioDeviceDisconnected(device); break; } } SDL_UnlockMutex(current_audio.detectionLock); current_audio.impl.FreeDeviceHandle(handle); } /* buffer queueing support... */ static void SDLCALL SDL_BufferQueueDrainCallback(void *userdata, Uint8 *stream, int len) { /* this function always holds the mixer lock before being called. */ SDL_AudioDevice *device = (SDL_AudioDevice *) userdata; size_t dequeued; SDL_assert(device != NULL); /* this shouldn't ever happen, right?! */ SDL_assert(!device->iscapture); /* this shouldn't ever happen, right?! */ SDL_assert(len >= 0); /* this shouldn't ever happen, right?! */ dequeued = SDL_ReadFromDataQueue(device->buffer_queue, stream, len); stream += dequeued; len -= (int) dequeued; if (len > 0) { /* fill any remaining space in the stream with silence. */ SDL_assert(SDL_CountDataQueue(device->buffer_queue) == 0); SDL_memset(stream, device->spec.silence, len); } } static void SDLCALL SDL_BufferQueueFillCallback(void *userdata, Uint8 *stream, int len) { /* this function always holds the mixer lock before being called. */ SDL_AudioDevice *device = (SDL_AudioDevice *) userdata; SDL_assert(device != NULL); /* this shouldn't ever happen, right?! */ SDL_assert(device->iscapture); /* this shouldn't ever happen, right?! */ SDL_assert(len >= 0); /* this shouldn't ever happen, right?! */ /* note that if this needs to allocate more space and run out of memory, we have no choice but to quietly drop the data and hope it works out later, but you probably have bigger problems in this case anyhow. */ SDL_WriteToDataQueue(device->buffer_queue, stream, len); } int SDL_QueueAudio(SDL_AudioDeviceID devid, const void *data, Uint32 len) { SDL_AudioDevice *device = get_audio_device(devid); int rc = 0; if (!device) { return -1; /* get_audio_device() will have set the error state */ } else if (device->iscapture) { return SDL_SetError("This is a capture device, queueing not allowed"); } else if (device->callbackspec.callback != SDL_BufferQueueDrainCallback) { return SDL_SetError("Audio device has a callback, queueing not allowed"); } if (len > 0) { current_audio.impl.LockDevice(device); rc = SDL_WriteToDataQueue(device->buffer_queue, data, len); current_audio.impl.UnlockDevice(device); } return rc; } Uint32 SDL_DequeueAudio(SDL_AudioDeviceID devid, void *data, Uint32 len) { SDL_AudioDevice *device = get_audio_device(devid); Uint32 rc; if ( (len == 0) || /* nothing to do? */ (!device) || /* called with bogus device id */ (!device->iscapture) || /* playback devices can't dequeue */ (device->callbackspec.callback != SDL_BufferQueueFillCallback) ) { /* not set for queueing */ return 0; /* just report zero bytes dequeued. */ } current_audio.impl.LockDevice(device); rc = (Uint32) SDL_ReadFromDataQueue(device->buffer_queue, data, len); current_audio.impl.UnlockDevice(device); return rc; } Uint32 SDL_GetQueuedAudioSize(SDL_AudioDeviceID devid) { Uint32 retval = 0; SDL_AudioDevice *device = get_audio_device(devid); if (!device) { return 0; } /* Nothing to do unless we're set up for queueing. */ if (device->callbackspec.callback == SDL_BufferQueueDrainCallback || device->callbackspec.callback == SDL_BufferQueueFillCallback) { current_audio.impl.LockDevice(device); retval = (Uint32) SDL_CountDataQueue(device->buffer_queue); current_audio.impl.UnlockDevice(device); } return retval; } void SDL_ClearQueuedAudio(SDL_AudioDeviceID devid) { SDL_AudioDevice *device = get_audio_device(devid); if (!device) { return; /* nothing to do. */ } /* Blank out the device and release the mutex. Free it afterwards. */ current_audio.impl.LockDevice(device); /* Keep up to two packets in the pool to reduce future malloc pressure. */ SDL_ClearDataQueue(device->buffer_queue, SDL_AUDIOBUFFERQUEUE_PACKETLEN * 2); current_audio.impl.UnlockDevice(device); } /* The general mixing thread function */ static int SDLCALL SDL_RunAudio(void *devicep) { SDL_AudioDevice *device = (SDL_AudioDevice *) devicep; void *udata = device->callbackspec.userdata; SDL_AudioCallback callback = device->callbackspec.callback; int data_len = 0; Uint8 *data; SDL_assert(!device->iscapture); #if SDL_AUDIO_DRIVER_ANDROID { /* Set thread priority to THREAD_PRIORITY_AUDIO */ extern void Android_JNI_AudioSetThreadPriority(int, int); Android_JNI_AudioSetThreadPriority(device->iscapture, device->id); } #else /* The audio mixing is always a high priority thread */ SDL_SetThreadPriority(SDL_THREAD_PRIORITY_TIME_CRITICAL); #endif /* Perform any thread setup */ device->threadid = SDL_ThreadID(); current_audio.impl.ThreadInit(device); /* Loop, filling the audio buffers */ while (!SDL_AtomicGet(&device->shutdown)) { current_audio.impl.BeginLoopIteration(device); data_len = device->callbackspec.size; /* Fill the current buffer with sound */ if (!device->stream && SDL_AtomicGet(&device->enabled)) { SDL_assert(data_len == device->spec.size); data = current_audio.impl.GetDeviceBuf(device); } else { /* if the device isn't enabled, we still write to the work_buffer, so the app's callback will fire with a regular frequency, in case they depend on that for timing or progress. They can use hotplug now to know if the device failed. Streaming playback uses work_buffer, too. */ data = NULL; } if (data == NULL) { data = device->work_buffer; } /* !!! FIXME: this should be LockDevice. */ SDL_LockMutex(device->mixer_lock); if (SDL_AtomicGet(&device->paused)) { SDL_memset(data, device->spec.silence, data_len); } else { callback(udata, data, data_len); } SDL_UnlockMutex(device->mixer_lock); if (device->stream) { /* Stream available audio to device, converting/resampling. */ /* if this fails...oh well. We'll play silence here. */ SDL_AudioStreamPut(device->stream, data, data_len); while (SDL_AudioStreamAvailable(device->stream) >= ((int) device->spec.size)) { int got; data = SDL_AtomicGet(&device->enabled) ? current_audio.impl.GetDeviceBuf(device) : NULL; got = SDL_AudioStreamGet(device->stream, data ? data : device->work_buffer, device->spec.size); SDL_assert((got < 0) || (got == device->spec.size)); if (data == NULL) { /* device is having issues... */ const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq); SDL_Delay(delay); /* wait for as long as this buffer would have played. Maybe device recovers later? */ } else { if (got != device->spec.size) { SDL_memset(data, device->spec.silence, device->spec.size); } current_audio.impl.PlayDevice(device); current_audio.impl.WaitDevice(device); } } } else if (data == device->work_buffer) { /* nothing to do; pause like we queued a buffer to play. */ const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq); SDL_Delay(delay); } else { /* writing directly to the device. */ /* queue this buffer and wait for it to finish playing. */ current_audio.impl.PlayDevice(device); current_audio.impl.WaitDevice(device); } } current_audio.impl.PrepareToClose(device); /* Wait for the audio to drain. */ SDL_Delay(((device->spec.samples * 1000) / device->spec.freq) * 2); current_audio.impl.ThreadDeinit(device); return 0; } /* !!! FIXME: this needs to deal with device spec changes. */ /* The general capture thread function */ static int SDLCALL SDL_CaptureAudio(void *devicep) { SDL_AudioDevice *device = (SDL_AudioDevice *) devicep; const int silence = (int) device->spec.silence; const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq); const int data_len = device->spec.size; Uint8 *data; void *udata = device->callbackspec.userdata; SDL_AudioCallback callback = device->callbackspec.callback; SDL_assert(device->iscapture); #if SDL_AUDIO_DRIVER_ANDROID { /* Set thread priority to THREAD_PRIORITY_AUDIO */ extern void Android_JNI_AudioSetThreadPriority(int, int); Android_JNI_AudioSetThreadPriority(device->iscapture, device->id); } #else /* The audio mixing is always a high priority thread */ SDL_SetThreadPriority(SDL_THREAD_PRIORITY_HIGH); #endif /* Perform any thread setup */ device->threadid = SDL_ThreadID(); current_audio.impl.ThreadInit(device); /* Loop, filling the audio buffers */ while (!SDL_AtomicGet(&device->shutdown)) { int still_need; Uint8 *ptr; current_audio.impl.BeginLoopIteration(device); if (SDL_AtomicGet(&device->paused)) { SDL_Delay(delay); /* just so we don't cook the CPU. */ if (device->stream) { SDL_AudioStreamClear(device->stream); } current_audio.impl.FlushCapture(device); /* dump anything pending. */ continue; } /* Fill the current buffer with sound */ still_need = data_len; /* Use the work_buffer to hold data read from the device. */ data = device->work_buffer; SDL_assert(data != NULL); ptr = data; /* We still read from the device when "paused" to keep the state sane, and block when there isn't data so this thread isn't eating CPU. But we don't process it further or call the app's callback. */ if (!SDL_AtomicGet(&device->enabled)) { SDL_Delay(delay); /* try to keep callback firing at normal pace. */ } else { while (still_need > 0) { const int rc = current_audio.impl.CaptureFromDevice(device, ptr, still_need); SDL_assert(rc <= still_need); /* device should not overflow buffer. :) */ if (rc > 0) { still_need -= rc; ptr += rc; } else { /* uhoh, device failed for some reason! */ SDL_OpenedAudioDeviceDisconnected(device); break; } } } if (still_need > 0) { /* Keep any data we already read, silence the rest. */ SDL_memset(ptr, silence, still_need); } if (device->stream) { /* if this fails...oh well. */ SDL_AudioStreamPut(device->stream, data, data_len); while (SDL_AudioStreamAvailable(device->stream) >= ((int) device->callbackspec.size)) { const int got = SDL_AudioStreamGet(device->stream, device->work_buffer, device->callbackspec.size); SDL_assert((got < 0) || (got == device->callbackspec.size)); if (got != device->callbackspec.size) { SDL_memset(device->work_buffer, device->spec.silence, device->callbackspec.size); } /* !!! FIXME: this should be LockDevice. */ SDL_LockMutex(device->mixer_lock); if (!SDL_AtomicGet(&device->paused)) { callback(udata, device->work_buffer, device->callbackspec.size); } SDL_UnlockMutex(device->mixer_lock); } } else { /* feeding user callback directly without streaming. */ /* !!! FIXME: this should be LockDevice. */ SDL_LockMutex(device->mixer_lock); if (!SDL_AtomicGet(&device->paused)) { callback(udata, data, device->callbackspec.size); } SDL_UnlockMutex(device->mixer_lock); } } current_audio.impl.FlushCapture(device); current_audio.impl.ThreadDeinit(device); return 0; } static SDL_AudioFormat SDL_ParseAudioFormat(const char *string) { #define CHECK_FMT_STRING(x) if (SDL_strcmp(string, #x) == 0) return AUDIO_##x CHECK_FMT_STRING(U8); CHECK_FMT_STRING(S8); CHECK_FMT_STRING(U16LSB); CHECK_FMT_STRING(S16LSB); CHECK_FMT_STRING(U16MSB); CHECK_FMT_STRING(S16MSB); CHECK_FMT_STRING(U16SYS); CHECK_FMT_STRING(S16SYS); CHECK_FMT_STRING(U16); CHECK_FMT_STRING(S16); CHECK_FMT_STRING(S32LSB); CHECK_FMT_STRING(S32MSB); CHECK_FMT_STRING(S32SYS); CHECK_FMT_STRING(S32); CHECK_FMT_STRING(F32LSB); CHECK_FMT_STRING(F32MSB); CHECK_FMT_STRING(F32SYS); CHECK_FMT_STRING(F32); #undef CHECK_FMT_STRING return 0; } int SDL_GetNumAudioDrivers(void) { return SDL_arraysize(bootstrap) - 1; } const char * SDL_GetAudioDriver(int index) { if (index >= 0 && index < SDL_GetNumAudioDrivers()) { return bootstrap[index]->name; } return NULL; } int SDL_AudioInit(const char *driver_name) { int i = 0; int initialized = 0; int tried_to_init = 0; if (SDL_WasInit(SDL_INIT_AUDIO)) { SDL_AudioQuit(); /* shutdown driver if already running. */ } SDL_zero(current_audio); SDL_zeroa(open_devices); /* Select the proper audio driver */ if (driver_name == NULL) { driver_name = SDL_getenv("SDL_AUDIODRIVER"); } for (i = 0; (!initialized) && (bootstrap[i]); ++i) { /* make sure we should even try this driver before doing so... */ const AudioBootStrap *backend = bootstrap[i]; if ((driver_name && (SDL_strncasecmp(backend->name, driver_name, SDL_strlen(driver_name)) != 0)) || (!driver_name && backend->demand_only)) { continue; } tried_to_init = 1; SDL_zero(current_audio); current_audio.name = backend->name; current_audio.desc = backend->desc; initialized = backend->init(&current_audio.impl); } if (!initialized) { /* specific drivers will set the error message if they fail... */ if (!tried_to_init) { if (driver_name) { SDL_SetError("Audio target '%s' not available", driver_name); } else { SDL_SetError("No available audio device"); } } SDL_zero(current_audio); return -1; /* No driver was available, so fail. */ } current_audio.detectionLock = SDL_CreateMutex(); finish_audio_entry_points_init(); /* Make sure we have a list of devices available at startup. */ current_audio.impl.DetectDevices(); #ifdef HAVE_LIBSAMPLERATE_H LoadLibSampleRate(); #endif return 0; } /* * Get the current audio driver name */ const char * SDL_GetCurrentAudioDriver() { return current_audio.name; } /* Clean out devices that we've removed but had to keep around for stability. */ static void clean_out_device_list(SDL_AudioDeviceItem **devices, int *devCount, SDL_bool *removedFlag) { SDL_AudioDeviceItem *item = *devices; SDL_AudioDeviceItem *prev = NULL; int total = 0; while (item) { SDL_AudioDeviceItem *next = item->next; if (item->handle != NULL) { total++; prev = item; } else { if (prev) { prev->next = next; } 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; } *devCount = total; *removedFlag = SDL_FALSE; } int SDL_GetNumAudioDevices(int iscapture) { int retval = 0; if (!SDL_WasInit(SDL_INIT_AUDIO)) { return -1; } SDL_LockMutex(current_audio.detectionLock); if (iscapture && current_audio.captureDevicesRemoved) { clean_out_device_list(&current_audio.inputDevices, &current_audio.inputDeviceCount, &current_audio.captureDevicesRemoved); } if (!iscapture && current_audio.outputDevicesRemoved) { clean_out_device_list(&current_audio.outputDevices, &current_audio.outputDeviceCount, &current_audio.outputDevicesRemoved); } retval = iscapture ? current_audio.inputDeviceCount : current_audio.outputDeviceCount; SDL_UnlockMutex(current_audio.detectionLock); return retval; } const char * SDL_GetAudioDeviceName(int index, int iscapture) { const char *retval = NULL; if (!SDL_WasInit(SDL_INIT_AUDIO)) { SDL_SetError("Audio subsystem is not initialized"); return NULL; } if (iscapture && !current_audio.impl.HasCaptureSupport) { SDL_SetError("No capture support"); return NULL; } if (index >= 0) { SDL_AudioDeviceItem *item; int i; SDL_LockMutex(current_audio.detectionLock); item = iscapture ? current_audio.inputDevices : current_audio.outputDevices; i = iscapture ? current_audio.inputDeviceCount : current_audio.outputDeviceCount; if (index < i) { for (i--; i > index; i--, item = item->next) { SDL_assert(item != NULL); } SDL_assert(item != NULL); retval = item->name; } SDL_UnlockMutex(current_audio.detectionLock); } if (retval == NULL) { SDL_SetError("No such device"); } return retval; } static void close_audio_device(SDL_AudioDevice * device) { if (!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); SDL_AtomicSet(&device->shutdown, 1); SDL_AtomicSet(&device->enabled, 0); current_audio.impl.UnlockDevice(device); if (device->thread != NULL) { SDL_WaitThread(device->thread, NULL); } if (device->mixer_lock != NULL) { SDL_DestroyMutex(device->mixer_lock); } 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); } SDL_FreeDataQueue(device->buffer_queue); SDL_free(device); } /* * Sanity check desired AudioSpec for SDL_OpenAudio() in (orig). * Fills in a sanitized copy in (prepared). * Returns non-zero if okay, zero on fatal parameters in (orig). */ static int prepare_audiospec(const SDL_AudioSpec * orig, SDL_AudioSpec * prepared) { SDL_memcpy(prepared, orig, sizeof(SDL_AudioSpec)); if (orig->freq == 0) { const char *env = SDL_getenv("SDL_AUDIO_FREQUENCY"); if ((!env) || ((prepared->freq = SDL_atoi(env)) == 0)) { prepared->freq = 22050; /* a reasonable default */ } } if (orig->format == 0) { const char *env = SDL_getenv("SDL_AUDIO_FORMAT"); if ((!env) || ((prepared->format = SDL_ParseAudioFormat(env)) == 0)) { prepared->format = AUDIO_S16; /* a reasonable default */ } } switch (orig->channels) { case 0:{ const char *env = SDL_getenv("SDL_AUDIO_CHANNELS"); if ((!env) || ((prepared->channels = (Uint8) SDL_atoi(env)) == 0)) { prepared->channels = 2; /* a reasonable default */ } break; } case 1: /* Mono */ case 2: /* Stereo */ case 4: /* Quadrophonic */ case 6: /* 5.1 surround */ case 8: /* 7.1 surround */ break; default: SDL_SetError("Unsupported number of audio channels."); return 0; } if (orig->samples == 0) { const char *env = SDL_getenv("SDL_AUDIO_SAMPLES"); if ((!env) || ((prepared->samples = (Uint16) SDL_atoi(env)) == 0)) { /* Pick a default of ~46 ms at desired frequency */ /* !!! FIXME: remove this when the non-Po2 resampling is in. */ const int samples = (prepared->freq / 1000) * 46; int power2 = 1; while (power2 < samples) { power2 *= 2; } prepared->samples = power2; } } /* Calculate the silence and size of the audio specification */ SDL_CalculateAudioSpec(prepared); return 1; } static SDL_AudioDeviceID open_audio_device(const char *devname, int iscapture, const SDL_AudioSpec * desired, SDL_AudioSpec * obtained, int allowed_changes, int min_id) { const SDL_bool is_internal_thread = (desired->callback == NULL); SDL_AudioDeviceID id = 0; SDL_AudioSpec _obtained; SDL_AudioDevice *device; SDL_bool build_stream; void *handle = NULL; int i = 0; if (!SDL_WasInit(SDL_INIT_AUDIO)) { SDL_SetError("Audio subsystem is not initialized"); return 0; } if (iscapture && !current_audio.impl.HasCaptureSupport) { SDL_SetError("No capture support"); return 0; } /* !!! FIXME: there is a race condition here if two devices open from two threads at once. */ /* Find an available device ID... */ for (id = min_id - 1; id < SDL_arraysize(open_devices); id++) { if (open_devices[id] == NULL) { break; } } if (id == SDL_arraysize(open_devices)) { SDL_SetError("Too many open audio devices"); return 0; } if (!obtained) { obtained = &_obtained; } if (!prepare_audiospec(desired, obtained)) { return 0; } /* If app doesn't care about a specific device, let the user override. */ if (devname == NULL) { devname = SDL_getenv("SDL_AUDIO_DEVICE_NAME"); } /* * Catch device names at the high level for the simple case... * This lets us have a basic "device enumeration" for systems that * don't have multiple devices, but makes sure the device name is * always NULL when it hits the low level. * * Also make sure that the simple case prevents multiple simultaneous * opens of the default system device. */ if ((iscapture) && (current_audio.impl.OnlyHasDefaultCaptureDevice)) { if ((devname) && (SDL_strcmp(devname, DEFAULT_INPUT_DEVNAME) != 0)) { SDL_SetError("No such device"); return 0; } devname = NULL; for (i = 0; i < SDL_arraysize(open_devices); i++) { if ((open_devices[i]) && (open_devices[i]->iscapture)) { SDL_SetError("Audio device already open"); return 0; } } } else if ((!iscapture) && (current_audio.impl.OnlyHasDefaultOutputDevice)) { if ((devname) && (SDL_strcmp(devname, DEFAULT_OUTPUT_DEVNAME) != 0)) { SDL_SetError("No such device"); return 0; } devname = NULL; for (i = 0; i < SDL_arraysize(open_devices); i++) { if ((open_devices[i]) && (!open_devices[i]->iscapture)) { SDL_SetError("Audio device already open"); return 0; } } } else if (devname != NULL) { /* if the app specifies an exact string, we can pass the backend an actual device handle thingey, which saves them the effort of figuring out what device this was (such as, reenumerating everything again to find the matching human-readable name). It might still need to open a device based on the string for, say, a network audio server, but this optimizes some cases. */ SDL_AudioDeviceItem *item; SDL_LockMutex(current_audio.detectionLock); for (item = iscapture ? current_audio.inputDevices : current_audio.outputDevices; item; item = item->next) { if ((item->handle != NULL) && (SDL_strcmp(item->name, devname) == 0)) { handle = item->handle; break; } } SDL_UnlockMutex(current_audio.detectionLock); } if (!current_audio.impl.AllowsArbitraryDeviceNames) { /* has to be in our device list, or the default device. */ if ((handle == NULL) && (devname != NULL)) { SDL_SetError("No such device."); return 0; } } device = (SDL_AudioDevice *) SDL_calloc(1, sizeof (SDL_AudioDevice)); if (device == NULL) { SDL_OutOfMemory(); return 0; } device->id = id + 1; device->spec = *obtained; device->iscapture = iscapture ? SDL_TRUE : SDL_FALSE; device->handle = handle; SDL_AtomicSet(&device->shutdown, 0); /* just in case. */ SDL_AtomicSet(&device->paused, 1); SDL_AtomicSet(&device->enabled, 1); /* Create a mutex for locking the sound buffers */ if (!current_audio.impl.SkipMixerLock) { device->mixer_lock = SDL_CreateMutex(); if (device->mixer_lock == NULL) { close_audio_device(device); SDL_SetError("Couldn't create mixer lock"); return 0; } } if (current_audio.impl.OpenDevice(device, handle, devname, iscapture) < 0) { close_audio_device(device); return 0; } /* if your target really doesn't need it, set it to 0x1 or something. */ /* otherwise, close_audio_device() won't call impl.CloseDevice(). */ SDL_assert(device->hidden != NULL); /* See if we need to do any conversion */ build_stream = SDL_FALSE; if (obtained->freq != device->spec.freq) { if (allowed_changes & SDL_AUDIO_ALLOW_FREQUENCY_CHANGE) { obtained->freq = device->spec.freq; } else { build_stream = SDL_TRUE; } } if (obtained->format != device->spec.format) { if (allowed_changes & SDL_AUDIO_ALLOW_FORMAT_CHANGE) { obtained->format = device->spec.format; } else { build_stream = SDL_TRUE; } } if (obtained->channels != device->spec.channels) { if (allowed_changes & SDL_AUDIO_ALLOW_CHANNELS_CHANGE) { obtained->channels = device->spec.channels; } else { build_stream = SDL_TRUE; } } if (device->spec.samples != obtained->samples) { if (allowed_changes & SDL_AUDIO_ALLOW_SAMPLES_CHANGE) { obtained->samples = device->spec.samples; } else { build_stream = SDL_TRUE; } } SDL_CalculateAudioSpec(obtained); /* recalc after possible changes. */ device->callbackspec = *obtained; if (build_stream) { if (iscapture) { device->stream = SDL_NewAudioStream(device->spec.format, device->spec.channels, device->spec.freq, obtained->format, obtained->channels, obtained->freq); } else { device->stream = SDL_NewAudioStream(obtained->format, obtained->channels, obtained->freq, device->spec.format, device->spec.channels, device->spec.freq); } if (!device->stream) { close_audio_device(device); return 0; } } if (device->spec.callback == NULL) { /* use buffer queueing? */ /* pool a few packets to start. Enough for two callbacks. */ device->buffer_queue = SDL_NewDataQueue(SDL_AUDIOBUFFERQUEUE_PACKETLEN, obtained->size * 2); if (!device->buffer_queue) { close_audio_device(device); SDL_SetError("Couldn't create audio buffer queue"); return 0; } device->callbackspec.callback = iscapture ? SDL_BufferQueueFillCallback : SDL_BufferQueueDrainCallback; device->callbackspec.userdata = device; } /* Allocate a scratch audio buffer */ device->work_buffer_len = build_stream ? device->callbackspec.size : 0; if (device->spec.size > device->work_buffer_len) { device->work_buffer_len = device->spec.size; } SDL_assert(device->work_buffer_len > 0); device->work_buffer = (Uint8 *) SDL_malloc(device->work_buffer_len); if (device->work_buffer == NULL) { close_audio_device(device); SDL_OutOfMemory(); return 0; } open_devices[id] = device; /* add it to our list of open devices. */ /* Start the audio thread if necessary */ if (!current_audio.impl.ProvidesOwnCallbackThread) { /* Start the audio thread */ /* !!! FIXME: we don't force the audio thread stack size here if it calls into user code, but maybe we should? */ /* buffer queueing callback only needs a few bytes, so make the stack tiny. */ const size_t stacksize = is_internal_thread ? 64 * 1024 : 0; char threadname[64]; SDL_snprintf(threadname, sizeof (threadname), "SDLAudio%c%d", (iscapture) ? 'C' : 'P', (int) device->id); device->thread = SDL_CreateThreadInternal(iscapture ? SDL_CaptureAudio : SDL_RunAudio, threadname, stacksize, device); if (device->thread == NULL) { close_audio_device(device); SDL_SetError("Couldn't create audio thread"); return 0; } } return device->id; } int SDL_OpenAudio(SDL_AudioSpec * desired, SDL_AudioSpec * obtained) { SDL_AudioDeviceID id = 0; /* Start up the audio driver, if necessary. This is legacy behaviour! */ if (!SDL_WasInit(SDL_INIT_AUDIO)) { if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { return -1; } } /* SDL_OpenAudio() is legacy and can only act on Device ID #1. */ if (open_devices[0] != NULL) { SDL_SetError("Audio device is already opened"); return -1; } if (obtained) { id = open_audio_device(NULL, 0, desired, obtained, SDL_AUDIO_ALLOW_ANY_CHANGE, 1); } else { SDL_AudioSpec _obtained; SDL_zero(_obtained); id = open_audio_device(NULL, 0, desired, &_obtained, 0, 1); /* On successful open, copy calculated values into 'desired'. */ if (id > 0) { desired->size = _obtained.size; desired->silence = _obtained.silence; } } SDL_assert((id == 0) || (id == 1)); return (id == 0) ? -1 : 0; } SDL_AudioDeviceID SDL_OpenAudioDevice(const char *device, int iscapture, const SDL_AudioSpec * desired, SDL_AudioSpec * obtained, int allowed_changes) { return open_audio_device(device, iscapture, desired, obtained, allowed_changes, 2); } SDL_AudioStatus SDL_GetAudioDeviceStatus(SDL_AudioDeviceID devid) { SDL_AudioDevice *device = get_audio_device(devid); SDL_AudioStatus status = SDL_AUDIO_STOPPED; if (device && SDL_AtomicGet(&device->enabled)) { if (SDL_AtomicGet(&device->paused)) { status = SDL_AUDIO_PAUSED; } else { status = SDL_AUDIO_PLAYING; } } return status; } SDL_AudioStatus SDL_GetAudioStatus(void) { return SDL_GetAudioDeviceStatus(1); } void SDL_PauseAudioDevice(SDL_AudioDeviceID devid, int pause_on) { SDL_AudioDevice *device = get_audio_device(devid); if (device) { current_audio.impl.LockDevice(device); SDL_AtomicSet(&device->paused, pause_on ? 1 : 0); current_audio.impl.UnlockDevice(device); } } void SDL_PauseAudio(int pause_on) { SDL_PauseAudioDevice(1, pause_on); } void SDL_LockAudioDevice(SDL_AudioDeviceID devid) { /* Obtain a lock on the mixing buffers */ SDL_AudioDevice *device = get_audio_device(devid); if (device) { current_audio.impl.LockDevice(device); } } void SDL_LockAudio(void) { SDL_LockAudioDevice(1); } void SDL_UnlockAudioDevice(SDL_AudioDeviceID devid) { /* Obtain a lock on the mixing buffers */ SDL_AudioDevice *device = get_audio_device(devid); if (device) { current_audio.impl.UnlockDevice(device); } } void SDL_UnlockAudio(void) { SDL_UnlockAudioDevice(1); } void SDL_CloseAudioDevice(SDL_AudioDeviceID devid) { close_audio_device(get_audio_device(devid)); } void SDL_CloseAudio(void) { SDL_CloseAudioDevice(1); } void SDL_AudioQuit(void) { SDL_AudioDeviceID i; if (!current_audio.name) { /* not initialized?! */ return; } for (i = 0; i < SDL_arraysize(open_devices); i++) { close_audio_device(open_devices[i]); } free_device_list(&current_audio.outputDevices, &current_audio.outputDeviceCount); free_device_list(&current_audio.inputDevices, &current_audio.inputDeviceCount); /* Free the driver data */ current_audio.impl.Deinitialize(); SDL_DestroyMutex(current_audio.detectionLock); SDL_zero(current_audio); SDL_zeroa(open_devices); #ifdef HAVE_LIBSAMPLERATE_H UnloadLibSampleRate(); #endif SDL_FreeResampleFilter(); } #define NUM_FORMATS 10 static int format_idx; static int format_idx_sub; static SDL_AudioFormat format_list[NUM_FORMATS][NUM_FORMATS] = { {AUDIO_U8, AUDIO_S8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB}, {AUDIO_S8, AUDIO_U8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB}, {AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8}, {AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8}, {AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8}, {AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8}, {AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8}, {AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8}, {AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8}, {AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8}, }; SDL_AudioFormat SDL_FirstAudioFormat(SDL_AudioFormat format) { for (format_idx = 0; format_idx < NUM_FORMATS; ++format_idx) { if (format_list[format_idx][0] == format) { break; } } format_idx_sub = 0; return SDL_NextAudioFormat(); } SDL_AudioFormat SDL_NextAudioFormat(void) { if ((format_idx == NUM_FORMATS) || (format_idx_sub == NUM_FORMATS)) { return 0; } return format_list[format_idx][format_idx_sub++]; } Uint8 SDL_SilenceValueForFormat(const SDL_AudioFormat format) { switch (format) { /* !!! FIXME: 0x80 isn't perfect for U16, but we can't fit 0x8000 in a !!! FIXME: byte for memset() use. This is actually 0.1953 percent !!! FIXME: off from silence. Maybe just don't use U16. */ case AUDIO_U16LSB: case AUDIO_U16MSB: case AUDIO_U8: return 0x80; default: break; } return 0x00; } void SDL_CalculateAudioSpec(SDL_AudioSpec * spec) { spec->silence = SDL_SilenceValueForFormat(spec->format); spec->size = SDL_AUDIO_BITSIZE(spec->format) / 8; spec->size *= spec->channels; spec->size *= spec->samples; } /* * Moved here from SDL_mixer.c, since it relies on internals of an opened * audio device (and is deprecated, by the way!). */ void SDL_MixAudio(Uint8 * dst, const Uint8 * src, Uint32 len, int volume) { /* Mix the user-level audio format */ SDL_AudioDevice *device = get_audio_device(1); if (device != NULL) { SDL_MixAudioFormat(dst, src, device->callbackspec.format, len, volume); } } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/SDL_audio.c
C
apache-2.0
52,455
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ #ifndef SDL_audio_c_h_ #define SDL_audio_c_h_ #include "../SDL_internal.h" #ifndef DEBUG_CONVERT #define DEBUG_CONVERT 0 #endif #if DEBUG_CONVERT #define LOG_DEBUG_CONVERT(from, to) fprintf(stderr, "Converting %s to %s.\n", from, to); #else #define LOG_DEBUG_CONVERT(from, to) #endif /* Functions and variables exported from SDL_audio.c for SDL_sysaudio.c */ #ifdef HAVE_LIBSAMPLERATE_H #include "samplerate.h" extern SDL_bool SRC_available; extern int SRC_converter; extern SRC_STATE* (*SRC_src_new)(int converter_type, int channels, int *error); extern int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data); extern int (*SRC_src_reset)(SRC_STATE *state); extern SRC_STATE* (*SRC_src_delete)(SRC_STATE *state); extern const char* (*SRC_src_strerror)(int error); #endif /* Functions to get a list of "close" audio formats */ extern SDL_AudioFormat SDL_FirstAudioFormat(SDL_AudioFormat format); extern SDL_AudioFormat SDL_NextAudioFormat(void); /* Function to calculate the size and silence for a SDL_AudioSpec */ extern Uint8 SDL_SilenceValueForFormat(const SDL_AudioFormat format); extern void SDL_CalculateAudioSpec(SDL_AudioSpec * spec); /* Choose the audio filter functions below */ extern void SDL_ChooseAudioConverters(void); /* These pointers get set during SDL_ChooseAudioConverters() to various SIMD implementations. */ extern SDL_AudioFilter SDL_Convert_S8_to_F32; extern SDL_AudioFilter SDL_Convert_U8_to_F32; extern SDL_AudioFilter SDL_Convert_S16_to_F32; extern SDL_AudioFilter SDL_Convert_U16_to_F32; extern SDL_AudioFilter SDL_Convert_S32_to_F32; extern SDL_AudioFilter SDL_Convert_F32_to_S8; extern SDL_AudioFilter SDL_Convert_F32_to_U8; extern SDL_AudioFilter SDL_Convert_F32_to_S16; extern SDL_AudioFilter SDL_Convert_F32_to_U16; extern SDL_AudioFilter SDL_Convert_F32_to_S32; /* You need to call SDL_PrepareResampleFilter() before using the internal resampler. SDL_AudioQuit() calls SDL_FreeResamplerFilter(), you should never call it yourself. */ extern int SDL_PrepareResampleFilter(void); extern void SDL_FreeResampleFilter(void); #endif /* SDL_audio_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/SDL_audio_c.h
C
apache-2.0
3,074
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" /* Functions for audio drivers to perform runtime conversion of audio format */ /* FIXME: Channel weights when converting from more channels to fewer may need to be adjusted, see https://msdn.microsoft.com/en-us/library/windows/desktop/ff819070(v=vs.85).aspx */ #include "SDL.h" #include "SDL_audio.h" #include "SDL_audio_c.h" #include "SDL_loadso.h" #include "SDL_assert.h" #include "../SDL_dataqueue.h" #include "SDL_cpuinfo.h" #define DEBUG_AUDIOSTREAM 0 #ifdef __SSE3__ #define HAVE_SSE3_INTRINSICS 1 #endif #if HAVE_SSE3_INTRINSICS /* Convert from stereo to mono. Average left and right. */ static void SDLCALL SDL_ConvertStereoToMono_SSE3(SDL_AudioCVT * cvt, SDL_AudioFormat format) { float *dst = (float *) cvt->buf; const float *src = dst; int i = cvt->len_cvt / 8; LOG_DEBUG_CONVERT("stereo", "mono (using SSE3)"); SDL_assert(format == AUDIO_F32SYS); /* We can only do this if dst is aligned to 16 bytes; since src is the same pointer and it moves by 2, it can't be forcibly aligned. */ if ((((size_t) dst) & 15) == 0) { /* Aligned! Do SSE blocks as long as we have 16 bytes available. */ const __m128 divby2 = _mm_set1_ps(0.5f); while (i >= 4) { /* 4 * float32 */ _mm_store_ps(dst, _mm_mul_ps(_mm_hadd_ps(_mm_load_ps(src), _mm_load_ps(src+4)), divby2)); i -= 4; src += 8; dst += 4; } } /* Finish off any leftovers with scalar operations. */ while (i) { *dst = (src[0] + src[1]) * 0.5f; dst++; i--; src += 2; } cvt->len_cvt /= 2; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } #endif /* Convert from stereo to mono. Average left and right. */ static void SDLCALL SDL_ConvertStereoToMono(SDL_AudioCVT * cvt, SDL_AudioFormat format) { float *dst = (float *) cvt->buf; const float *src = dst; int i; LOG_DEBUG_CONVERT("stereo", "mono"); SDL_assert(format == AUDIO_F32SYS); for (i = cvt->len_cvt / 8; i; --i, src += 2) { *(dst++) = (src[0] + src[1]) * 0.5f; } cvt->len_cvt /= 2; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } /* Convert from 5.1 to stereo. Average left and right, distribute center, discard LFE. */ static void SDLCALL SDL_Convert51ToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format) { float *dst = (float *) cvt->buf; const float *src = dst; int i; LOG_DEBUG_CONVERT("5.1", "stereo"); SDL_assert(format == AUDIO_F32SYS); /* SDL's 5.1 layout: FL+FR+FC+LFE+BL+BR */ for (i = cvt->len_cvt / (sizeof (float) * 6); i; --i, src += 6, dst += 2) { const float front_center_distributed = src[2] * 0.5f; dst[0] = (src[0] + front_center_distributed + src[4]) / 2.5f; /* left */ dst[1] = (src[1] + front_center_distributed + src[5]) / 2.5f; /* right */ } cvt->len_cvt /= 3; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } /* Convert from quad to stereo. Average left and right. */ static void SDLCALL SDL_ConvertQuadToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format) { float *dst = (float *) cvt->buf; const float *src = dst; int i; LOG_DEBUG_CONVERT("quad", "stereo"); SDL_assert(format == AUDIO_F32SYS); for (i = cvt->len_cvt / (sizeof (float) * 4); i; --i, src += 4, dst += 2) { dst[0] = (src[0] + src[2]) * 0.5f; /* left */ dst[1] = (src[1] + src[3]) * 0.5f; /* right */ } cvt->len_cvt /= 2; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } /* Convert from 7.1 to 5.1. Distribute sides across front and back. */ static void SDLCALL SDL_Convert71To51(SDL_AudioCVT * cvt, SDL_AudioFormat format) { float *dst = (float *) cvt->buf; const float *src = dst; int i; LOG_DEBUG_CONVERT("7.1", "5.1"); SDL_assert(format == AUDIO_F32SYS); for (i = cvt->len_cvt / (sizeof (float) * 8); i; --i, src += 8, dst += 6) { const float surround_left_distributed = src[6] * 0.5f; const float surround_right_distributed = src[7] * 0.5f; dst[0] = (src[0] + surround_left_distributed) / 1.5f; /* FL */ dst[1] = (src[1] + surround_right_distributed) / 1.5f; /* FR */ dst[2] = src[2] / 1.5f; /* CC */ dst[3] = src[3] / 1.5f; /* LFE */ dst[4] = (src[4] + surround_left_distributed) / 1.5f; /* BL */ dst[5] = (src[5] + surround_right_distributed) / 1.5f; /* BR */ } cvt->len_cvt /= 8; cvt->len_cvt *= 6; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } /* Convert from 5.1 to quad. Distribute center across front, discard LFE. */ static void SDLCALL SDL_Convert51ToQuad(SDL_AudioCVT * cvt, SDL_AudioFormat format) { float *dst = (float *) cvt->buf; const float *src = dst; int i; LOG_DEBUG_CONVERT("5.1", "quad"); SDL_assert(format == AUDIO_F32SYS); /* SDL's 4.0 layout: FL+FR+BL+BR */ /* SDL's 5.1 layout: FL+FR+FC+LFE+BL+BR */ for (i = cvt->len_cvt / (sizeof (float) * 6); i; --i, src += 6, dst += 4) { const float front_center_distributed = src[2] * 0.5f; dst[0] = (src[0] + front_center_distributed) / 1.5f; /* FL */ dst[1] = (src[1] + front_center_distributed) / 1.5f; /* FR */ dst[2] = src[4] / 1.5f; /* BL */ dst[3] = src[5] / 1.5f; /* BR */ } cvt->len_cvt /= 6; cvt->len_cvt *= 4; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } /* Upmix mono to stereo (by duplication) */ static void SDLCALL SDL_ConvertMonoToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format) { const float *src = (const float *) (cvt->buf + cvt->len_cvt); float *dst = (float *) (cvt->buf + cvt->len_cvt * 2); int i; LOG_DEBUG_CONVERT("mono", "stereo"); SDL_assert(format == AUDIO_F32SYS); for (i = cvt->len_cvt / sizeof (float); i; --i) { src--; dst -= 2; dst[0] = dst[1] = *src; } cvt->len_cvt *= 2; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } /* Upmix stereo to a pseudo-5.1 stream */ static void SDLCALL SDL_ConvertStereoTo51(SDL_AudioCVT * cvt, SDL_AudioFormat format) { int i; float lf, rf, ce; const float *src = (const float *) (cvt->buf + cvt->len_cvt); float *dst = (float *) (cvt->buf + cvt->len_cvt * 3); LOG_DEBUG_CONVERT("stereo", "5.1"); SDL_assert(format == AUDIO_F32SYS); for (i = cvt->len_cvt / (sizeof(float) * 2); i; --i) { dst -= 6; src -= 2; lf = src[0]; rf = src[1]; ce = (lf + rf) * 0.5f; /* !!! FIXME: FL and FR may clip */ dst[0] = lf + (lf - ce); /* FL */ dst[1] = rf + (rf - ce); /* FR */ dst[2] = ce; /* FC */ dst[3] = 0; /* LFE (only meant for special LFE effects) */ dst[4] = lf; /* BL */ dst[5] = rf; /* BR */ } cvt->len_cvt *= 3; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } /* Upmix quad to a pseudo-5.1 stream */ static void SDLCALL SDL_ConvertQuadTo51(SDL_AudioCVT * cvt, SDL_AudioFormat format) { int i; float lf, rf, lb, rb, ce; const float *src = (const float *) (cvt->buf + cvt->len_cvt); float *dst = (float *) (cvt->buf + cvt->len_cvt * 3 / 2); LOG_DEBUG_CONVERT("quad", "5.1"); SDL_assert(format == AUDIO_F32SYS); SDL_assert(cvt->len_cvt % (sizeof(float) * 4) == 0); for (i = cvt->len_cvt / (sizeof(float) * 4); i; --i) { dst -= 6; src -= 4; lf = src[0]; rf = src[1]; lb = src[2]; rb = src[3]; ce = (lf + rf) * 0.5f; /* !!! FIXME: FL and FR may clip */ dst[0] = lf + (lf - ce); /* FL */ dst[1] = rf + (rf - ce); /* FR */ dst[2] = ce; /* FC */ dst[3] = 0; /* LFE (only meant for special LFE effects) */ dst[4] = lb; /* BL */ dst[5] = rb; /* BR */ } cvt->len_cvt = cvt->len_cvt * 3 / 2; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } /* Upmix stereo to a pseudo-4.0 stream (by duplication) */ static void SDLCALL SDL_ConvertStereoToQuad(SDL_AudioCVT * cvt, SDL_AudioFormat format) { const float *src = (const float *) (cvt->buf + cvt->len_cvt); float *dst = (float *) (cvt->buf + cvt->len_cvt * 2); float lf, rf; int i; LOG_DEBUG_CONVERT("stereo", "quad"); SDL_assert(format == AUDIO_F32SYS); for (i = cvt->len_cvt / (sizeof(float) * 2); i; --i) { dst -= 4; src -= 2; lf = src[0]; rf = src[1]; dst[0] = lf; /* FL */ dst[1] = rf; /* FR */ dst[2] = lf; /* BL */ dst[3] = rf; /* BR */ } cvt->len_cvt *= 2; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } /* Upmix 5.1 to 7.1 */ static void SDLCALL SDL_Convert51To71(SDL_AudioCVT * cvt, SDL_AudioFormat format) { float lf, rf, lb, rb, ls, rs; int i; const float *src = (const float *) (cvt->buf + cvt->len_cvt); float *dst = (float *) (cvt->buf + cvt->len_cvt * 4 / 3); LOG_DEBUG_CONVERT("5.1", "7.1"); SDL_assert(format == AUDIO_F32SYS); SDL_assert(cvt->len_cvt % (sizeof(float) * 6) == 0); for (i = cvt->len_cvt / (sizeof(float) * 6); i; --i) { dst -= 8; src -= 6; lf = src[0]; rf = src[1]; lb = src[4]; rb = src[5]; ls = (lf + lb) * 0.5f; rs = (rf + rb) * 0.5f; /* !!! FIXME: these four may clip */ lf += lf - ls; rf += rf - ls; lb += lb - ls; rb += rb - ls; dst[3] = src[3]; /* LFE */ dst[2] = src[2]; /* FC */ dst[7] = rs; /* SR */ dst[6] = ls; /* SL */ dst[5] = rb; /* BR */ dst[4] = lb; /* BL */ dst[1] = rf; /* FR */ dst[0] = lf; /* FL */ } cvt->len_cvt = cvt->len_cvt * 4 / 3; if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index] (cvt, format); } } /* SDL's resampler uses a "bandlimited interpolation" algorithm: https://ccrma.stanford.edu/~jos/resample/ */ #define RESAMPLER_ZERO_CROSSINGS 5 #define RESAMPLER_BITS_PER_SAMPLE 16 #define RESAMPLER_SAMPLES_PER_ZERO_CROSSING (1 << ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1)) #define RESAMPLER_FILTER_SIZE ((RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS) + 1) /* This is a "modified" bessel function, so you can't use POSIX j0() */ static double bessel(const double x) { const double xdiv2 = x / 2.0; double i0 = 1.0f; double f = 1.0f; int i = 1; while (SDL_TRUE) { const double diff = SDL_pow(xdiv2, i * 2) / SDL_pow(f, 2); if (diff < 1.0e-21f) { break; } i0 += diff; i++; f *= (double) i; } return i0; } /* build kaiser table with cardinal sine applied to it, and array of differences between elements. */ static void kaiser_and_sinc(float *table, float *diffs, const int tablelen, const double beta) { const int lenm1 = tablelen - 1; const int lenm1div2 = lenm1 / 2; int i; table[0] = 1.0f; for (i = 1; i < tablelen; i++) { const double kaiser = bessel(beta * SDL_sqrt(1.0 - SDL_pow(((i - lenm1) / 2.0) / lenm1div2, 2.0))) / bessel(beta); table[tablelen - i] = (float) kaiser; } for (i = 1; i < tablelen; i++) { const float x = (((float) i) / ((float) RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) * ((float) M_PI); table[i] *= SDL_sinf(x) / x; diffs[i - 1] = table[i] - table[i - 1]; } diffs[lenm1] = 0.0f; } static SDL_SpinLock ResampleFilterSpinlock = 0; static float *ResamplerFilter = NULL; static float *ResamplerFilterDifference = NULL; int SDL_PrepareResampleFilter(void) { SDL_AtomicLock(&ResampleFilterSpinlock); if (!ResamplerFilter) { /* if dB > 50, beta=(0.1102 * (dB - 8.7)), according to Matlab. */ const double dB = 80.0; const double beta = 0.1102 * (dB - 8.7); const size_t alloclen = RESAMPLER_FILTER_SIZE * sizeof (float); ResamplerFilter = (float *) SDL_malloc(alloclen); if (!ResamplerFilter) { SDL_AtomicUnlock(&ResampleFilterSpinlock); return SDL_OutOfMemory(); } ResamplerFilterDifference = (float *) SDL_malloc(alloclen); if (!ResamplerFilterDifference) { SDL_free(ResamplerFilter); ResamplerFilter = NULL; SDL_AtomicUnlock(&ResampleFilterSpinlock); return SDL_OutOfMemory(); } kaiser_and_sinc(ResamplerFilter, ResamplerFilterDifference, RESAMPLER_FILTER_SIZE, beta); } SDL_AtomicUnlock(&ResampleFilterSpinlock); return 0; } void SDL_FreeResampleFilter(void) { SDL_free(ResamplerFilter); SDL_free(ResamplerFilterDifference); ResamplerFilter = NULL; ResamplerFilterDifference = NULL; } static int ResamplerPadding(const int inrate, const int outrate) { if (inrate == outrate) { return 0; } else if (inrate > outrate) { return (int) SDL_ceil(((float) (RESAMPLER_SAMPLES_PER_ZERO_CROSSING * inrate) / ((float) outrate))); } return RESAMPLER_SAMPLES_PER_ZERO_CROSSING; } /* lpadding and rpadding are expected to be buffers of (ResamplePadding(inrate, outrate) * chans * sizeof (float)) bytes. */ static int SDL_ResampleAudio(const int chans, const int inrate, const int outrate, const float *lpadding, const float *rpadding, const float *inbuf, const int inbuflen, float *outbuf, const int outbuflen) { const double finrate = (double) inrate; const double outtimeincr = 1.0 / ((float) outrate); const double ratio = ((float) outrate) / ((float) inrate); const int paddinglen = ResamplerPadding(inrate, outrate); const int framelen = chans * (int)sizeof (float); const int inframes = inbuflen / framelen; const int wantedoutframes = (int) ((inbuflen / framelen) * ratio); /* outbuflen isn't total to write, it's total available. */ const int maxoutframes = outbuflen / framelen; const int outframes = SDL_min(wantedoutframes, maxoutframes); float *dst = outbuf; double outtime = 0.0; int i, j, chan; for (i = 0; i < outframes; i++) { const int srcindex = (int) (outtime * inrate); const double intime = ((double) srcindex) / finrate; const double innexttime = ((double) (srcindex + 1)) / finrate; const double interpolation1 = 1.0 - ((innexttime - outtime) / (innexttime - intime)); const int filterindex1 = (int) (interpolation1 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING); const double interpolation2 = 1.0 - interpolation1; const int filterindex2 = (int) (interpolation2 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING); for (chan = 0; chan < chans; chan++) { float outsample = 0.0f; /* do this twice to calculate the sample, once for the "left wing" and then same for the right. */ /* !!! FIXME: do both wings in one loop */ for (j = 0; (filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) { const int srcframe = srcindex - j; /* !!! FIXME: we can bubble this conditional out of here by doing a pre loop. */ const float insample = (srcframe < 0) ? lpadding[((paddinglen + srcframe) * chans) + chan] : inbuf[(srcframe * chans) + chan]; outsample += (float)(insample * (ResamplerFilter[filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)] + (interpolation1 * ResamplerFilterDifference[filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)]))); } for (j = 0; (filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) { const int srcframe = srcindex + 1 + j; /* !!! FIXME: we can bubble this conditional out of here by doing a post loop. */ const float insample = (srcframe >= inframes) ? rpadding[((srcframe - inframes) * chans) + chan] : inbuf[(srcframe * chans) + chan]; outsample += (float)(insample * (ResamplerFilter[filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)] + (interpolation2 * ResamplerFilterDifference[filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)]))); } *(dst++) = outsample; } outtime += outtimeincr; } return outframes * chans * sizeof (float); } int SDL_ConvertAudio(SDL_AudioCVT * cvt) { /* !!! FIXME: (cvt) should be const; stack-copy it here. */ /* !!! FIXME: (actually, we can't...len_cvt needs to be updated. Grr.) */ /* Make sure there's data to convert */ if (cvt->buf == NULL) { return SDL_SetError("No buffer allocated for conversion"); } /* Return okay if no conversion is necessary */ cvt->len_cvt = cvt->len; if (cvt->filters[0] == NULL) { return 0; } /* Set up the conversion and go! */ cvt->filter_index = 0; cvt->filters[0] (cvt, cvt->src_format); return 0; } static void SDLCALL SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format) { #if DEBUG_CONVERT printf("Converting byte order\n"); #endif switch (SDL_AUDIO_BITSIZE(format)) { #define CASESWAP(b) \ case b: { \ Uint##b *ptr = (Uint##b *) cvt->buf; \ int i; \ for (i = cvt->len_cvt / sizeof (*ptr); i; --i, ++ptr) { \ *ptr = SDL_Swap##b(*ptr); \ } \ break; \ } CASESWAP(16); CASESWAP(32); CASESWAP(64); #undef CASESWAP default: SDL_assert(!"unhandled byteswap datatype!"); break; } if (cvt->filters[++cvt->filter_index]) { /* flip endian flag for data. */ if (format & SDL_AUDIO_MASK_ENDIAN) { format &= ~SDL_AUDIO_MASK_ENDIAN; } else { format |= SDL_AUDIO_MASK_ENDIAN; } cvt->filters[cvt->filter_index](cvt, format); } } static int SDL_AddAudioCVTFilter(SDL_AudioCVT *cvt, const SDL_AudioFilter filter) { if (cvt->filter_index >= SDL_AUDIOCVT_MAX_FILTERS) { return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS); } if (filter == NULL) { return SDL_SetError("Audio filter pointer is NULL"); } cvt->filters[cvt->filter_index++] = filter; cvt->filters[cvt->filter_index] = NULL; /* Moving terminator */ return 0; } static int SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt) { int retval = 0; /* 0 == no conversion necessary. */ if ((SDL_AUDIO_ISBIGENDIAN(src_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) { if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) { return -1; } retval = 1; /* added a converter. */ } if (!SDL_AUDIO_ISFLOAT(src_fmt)) { const Uint16 src_bitsize = SDL_AUDIO_BITSIZE(src_fmt); const Uint16 dst_bitsize = 32; SDL_AudioFilter filter = NULL; switch (src_fmt & ~SDL_AUDIO_MASK_ENDIAN) { case AUDIO_S8: filter = SDL_Convert_S8_to_F32; break; case AUDIO_U8: filter = SDL_Convert_U8_to_F32; break; case AUDIO_S16: filter = SDL_Convert_S16_to_F32; break; case AUDIO_U16: filter = SDL_Convert_U16_to_F32; break; case AUDIO_S32: filter = SDL_Convert_S32_to_F32; break; default: SDL_assert(!"Unexpected audio format!"); break; } if (!filter) { return SDL_SetError("No conversion from source format to float available"); } if (SDL_AddAudioCVTFilter(cvt, filter) < 0) { return -1; } if (src_bitsize < dst_bitsize) { const int mult = (dst_bitsize / src_bitsize); cvt->len_mult *= mult; cvt->len_ratio *= mult; } else if (src_bitsize > dst_bitsize) { cvt->len_ratio /= (src_bitsize / dst_bitsize); } retval = 1; /* added a converter. */ } return retval; } static int SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt) { int retval = 0; /* 0 == no conversion necessary. */ if (!SDL_AUDIO_ISFLOAT(dst_fmt)) { const Uint16 dst_bitsize = SDL_AUDIO_BITSIZE(dst_fmt); const Uint16 src_bitsize = 32; SDL_AudioFilter filter = NULL; switch (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN) { case AUDIO_S8: filter = SDL_Convert_F32_to_S8; break; case AUDIO_U8: filter = SDL_Convert_F32_to_U8; break; case AUDIO_S16: filter = SDL_Convert_F32_to_S16; break; case AUDIO_U16: filter = SDL_Convert_F32_to_U16; break; case AUDIO_S32: filter = SDL_Convert_F32_to_S32; break; default: SDL_assert(!"Unexpected audio format!"); break; } if (!filter) { return SDL_SetError("No conversion from float to format 0x%.4x available", dst_fmt); } if (SDL_AddAudioCVTFilter(cvt, filter) < 0) { return -1; } if (src_bitsize < dst_bitsize) { const int mult = (dst_bitsize / src_bitsize); cvt->len_mult *= mult; cvt->len_ratio *= mult; } else if (src_bitsize > dst_bitsize) { cvt->len_ratio /= (src_bitsize / dst_bitsize); } retval = 1; /* added a converter. */ } if ((SDL_AUDIO_ISBIGENDIAN(dst_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) { if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) { return -1; } retval = 1; /* added a converter. */ } return retval; } static void SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format) { /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator). !!! FIXME in 2.1: We need to store data for this resampler, because the cvt structure doesn't store the original sample rates, !!! FIXME in 2.1: so we steal the ninth and tenth slot. :( */ const int inrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1]; const int outrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS]; const float *src = (const float *) cvt->buf; const int srclen = cvt->len_cvt; /*float *dst = (float *) cvt->buf; const int dstlen = (cvt->len * cvt->len_mult);*/ /* !!! FIXME: remove this if we can get the resampler to work in-place again. */ float *dst = (float *) (cvt->buf + srclen); const int dstlen = (cvt->len * cvt->len_mult) - srclen; const int requestedpadding = ResamplerPadding(inrate, outrate); int paddingsamples; float *padding; if (requestedpadding < SDL_MAX_SINT32 / chans) { paddingsamples = requestedpadding * chans; } else { paddingsamples = 0; } 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)); if (!padding) { SDL_OutOfMemory(); return; } cvt->len_cvt = SDL_ResampleAudio(chans, inrate, outrate, padding, padding, src, srclen, dst, dstlen); SDL_free(padding); SDL_memmove(cvt->buf, dst, cvt->len_cvt); /* !!! FIXME: remove this if we can get the resampler to work in-place again. */ if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index](cvt, format); } } /* !!! FIXME: We only have this macro salsa because SDL_AudioCVT doesn't !!! FIXME: store channel info, so we have to have function entry !!! FIXME: points for each supported channel count and multiple !!! FIXME: vs arbitrary. When we rev the ABI, clean this up. */ #define RESAMPLER_FUNCS(chans) \ static void SDLCALL \ SDL_ResampleCVT_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) { \ SDL_ResampleCVT(cvt, chans, format); \ } RESAMPLER_FUNCS(1) RESAMPLER_FUNCS(2) RESAMPLER_FUNCS(4) RESAMPLER_FUNCS(6) RESAMPLER_FUNCS(8) #undef RESAMPLER_FUNCS static SDL_AudioFilter ChooseCVTResampler(const int dst_channels) { switch (dst_channels) { case 1: return SDL_ResampleCVT_c1; case 2: return SDL_ResampleCVT_c2; case 4: return SDL_ResampleCVT_c4; case 6: return SDL_ResampleCVT_c6; case 8: return SDL_ResampleCVT_c8; default: break; } return NULL; } static int SDL_BuildAudioResampleCVT(SDL_AudioCVT * cvt, const int dst_channels, const int src_rate, const int dst_rate) { SDL_AudioFilter filter; if (src_rate == dst_rate) { return 0; /* no conversion necessary. */ } filter = ChooseCVTResampler(dst_channels); if (filter == NULL) { return SDL_SetError("No conversion available for these rates"); } if (SDL_PrepareResampleFilter() < 0) { return -1; } /* Update (cvt) with filter details... */ if (SDL_AddAudioCVTFilter(cvt, filter) < 0) { return -1; } /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator). !!! FIXME in 2.1: We need to store data for this resampler, because the cvt structure doesn't store the original sample rates, !!! FIXME in 2.1: so we steal the ninth and tenth slot. :( */ if (cvt->filter_index >= (SDL_AUDIOCVT_MAX_FILTERS-2)) { return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS-2); } cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1] = (SDL_AudioFilter) (size_t) src_rate; cvt->filters[SDL_AUDIOCVT_MAX_FILTERS] = (SDL_AudioFilter) (size_t) dst_rate; if (src_rate < dst_rate) { const double mult = ((double) dst_rate) / ((double) src_rate); cvt->len_mult *= (int) SDL_ceil(mult); cvt->len_ratio *= mult; } else { cvt->len_ratio /= ((double) src_rate) / ((double) dst_rate); } /* !!! FIXME: remove this if we can get the resampler to work in-place again. */ /* the buffer is big enough to hold the destination now, but we need it large enough to hold a separate scratch buffer. */ cvt->len_mult *= 2; return 1; /* added a converter. */ } static SDL_bool SDL_SupportedAudioFormat(const SDL_AudioFormat fmt) { switch (fmt) { case AUDIO_U8: case AUDIO_S8: case AUDIO_U16LSB: case AUDIO_S16LSB: case AUDIO_U16MSB: case AUDIO_S16MSB: case AUDIO_S32LSB: case AUDIO_S32MSB: case AUDIO_F32LSB: case AUDIO_F32MSB: return SDL_TRUE; /* supported. */ default: break; } return SDL_FALSE; /* unsupported. */ } static SDL_bool SDL_SupportedChannelCount(const int channels) { switch (channels) { case 1: /* mono */ case 2: /* stereo */ case 4: /* quad */ case 6: /* 5.1 */ case 8: /* 7.1 */ return SDL_TRUE; /* supported. */ default: break; } return SDL_FALSE; /* unsupported. */ } /* Creates a set of audio filters to convert from one format to another. Returns 0 if no conversion is needed, 1 if the audio filter is set up, or -1 if an error like invalid parameter, unsupported format, etc. occurred. */ int SDL_BuildAudioCVT(SDL_AudioCVT * cvt, SDL_AudioFormat src_fmt, Uint8 src_channels, int src_rate, SDL_AudioFormat dst_fmt, Uint8 dst_channels, int dst_rate) { /* Sanity check target pointer */ if (cvt == NULL) { return SDL_InvalidParamError("cvt"); } /* Make sure we zero out the audio conversion before error checking */ SDL_zerop(cvt); if (!SDL_SupportedAudioFormat(src_fmt)) { return SDL_SetError("Invalid source format"); } else if (!SDL_SupportedAudioFormat(dst_fmt)) { return SDL_SetError("Invalid destination format"); } else if (!SDL_SupportedChannelCount(src_channels)) { return SDL_SetError("Invalid source channels"); } else if (!SDL_SupportedChannelCount(dst_channels)) { return SDL_SetError("Invalid destination channels"); } else if (src_rate <= 0) { return SDL_SetError("Source rate is equal to or less than zero"); } else if (dst_rate <= 0) { return SDL_SetError("Destination rate is equal to or less than zero"); } else if (src_rate >= SDL_MAX_SINT32 / RESAMPLER_SAMPLES_PER_ZERO_CROSSING) { return SDL_SetError("Source rate is too high"); } else if (dst_rate >= SDL_MAX_SINT32 / RESAMPLER_SAMPLES_PER_ZERO_CROSSING) { return SDL_SetError("Destination rate is too high"); } #if DEBUG_CONVERT printf("Build format %04x->%04x, channels %u->%u, rate %d->%d\n", src_fmt, dst_fmt, src_channels, dst_channels, src_rate, dst_rate); #endif /* Start off with no conversion necessary */ cvt->src_format = src_fmt; cvt->dst_format = dst_fmt; cvt->needed = 0; cvt->filter_index = 0; SDL_zeroa(cvt->filters); cvt->len_mult = 1; cvt->len_ratio = 1.0; cvt->rate_incr = ((double) dst_rate) / ((double) src_rate); /* Make sure we've chosen audio conversion functions (MMX, scalar, etc.) */ SDL_ChooseAudioConverters(); /* Type conversion goes like this now: - byteswap to CPU native format first if necessary. - convert to native Float32 if necessary. - resample and change channel count if necessary. - convert back to native format. - byteswap back to foreign format if necessary. The expectation is we can process data faster in float32 (possibly with SIMD), and making several passes over the same buffer is likely to be CPU cache-friendly, avoiding the biggest performance hit in modern times. Previously we had (script-generated) custom converters for every data type and it was a bloat on SDL compile times and final library size. */ /* see if we can skip float conversion entirely. */ if (src_rate == dst_rate && src_channels == dst_channels) { if (src_fmt == dst_fmt) { return 0; } /* just a byteswap needed? */ if ((src_fmt & ~SDL_AUDIO_MASK_ENDIAN) == (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN)) { if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) { return -1; } cvt->needed = 1; return 1; } } /* Convert data types, if necessary. Updates (cvt). */ if (SDL_BuildAudioTypeCVTToFloat(cvt, src_fmt) < 0) { return -1; /* shouldn't happen, but just in case... */ } /* Channel conversion */ if (src_channels < dst_channels) { /* Upmixing */ /* Mono -> Stereo [-> ...] */ if ((src_channels == 1) && (dst_channels > 1)) { if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertMonoToStereo) < 0) { return -1; } cvt->len_mult *= 2; src_channels = 2; cvt->len_ratio *= 2; } /* [Mono ->] Stereo -> 5.1 [-> 7.1] */ if ((src_channels == 2) && (dst_channels >= 6)) { if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertStereoTo51) < 0) { return -1; } src_channels = 6; cvt->len_mult *= 3; cvt->len_ratio *= 3; } /* Quad -> 5.1 [-> 7.1] */ if ((src_channels == 4) && (dst_channels >= 6)) { if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertQuadTo51) < 0) { return -1; } src_channels = 6; cvt->len_mult = (cvt->len_mult * 3 + 1) / 2; cvt->len_ratio *= 1.5; } /* [[Mono ->] Stereo ->] 5.1 -> 7.1 */ if ((src_channels == 6) && (dst_channels == 8)) { if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51To71) < 0) { return -1; } src_channels = 8; cvt->len_mult = (cvt->len_mult * 4 + 2) / 3; /* Should be numerically exact with every valid input to this function */ cvt->len_ratio = cvt->len_ratio * 4 / 3; } /* [Mono ->] Stereo -> Quad */ if ((src_channels == 2) && (dst_channels == 4)) { if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertStereoToQuad) < 0) { return -1; } src_channels = 4; cvt->len_mult *= 2; cvt->len_ratio *= 2; } } else if (src_channels > dst_channels) { /* Downmixing */ /* 7.1 -> 5.1 [-> Stereo [-> Mono]] */ /* 7.1 -> 5.1 [-> Quad] */ if ((src_channels == 8) && (dst_channels <= 6)) { if (SDL_AddAudioCVTFilter(cvt, SDL_Convert71To51) < 0) { return -1; } src_channels = 6; cvt->len_ratio *= 0.75; } /* [7.1 ->] 5.1 -> Stereo [-> Mono] */ if ((src_channels == 6) && (dst_channels <= 2)) { if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51ToStereo) < 0) { return -1; } src_channels = 2; cvt->len_ratio /= 3; } /* 5.1 -> Quad */ if ((src_channels == 6) && (dst_channels == 4)) { if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51ToQuad) < 0) { return -1; } src_channels = 4; cvt->len_ratio = cvt->len_ratio * 2 / 3; } /* Quad -> Stereo [-> Mono] */ if ((src_channels == 4) && (dst_channels <= 2)) { if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertQuadToStereo) < 0) { return -1; } src_channels = 2; cvt->len_ratio /= 2; } /* [... ->] Stereo -> Mono */ if ((src_channels == 2) && (dst_channels == 1)) { SDL_AudioFilter filter = NULL; #if HAVE_SSE3_INTRINSICS if (SDL_HasSSE3()) { filter = SDL_ConvertStereoToMono_SSE3; } #endif if (!filter) { filter = SDL_ConvertStereoToMono; } if (SDL_AddAudioCVTFilter(cvt, filter) < 0) { return -1; } src_channels = 1; cvt->len_ratio /= 2; } } if (src_channels != dst_channels) { /* All combinations of supported channel counts should have been handled by now, but let's be defensive */ return SDL_SetError("Invalid channel combination"); } /* Do rate conversion, if necessary. Updates (cvt). */ if (SDL_BuildAudioResampleCVT(cvt, dst_channels, src_rate, dst_rate) < 0) { return -1; /* shouldn't happen, but just in case... */ } /* Move to final data type. */ if (SDL_BuildAudioTypeCVTFromFloat(cvt, dst_fmt) < 0) { return -1; /* shouldn't happen, but just in case... */ } cvt->needed = (cvt->filter_index != 0); return (cvt->needed); } typedef int (*SDL_ResampleAudioStreamFunc)(SDL_AudioStream *stream, const void *inbuf, const int inbuflen, void *outbuf, const int outbuflen); typedef void (*SDL_ResetAudioStreamResamplerFunc)(SDL_AudioStream *stream); typedef void (*SDL_CleanupAudioStreamResamplerFunc)(SDL_AudioStream *stream); struct _SDL_AudioStream { SDL_AudioCVT cvt_before_resampling; SDL_AudioCVT cvt_after_resampling; SDL_DataQueue *queue; SDL_bool first_run; Uint8 *staging_buffer; int staging_buffer_size; int staging_buffer_filled; Uint8 *work_buffer_base; /* maybe unaligned pointer from SDL_realloc(). */ int work_buffer_len; int src_sample_frame_size; SDL_AudioFormat src_format; Uint8 src_channels; int src_rate; int dst_sample_frame_size; SDL_AudioFormat dst_format; Uint8 dst_channels; int dst_rate; double rate_incr; Uint8 pre_resample_channels; int packetlen; int resampler_padding_samples; float *resampler_padding; void *resampler_state; SDL_ResampleAudioStreamFunc resampler_func; SDL_ResetAudioStreamResamplerFunc reset_resampler_func; SDL_CleanupAudioStreamResamplerFunc cleanup_resampler_func; }; static Uint8 * EnsureStreamBufferSize(SDL_AudioStream *stream, const int newlen) { Uint8 *ptr; size_t offset; if (stream->work_buffer_len >= newlen) { ptr = stream->work_buffer_base; } else { ptr = (Uint8 *) SDL_realloc(stream->work_buffer_base, newlen + 32); if (!ptr) { SDL_OutOfMemory(); return NULL; } /* Make sure we're aligned to 16 bytes for SIMD code. */ stream->work_buffer_base = ptr; stream->work_buffer_len = newlen; } offset = ((size_t) ptr) & 15; return offset ? ptr + (16 - offset) : ptr; } #ifdef HAVE_LIBSAMPLERATE_H static int SDL_ResampleAudioStream_SRC(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen) { const float *inbuf = (const float *) _inbuf; float *outbuf = (float *) _outbuf; const int framelen = sizeof(float) * stream->pre_resample_channels; SRC_STATE *state = (SRC_STATE *)stream->resampler_state; SRC_DATA data; int result; SDL_assert(inbuf != ((const float *) outbuf)); /* SDL_AudioStreamPut() shouldn't allow in-place resamples. */ data.data_in = (float *)inbuf; /* Older versions of libsamplerate had a non-const pointer, but didn't write to it */ data.input_frames = inbuflen / framelen; data.input_frames_used = 0; data.data_out = outbuf; data.output_frames = outbuflen / framelen; data.end_of_input = 0; data.src_ratio = stream->rate_incr; result = SRC_src_process(state, &data); if (result != 0) { SDL_SetError("src_process() failed: %s", SRC_src_strerror(result)); return 0; } /* If this fails, we need to store them off somewhere */ SDL_assert(data.input_frames_used == data.input_frames); return data.output_frames_gen * (sizeof(float) * stream->pre_resample_channels); } static void SDL_ResetAudioStreamResampler_SRC(SDL_AudioStream *stream) { SRC_src_reset((SRC_STATE *)stream->resampler_state); } static void SDL_CleanupAudioStreamResampler_SRC(SDL_AudioStream *stream) { SRC_STATE *state = (SRC_STATE *)stream->resampler_state; if (state) { SRC_src_delete(state); } stream->resampler_state = NULL; stream->resampler_func = NULL; stream->reset_resampler_func = NULL; stream->cleanup_resampler_func = NULL; } static SDL_bool SetupLibSampleRateResampling(SDL_AudioStream *stream) { int result = 0; SRC_STATE *state = NULL; if (SRC_available) { state = SRC_src_new(SRC_converter, stream->pre_resample_channels, &result); if (!state) { SDL_SetError("src_new() failed: %s", SRC_src_strerror(result)); } } if (!state) { SDL_CleanupAudioStreamResampler_SRC(stream); return SDL_FALSE; } stream->resampler_state = state; stream->resampler_func = SDL_ResampleAudioStream_SRC; stream->reset_resampler_func = SDL_ResetAudioStreamResampler_SRC; stream->cleanup_resampler_func = SDL_CleanupAudioStreamResampler_SRC; return SDL_TRUE; } #endif /* HAVE_LIBSAMPLERATE_H */ static int SDL_ResampleAudioStream(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen) { const Uint8 *inbufend = ((const Uint8 *) _inbuf) + inbuflen; const float *inbuf = (const float *) _inbuf; float *outbuf = (float *) _outbuf; const int chans = (int) stream->pre_resample_channels; const int inrate = stream->src_rate; const int outrate = stream->dst_rate; const int paddingsamples = stream->resampler_padding_samples; const int paddingbytes = paddingsamples * sizeof (float); float *lpadding = (float *) stream->resampler_state; const float *rpadding = (const float *) inbufend; /* we set this up so there are valid padding samples at the end of the input buffer. */ const int cpy = SDL_min(inbuflen, paddingbytes); int retval; SDL_assert(inbuf != ((const float *) outbuf)); /* SDL_AudioStreamPut() shouldn't allow in-place resamples. */ retval = SDL_ResampleAudio(chans, inrate, outrate, lpadding, rpadding, inbuf, inbuflen, outbuf, outbuflen); /* update our left padding with end of current input, for next run. */ SDL_memcpy((lpadding + paddingsamples) - (cpy / sizeof (float)), inbufend - cpy, cpy); return retval; } static void SDL_ResetAudioStreamResampler(SDL_AudioStream *stream) { /* set all the padding to silence. */ const int len = stream->resampler_padding_samples; SDL_memset(stream->resampler_state, '\0', len * sizeof (float)); } static void SDL_CleanupAudioStreamResampler(SDL_AudioStream *stream) { SDL_free(stream->resampler_state); } SDL_AudioStream * SDL_NewAudioStream(const SDL_AudioFormat src_format, const Uint8 src_channels, const int src_rate, const SDL_AudioFormat dst_format, const Uint8 dst_channels, const int dst_rate) { const int packetlen = 4096; /* !!! FIXME: good enough for now. */ Uint8 pre_resample_channels; SDL_AudioStream *retval; retval = (SDL_AudioStream *) SDL_calloc(1, sizeof (SDL_AudioStream)); if (!retval) { return NULL; } /* If increasing channels, do it after resampling, since we'd just do more work to resample duplicate channels. If we're decreasing, do it first so we resample the interpolated data instead of interpolating the resampled data (!!! FIXME: decide if that works in practice, though!). */ pre_resample_channels = SDL_min(src_channels, dst_channels); retval->first_run = SDL_TRUE; retval->src_sample_frame_size = (SDL_AUDIO_BITSIZE(src_format) / 8) * src_channels; retval->src_format = src_format; retval->src_channels = src_channels; retval->src_rate = src_rate; retval->dst_sample_frame_size = (SDL_AUDIO_BITSIZE(dst_format) / 8) * dst_channels; retval->dst_format = dst_format; retval->dst_channels = dst_channels; retval->dst_rate = dst_rate; retval->pre_resample_channels = pre_resample_channels; 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)); if (retval->resampler_padding == NULL) { SDL_FreeAudioStream(retval); SDL_OutOfMemory(); return NULL; } retval->staging_buffer_size = ((retval->resampler_padding_samples / retval->pre_resample_channels) * retval->src_sample_frame_size); if (retval->staging_buffer_size > 0) { retval->staging_buffer = (Uint8 *) SDL_malloc(retval->staging_buffer_size); if (retval->staging_buffer == NULL) { SDL_FreeAudioStream(retval); SDL_OutOfMemory(); return NULL; } } /* Not resampling? It's an easy conversion (and maybe not even that!) */ if (src_rate == dst_rate) { retval->cvt_before_resampling.needed = SDL_FALSE; if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, src_format, src_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) { SDL_FreeAudioStream(retval); return NULL; /* SDL_BuildAudioCVT should have called SDL_SetError. */ } } else { /* Don't resample at first. Just get us to Float32 format. */ /* !!! FIXME: convert to int32 on devices without hardware float. */ if (SDL_BuildAudioCVT(&retval->cvt_before_resampling, src_format, src_channels, src_rate, AUDIO_F32SYS, pre_resample_channels, src_rate) < 0) { SDL_FreeAudioStream(retval); return NULL; /* SDL_BuildAudioCVT should have called SDL_SetError. */ } #ifdef HAVE_LIBSAMPLERATE_H SetupLibSampleRateResampling(retval); #endif if (!retval->resampler_func) { retval->resampler_state = SDL_calloc(retval->resampler_padding_samples, sizeof (float)); if (!retval->resampler_state) { SDL_FreeAudioStream(retval); SDL_OutOfMemory(); return NULL; } if (SDL_PrepareResampleFilter() < 0) { SDL_free(retval->resampler_state); retval->resampler_state = NULL; SDL_FreeAudioStream(retval); return NULL; } retval->resampler_func = SDL_ResampleAudioStream; retval->reset_resampler_func = SDL_ResetAudioStreamResampler; retval->cleanup_resampler_func = SDL_CleanupAudioStreamResampler; } /* Convert us to the final format after resampling. */ if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, AUDIO_F32SYS, pre_resample_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) { SDL_FreeAudioStream(retval); return NULL; /* SDL_BuildAudioCVT should have called SDL_SetError. */ } } retval->queue = SDL_NewDataQueue(packetlen, packetlen * 2); if (!retval->queue) { SDL_FreeAudioStream(retval); return NULL; /* SDL_NewDataQueue should have called SDL_SetError. */ } return retval; } static int SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, int *maxputbytes) { int buflen = len; int workbuflen; Uint8 *workbuf; Uint8 *resamplebuf = NULL; int resamplebuflen = 0; int neededpaddingbytes; int paddingbytes; /* !!! FIXME: several converters can take advantage of SIMD, but only !!! FIXME: if the data is aligned to 16 bytes. EnsureStreamBufferSize() !!! FIXME: guarantees the buffer will align, but the !!! FIXME: converters will iterate over the data backwards if !!! FIXME: the output grows, and this means we won't align if buflen !!! FIXME: isn't a multiple of 16. In these cases, we should chop off !!! FIXME: a few samples at the end and convert them separately. */ /* no padding prepended on first run. */ neededpaddingbytes = stream->resampler_padding_samples * sizeof (float); paddingbytes = stream->first_run ? 0 : neededpaddingbytes; stream->first_run = SDL_FALSE; /* Make sure the work buffer can hold all the data we need at once... */ workbuflen = buflen; if (stream->cvt_before_resampling.needed) { workbuflen *= stream->cvt_before_resampling.len_mult; } if (stream->dst_rate != stream->src_rate) { /* resamples can't happen in place, so make space for second buf. */ const int framesize = stream->pre_resample_channels * sizeof (float); const int frames = workbuflen / framesize; resamplebuflen = ((int) SDL_ceil(frames * stream->rate_incr)) * framesize; #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: will resample %d bytes to %d (ratio=%.6f)\n", workbuflen, resamplebuflen, stream->rate_incr); #endif workbuflen += resamplebuflen; } if (stream->cvt_after_resampling.needed) { /* !!! FIXME: buffer might be big enough already? */ workbuflen *= stream->cvt_after_resampling.len_mult; } workbuflen += neededpaddingbytes; #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: Putting %d bytes of preconverted audio, need %d byte work buffer\n", buflen, workbuflen); #endif workbuf = EnsureStreamBufferSize(stream, workbuflen); if (!workbuf) { return -1; /* probably out of memory. */ } resamplebuf = workbuf; /* default if not resampling. */ SDL_memcpy(workbuf + paddingbytes, buf, buflen); if (stream->cvt_before_resampling.needed) { stream->cvt_before_resampling.buf = workbuf + paddingbytes; stream->cvt_before_resampling.len = buflen; if (SDL_ConvertAudio(&stream->cvt_before_resampling) == -1) { return -1; /* uhoh! */ } buflen = stream->cvt_before_resampling.len_cvt; #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: After initial conversion we have %d bytes\n", buflen); #endif } if (stream->dst_rate != stream->src_rate) { /* save off some samples at the end; they are used for padding now so the resampler is coherent and then used at the start of the next put operation. Prepend last put operation's padding, too. */ /* prepend prior put's padding. :P */ if (paddingbytes) { SDL_memcpy(workbuf, stream->resampler_padding, paddingbytes); buflen += paddingbytes; } /* save off the data at the end for the next run. */ SDL_memcpy(stream->resampler_padding, workbuf + (buflen - neededpaddingbytes), neededpaddingbytes); resamplebuf = workbuf + buflen; /* skip to second piece of workbuf. */ SDL_assert(buflen >= neededpaddingbytes); if (buflen > neededpaddingbytes) { buflen = stream->resampler_func(stream, workbuf, buflen - neededpaddingbytes, resamplebuf, resamplebuflen); } else { buflen = 0; } #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: After resampling we have %d bytes\n", buflen); #endif } if (stream->cvt_after_resampling.needed && (buflen > 0)) { stream->cvt_after_resampling.buf = resamplebuf; stream->cvt_after_resampling.len = buflen; if (SDL_ConvertAudio(&stream->cvt_after_resampling) == -1) { return -1; /* uhoh! */ } buflen = stream->cvt_after_resampling.len_cvt; #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: After final conversion we have %d bytes\n", buflen); #endif } #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: Final output is %d bytes\n", buflen); #endif if (maxputbytes) { const int maxbytes = *maxputbytes; if (buflen > maxbytes) buflen = maxbytes; *maxputbytes -= buflen; } /* resamplebuf holds the final output, even if we didn't resample. */ return buflen ? SDL_WriteToDataQueue(stream->queue, resamplebuf, buflen) : 0; } int SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len) { /* !!! FIXME: several converters can take advantage of SIMD, but only !!! FIXME: if the data is aligned to 16 bytes. EnsureStreamBufferSize() !!! FIXME: guarantees the buffer will align, but the !!! FIXME: converters will iterate over the data backwards if !!! FIXME: the output grows, and this means we won't align if buflen !!! FIXME: isn't a multiple of 16. In these cases, we should chop off !!! FIXME: a few samples at the end and convert them separately. */ #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: wants to put %d preconverted bytes\n", buflen); #endif if (!stream) { return SDL_InvalidParamError("stream"); } else if (!buf) { return SDL_InvalidParamError("buf"); } else if (len == 0) { return 0; /* nothing to do. */ } else if ((len % stream->src_sample_frame_size) != 0) { return SDL_SetError("Can't add partial sample frames"); } if (!stream->cvt_before_resampling.needed && (stream->dst_rate == stream->src_rate) && !stream->cvt_after_resampling.needed) { #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: no conversion needed at all, queueing %d bytes.\n", len); #endif return SDL_WriteToDataQueue(stream->queue, buf, len); } while (len > 0) { int amount; /* If we don't have a staging buffer or we're given enough data that we don't need to store it for later, skip the staging process. */ if (!stream->staging_buffer_filled && len >= stream->staging_buffer_size) { return SDL_AudioStreamPutInternal(stream, buf, len, NULL); } /* If there's not enough data to fill the staging buffer, just save it */ if ((stream->staging_buffer_filled + len) < stream->staging_buffer_size) { SDL_memcpy(stream->staging_buffer + stream->staging_buffer_filled, buf, len); stream->staging_buffer_filled += len; return 0; } /* Fill the staging buffer, process it, and continue */ amount = (stream->staging_buffer_size - stream->staging_buffer_filled); SDL_assert(amount > 0); SDL_memcpy(stream->staging_buffer + stream->staging_buffer_filled, buf, amount); stream->staging_buffer_filled = 0; if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, NULL) < 0) { return -1; } buf = (void *)((Uint8 *)buf + amount); len -= amount; } return 0; } int SDL_AudioStreamFlush(SDL_AudioStream *stream) { if (!stream) { return SDL_InvalidParamError("stream"); } #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: flushing! staging_buffer_filled=%d bytes\n", stream->staging_buffer_filled); #endif /* shouldn't use a staging buffer if we're not resampling. */ SDL_assert((stream->dst_rate != stream->src_rate) || (stream->staging_buffer_filled == 0)); if (stream->staging_buffer_filled > 0) { /* push the staging buffer + silence. We need to flush out not just the staging buffer, but the piece that the stream was saving off for right-side resampler padding. */ const SDL_bool first_run = stream->first_run; const int filled = stream->staging_buffer_filled; int actual_input_frames = filled / stream->src_sample_frame_size; if (!first_run) actual_input_frames += stream->resampler_padding_samples / stream->pre_resample_channels; if (actual_input_frames > 0) { /* don't bother if nothing to flush. */ /* This is how many bytes we're expecting without silence appended. */ int flush_remaining = ((int) SDL_ceil(actual_input_frames * stream->rate_incr)) * stream->dst_sample_frame_size; #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: flushing with padding to get max %d bytes!\n", flush_remaining); #endif SDL_memset(stream->staging_buffer + filled, '\0', stream->staging_buffer_size - filled); if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, &flush_remaining) < 0) { return -1; } /* we have flushed out (or initially filled) the pending right-side resampler padding, but we need to push more silence to guarantee the staging buffer is fully flushed out, too. */ SDL_memset(stream->staging_buffer, '\0', filled); if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, &flush_remaining) < 0) { return -1; } } } stream->staging_buffer_filled = 0; stream->first_run = SDL_TRUE; return 0; } /* get converted/resampled data from the stream */ int SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, int len) { #if DEBUG_AUDIOSTREAM printf("AUDIOSTREAM: want to get %d converted bytes\n", len); #endif if (!stream) { return SDL_InvalidParamError("stream"); } else if (!buf) { return SDL_InvalidParamError("buf"); } else if (len <= 0) { return 0; /* nothing to do. */ } else if ((len % stream->dst_sample_frame_size) != 0) { return SDL_SetError("Can't request partial sample frames"); } return (int) SDL_ReadFromDataQueue(stream->queue, buf, len); } /* number of converted/resampled bytes available */ int SDL_AudioStreamAvailable(SDL_AudioStream *stream) { return stream ? (int) SDL_CountDataQueue(stream->queue) : 0; } void SDL_AudioStreamClear(SDL_AudioStream *stream) { if (!stream) { SDL_InvalidParamError("stream"); } else { SDL_ClearDataQueue(stream->queue, stream->packetlen * 2); if (stream->reset_resampler_func) { stream->reset_resampler_func(stream); } stream->first_run = SDL_TRUE; stream->staging_buffer_filled = 0; } } /* dispose of a stream */ void SDL_FreeAudioStream(SDL_AudioStream *stream) { if (stream) { if (stream->cleanup_resampler_func) { stream->cleanup_resampler_func(stream); } SDL_FreeDataQueue(stream->queue); SDL_free(stream->staging_buffer); SDL_free(stream->work_buffer_base); SDL_free(stream->resampler_padding); SDL_free(stream); } } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/SDL_audiocvt.c
C
apache-2.0
58,748
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" /* Get the name of the audio device we use for output */ #if SDL_AUDIO_DRIVER_NETBSD || SDL_AUDIO_DRIVER_OSS || SDL_AUDIO_DRIVER_SUNAUDIO #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> /* For close() */ #include "SDL_stdinc.h" #include "SDL_audiodev_c.h" #ifndef _PATH_DEV_DSP #if defined(__NETBSD__) || defined(__OPENBSD__) #define _PATH_DEV_DSP "/dev/audio" #else #define _PATH_DEV_DSP "/dev/dsp" #endif #endif #ifndef _PATH_DEV_DSP24 #define _PATH_DEV_DSP24 "/dev/sound/dsp" #endif #ifndef _PATH_DEV_AUDIO #define _PATH_DEV_AUDIO "/dev/audio" #endif static void test_device(const int iscapture, const char *fname, int flags, int (*test) (int fd)) { struct stat sb; if ((stat(fname, &sb) == 0) && (S_ISCHR(sb.st_mode))) { const int audio_fd = open(fname, flags, 0); if (audio_fd >= 0) { const int okay = test(audio_fd); close(audio_fd); if (okay) { static size_t dummyhandle = 0; dummyhandle++; SDL_assert(dummyhandle != 0); SDL_AddAudioDevice(iscapture, fname, (void *) dummyhandle); } } } } static int test_stub(int fd) { return 1; } static void SDL_EnumUnixAudioDevices_Internal(const int iscapture, const int classic, int (*test)(int)) { const int flags = iscapture ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT; const char *audiodev; char audiopath[1024]; if (test == NULL) test = test_stub; /* Figure out what our audio device is */ if (((audiodev = SDL_getenv("SDL_PATH_DSP")) == NULL) && ((audiodev = SDL_getenv("AUDIODEV")) == NULL)) { if (classic) { audiodev = _PATH_DEV_AUDIO; } else { struct stat sb; /* Added support for /dev/sound/\* in Linux 2.4 */ if (((stat("/dev/sound", &sb) == 0) && S_ISDIR(sb.st_mode)) && ((stat(_PATH_DEV_DSP24, &sb) == 0) && S_ISCHR(sb.st_mode))) { audiodev = _PATH_DEV_DSP24; } else { audiodev = _PATH_DEV_DSP; } } } test_device(iscapture, audiodev, flags, test); if (SDL_strlen(audiodev) < (sizeof(audiopath) - 3)) { int instance = 0; while (instance <= 64) { SDL_snprintf(audiopath, SDL_arraysize(audiopath), "%s%d", audiodev, instance); instance++; test_device(iscapture, audiopath, flags, test); } } } void SDL_EnumUnixAudioDevices(const int classic, int (*test)(int)) { SDL_EnumUnixAudioDevices_Internal(SDL_TRUE, classic, test); SDL_EnumUnixAudioDevices_Internal(SDL_FALSE, classic, test); } #endif /* Audio driver selection */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/SDL_audiodev.c
C
apache-2.0
3,792
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ #ifndef SDL_audiodev_c_h_ #define SDL_audiodev_c_h_ #include "SDL.h" #include "../SDL_internal.h" #include "SDL_sysaudio.h" /* Open the audio device for playback, and don't block if busy */ /* #define USE_BLOCKING_WRITES */ #ifdef USE_BLOCKING_WRITES #define OPEN_FLAGS_OUTPUT O_WRONLY #define OPEN_FLAGS_INPUT O_RDONLY #else #define OPEN_FLAGS_OUTPUT (O_WRONLY|O_NONBLOCK) #define OPEN_FLAGS_INPUT (O_RDONLY|O_NONBLOCK) #endif extern void SDL_EnumUnixAudioDevices(const int classic, int (*test)(int)); #endif /* SDL_audiodev_c_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/SDL_audiodev_c.h
C
apache-2.0
1,515
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #include "SDL_audio.h" #include "SDL_audio_c.h" #include "SDL_cpuinfo.h" #include "SDL_assert.h" #ifdef __ARM_NEON #define HAVE_NEON_INTRINSICS 1 #endif #ifdef __SSE2__ #define HAVE_SSE2_INTRINSICS 1 #endif #if defined(__x86_64__) && HAVE_SSE2_INTRINSICS #define NEED_SCALAR_CONVERTER_FALLBACKS 0 /* x86_64 guarantees SSE2. */ #elif __MACOSX__ && HAVE_SSE2_INTRINSICS #define NEED_SCALAR_CONVERTER_FALLBACKS 0 /* Mac OS X/Intel guarantees SSE2. */ #elif defined(__ARM_ARCH) && (__ARM_ARCH >= 8) && HAVE_NEON_INTRINSICS #define NEED_SCALAR_CONVERTER_FALLBACKS 0 /* ARMv8+ promise NEON. */ #elif defined(__APPLE__) && defined(__ARM_ARCH) && (__ARM_ARCH >= 7) && HAVE_NEON_INTRINSICS #define NEED_SCALAR_CONVERTER_FALLBACKS 0 /* All Apple ARMv7 chips promise NEON support. */ #endif /* Set to zero if platform is guaranteed to use a SIMD codepath here. */ #ifndef NEED_SCALAR_CONVERTER_FALLBACKS #define NEED_SCALAR_CONVERTER_FALLBACKS 1 #endif /* Function pointers set to a CPU-specific implementation. */ SDL_AudioFilter SDL_Convert_S8_to_F32 = NULL; SDL_AudioFilter SDL_Convert_U8_to_F32 = NULL; SDL_AudioFilter SDL_Convert_S16_to_F32 = NULL; SDL_AudioFilter SDL_Convert_U16_to_F32 = NULL; SDL_AudioFilter SDL_Convert_S32_to_F32 = NULL; SDL_AudioFilter SDL_Convert_F32_to_S8 = NULL; SDL_AudioFilter SDL_Convert_F32_to_U8 = NULL; SDL_AudioFilter SDL_Convert_F32_to_S16 = NULL; SDL_AudioFilter SDL_Convert_F32_to_U16 = NULL; SDL_AudioFilter SDL_Convert_F32_to_S32 = NULL; #define DIVBY128 0.0078125f #define DIVBY32768 0.000030517578125f #define DIVBY8388607 0.00000011920930376163766f #if NEED_SCALAR_CONVERTER_FALLBACKS static void SDLCALL SDL_Convert_S8_to_F32_Scalar(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"); for (i = cvt->len_cvt; i; --i, --src, --dst) { *dst = ((float) *src) * DIVBY128; } 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_Scalar(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"); for (i = cvt->len_cvt; i; --i, --src, --dst) { *dst = (((float) *src) * DIVBY128) - 1.0f; } 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_Scalar(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"); for (i = cvt->len_cvt / sizeof (Sint16); i; --i, --src, --dst) { *dst = ((float) *src) * DIVBY32768; } 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_Scalar(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"); for (i = cvt->len_cvt / sizeof (Uint16); i; --i, --src, --dst) { *dst = (((float) *src) * DIVBY32768) - 1.0f; } 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_Scalar(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"); for (i = cvt->len_cvt / sizeof (Sint32); i; --i, ++src, ++dst) { *dst = ((float) (*src>>8)) * DIVBY8388607; } if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index](cvt, AUDIO_F32SYS); } } static void SDLCALL SDL_Convert_F32_to_S8_Scalar(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"); for (i = cvt->len_cvt / sizeof (float); i; --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); } } 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_Scalar(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"); for (i = cvt->len_cvt / sizeof (float); i; --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); } } 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_Scalar(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"); for (i = cvt->len_cvt / sizeof (float); i; --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); } } 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_Scalar(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"); 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) { *dst = 0; } else { *dst = (Uint16)((sample + 1.0f) * 32767.0f); } } 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_Scalar(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"); for (i = cvt->len_cvt / sizeof (float); i; --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; } } if (cvt->filters[++cvt->filter_index]) { cvt->filters[cvt->filter_index](cvt, AUDIO_S32SYS); } } #endif #if HAVE_SSE2_INTRINSICS static void SDLCALL SDL_Convert_S8_to_F32_SSE2(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 SSE2)"); /* 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 SSE 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 SSE blocks as long as we have 16 bytes available. */ const __m128i *mmsrc = (const __m128i *) src; const __m128i zero = _mm_setzero_si128(); const __m128 divby128 = _mm_set1_ps(DIVBY128); while (i >= 16) { /* 16 * 8-bit */ const __m128i bytes = _mm_load_si128(mmsrc); /* get 16 sint8 into an XMM register. */ /* treat as int16, shift left to clear every other sint16, then back right with sign-extend. Now sint16. */ const __m128i shorts1 = _mm_srai_epi16(_mm_slli_epi16(bytes, 8), 8); /* right-shift-sign-extend gets us sint16 with the other set of values. */ const __m128i shorts2 = _mm_srai_epi16(bytes, 8); /* unpack against zero to make these int32, shift to make them sign-extend, convert to float, multiply. Whew! */ const __m128 floats1 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpacklo_epi16(shorts1, zero), 16), 16)), divby128); const __m128 floats2 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpacklo_epi16(shorts2, zero), 16), 16)), divby128); const __m128 floats3 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpackhi_epi16(shorts1, zero), 16), 16)), divby128); const __m128 floats4 = _mm_mul_ps(_mm_cvtepi32_ps(_mm_srai_epi32(_mm_slli_epi32(_mm_unpackhi_epi16(shorts2, zero), 16), 16)), divby128); /* Interleave back into correct order, store. */ _mm_store_ps(dst, _mm_unpacklo_ps(floats1, floats2)); _mm_store_ps(dst+4, _mm_unpackhi_ps(floats1, floats2)); _mm_store_ps(dst+8, _mm_unpacklo_ps(floats3, floats4)); _mm_store_ps(dst+12, _mm_unpackhi_ps(floats3, floats4)); i -= 16; mmsrc--; 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_SSE2(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 SSE2)"); /* 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 SSE 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 SSE blocks as long as we have 16 bytes available. */ const __m128i *mmsrc = (const __m128i *) src; const __m128i zero = _mm_setzero_si128(); const __m128 divby128 = _mm_set1_ps(DIVBY128); const __m128 minus1 = _mm_set1_ps(-1.0f); while (i >= 16) { /* 16 * 8-bit */ const __m128i bytes = _mm_load_si128(mmsrc); /* get 16 uint8 into an XMM register. */ /* treat as int16, shift left to clear every other sint16, then back right with zero-extend. Now uint16. */ const __m128i shorts1 = _mm_srli_epi16(_mm_slli_epi16(bytes, 8), 8); /* right-shift-zero-extend gets us uint16 with the other set of values. */ const __m128i shorts2 = _mm_srli_epi16(bytes, 8); /* unpack against zero to make these int32, convert to float, multiply, add. Whew! */ /* Note that AVX2 can do floating point multiply+add in one instruction, fwiw. SSE2 cannot. */ const __m128 floats1 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi16(shorts1, zero)), divby128), minus1); const __m128 floats2 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi16(shorts2, zero)), divby128), minus1); const __m128 floats3 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi16(shorts1, zero)), divby128), minus1); const __m128 floats4 = _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi16(shorts2, zero)), divby128), minus1); /* Interleave back into correct order, store. */ _mm_store_ps(dst, _mm_unpacklo_ps(floats1, floats2)); _mm_store_ps(dst+4, _mm_unpackhi_ps(floats1, floats2)); _mm_store_ps(dst+8, _mm_unpacklo_ps(floats3, floats4)); _mm_store_ps(dst+12, _mm_unpackhi_ps(floats3, floats4)); i -= 16; mmsrc--; 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_SSE2(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 SSE2)"); /* 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 SSE 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 SSE blocks as long as we have 16 bytes available. */ const __m128 divby32768 = _mm_set1_ps(DIVBY32768); while (i >= 8) { /* 8 * 16-bit */ const __m128i ints = _mm_load_si128((__m128i const *) src); /* get 8 sint16 into an XMM register. */ /* treat as int32, shift left to clear every other sint16, then back right with sign-extend. Now sint32. */ const __m128i a = _mm_srai_epi32(_mm_slli_epi32(ints, 16), 16); /* right-shift-sign-extend gets us sint32 with the other set of values. */ const __m128i b = _mm_srai_epi32(ints, 16); /* Interleave these back into the right order, convert to float, multiply, store. */ _mm_store_ps(dst, _mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi32(a, b)), divby32768)); _mm_store_ps(dst+4, _mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi32(a, b)), 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_SSE2(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 SSE2)"); /* 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 SSE 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 SSE blocks as long as we have 16 bytes available. */ const __m128 divby32768 = _mm_set1_ps(DIVBY32768); const __m128 minus1 = _mm_set1_ps(-1.0f); while (i >= 8) { /* 8 * 16-bit */ const __m128i ints = _mm_load_si128((__m128i const *) src); /* get 8 sint16 into an XMM register. */ /* treat as int32, shift left to clear every other sint16, then back right with zero-extend. Now sint32. */ const __m128i a = _mm_srli_epi32(_mm_slli_epi32(ints, 16), 16); /* right-shift-sign-extend gets us sint32 with the other set of values. */ const __m128i b = _mm_srli_epi32(ints, 16); /* Interleave these back into the right order, convert to float, multiply, store. */ _mm_store_ps(dst, _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpacklo_epi32(a, b)), divby32768), minus1)); _mm_store_ps(dst+4, _mm_add_ps(_mm_mul_ps(_mm_cvtepi32_ps(_mm_unpackhi_epi32(a, b)), divby32768), minus1)); 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_SSE2(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 SSE2)"); /* 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)); /* 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 divby8388607 = _mm_set1_ps(DIVBY8388607); 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)); i -= 4; mmsrc++; 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_SSE2(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 SSE2)"); /* 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 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 */ _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++; } 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_SSE2(SDL_AudioCVT *cvt, SDL_AudioFormat format) { const float *src = (const float *) cvt->buf; Uint8 *dst = cvt->buf; int i; LOG_DEBUG_CONVERT("AUDIO_F32", "AUDIO_U8 (using SSE2)"); /* 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 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_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 */ _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++; } 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_SSE2(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 SSE2)"); /* 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 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 */ _mm_store_si128(mmdst, _mm_packs_epi32(ints1, ints2)); /* pack to sint16, store out. */ i -= 8; src += 8; mmdst++; } 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_SSE2(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 SSE2)"); /* 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 SSE blocks as long as we have 16 bytes available. */ /* This calculates differently than the scalar path because SSE2 can't pack int32 data down to unsigned int16. _mm_packs_epi32 does signed saturation, so that would corrupt our data. _mm_packus_epi32 exists, but not before SSE 4.1. So we convert from float to sint16, packing that down with legit signed saturation, and then xor the top bit against 1. This results in the correct unsigned 16-bit value, even 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 */ _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++; } 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_SSE2(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 SSE2)"); /* 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; } } SDL_assert(!i || ((((size_t) dst) & 15) == 0)); SDL_assert(!i || ((((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 mulby8388607 = _mm_set1_ps(8388607.0f); __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 */ i -= 4; src += 4; mmdst++; } 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 = (Sint32) -2147483648LL; } 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 #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_low_s16(int16lo))), divby128)); vst1q_f32(dst+4, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_high_s16(int16lo))), divby128)); vst1q_f32(dst+8, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_low_s16(int16hi))), divby128)); vst1q_f32(dst+12, vmulq_f32(vcvtq_f32_s32(vmovl_s16(vget_high_s16(int16hi))), 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 negone = 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, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_low_u16(uint16lo))), divby128)); vst1q_f32(dst+4, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_high_u16(uint16lo))), divby128)); vst1q_f32(dst+8, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_low_u16(uint16hi))), divby128)); vst1q_f32(dst+12, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_high_u16(uint16hi))), divby128)); 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 negone = 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, vmlaq_f32(negone, vcvtq_f32_u32(vmovl_u16(vget_low_u16(uints))), divby32768)); vst1q_f32(dst+4, vmlaq_f32(negone, 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)); /* 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 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 = (-2147483647) - 1; } 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 = (-2147483647) - 1; } 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; if (converters_chosen) { return; } #define SET_CONVERTER_FUNCS(fntype) \ SDL_Convert_S8_to_F32 = SDL_Convert_S8_to_F32_##fntype; \ SDL_Convert_U8_to_F32 = SDL_Convert_U8_to_F32_##fntype; \ SDL_Convert_S16_to_F32 = SDL_Convert_S16_to_F32_##fntype; \ SDL_Convert_U16_to_F32 = SDL_Convert_U16_to_F32_##fntype; \ SDL_Convert_S32_to_F32 = SDL_Convert_S32_to_F32_##fntype; \ SDL_Convert_F32_to_S8 = SDL_Convert_F32_to_S8_##fntype; \ SDL_Convert_F32_to_U8 = SDL_Convert_F32_to_U8_##fntype; \ SDL_Convert_F32_to_S16 = SDL_Convert_F32_to_S16_##fntype; \ SDL_Convert_F32_to_U16 = SDL_Convert_F32_to_U16_##fntype; \ SDL_Convert_F32_to_S32 = SDL_Convert_F32_to_S32_##fntype; \ converters_chosen = SDL_TRUE #if HAVE_SSE2_INTRINSICS if (SDL_HasSSE2()) { SET_CONVERTER_FUNCS(SSE2); return; } #endif #if HAVE_NEON_INTRINSICS if (SDL_HasNEON()) { SET_CONVERTER_FUNCS(NEON); return; } #endif #if NEED_SCALAR_CONVERTER_FALLBACKS SET_CONVERTER_FUNCS(Scalar); #endif #undef SET_CONVERTER_FUNCS SDL_assert(converters_chosen == SDL_TRUE); } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/SDL_audiotypecvt.c
C
apache-2.0
54,865
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" /* This provides the default mixing callback for the SDL audio routines */ #include "SDL_cpuinfo.h" #include "SDL_timer.h" #include "SDL_audio.h" #include "SDL_sysaudio.h" /* This table is used to add two sound values together and pin * the value to avoid overflow. (used with permission from ARDI) * Changed to use 0xFE instead of 0xFF for better sound quality. */ static const Uint8 mix8[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE }; /* The volume ranges from 0 - 128 */ #define ADJUST_VOLUME(s, v) (s = (s*v)/SDL_MIX_MAXVOLUME) #define ADJUST_VOLUME_U8(s, v) (s = (((s-128)*v)/SDL_MIX_MAXVOLUME)+128) void SDL_MixAudioFormat(Uint8 * dst, const Uint8 * src, SDL_AudioFormat format, Uint32 len, int volume) { if (volume == 0) { return; } switch (format) { case AUDIO_U8: { #if defined(__GNUC__) && defined(__M68000__) && !defined(__mcoldfire__) && defined(SDL_ASSEMBLY_ROUTINES) SDL_MixAudio_m68k_U8((char *) dst, (char *) src, (unsigned long) len, (long) volume, (char *) mix8); #else Uint8 src_sample; while (len--) { src_sample = *src; ADJUST_VOLUME_U8(src_sample, volume); *dst = mix8[*dst + src_sample]; ++dst; ++src; } #endif } break; case AUDIO_S8: { Sint8 *dst8, *src8; Sint8 src_sample; int dst_sample; const int max_audioval = ((1 << (8 - 1)) - 1); const int min_audioval = -(1 << (8 - 1)); src8 = (Sint8 *) src; dst8 = (Sint8 *) dst; while (len--) { src_sample = *src8; ADJUST_VOLUME(src_sample, volume); dst_sample = *dst8 + src_sample; if (dst_sample > max_audioval) { *dst8 = max_audioval; } else if (dst_sample < min_audioval) { *dst8 = min_audioval; } else { *dst8 = dst_sample; } ++dst8; ++src8; } } break; case AUDIO_S16LSB: { Sint16 src1, src2; int dst_sample; const int max_audioval = ((1 << (16 - 1)) - 1); const int min_audioval = -(1 << (16 - 1)); len /= 2; while (len--) { src1 = ((src[1]) << 8 | src[0]); ADJUST_VOLUME(src1, volume); src2 = ((dst[1]) << 8 | dst[0]); src += 2; dst_sample = src1 + src2; if (dst_sample > max_audioval) { dst_sample = max_audioval; } else if (dst_sample < min_audioval) { dst_sample = min_audioval; } dst[0] = dst_sample & 0xFF; dst_sample >>= 8; dst[1] = dst_sample & 0xFF; dst += 2; } } break; case AUDIO_S16MSB: { #if defined(__GNUC__) && defined(__M68000__) && !defined(__mcoldfire__) && defined(SDL_ASSEMBLY_ROUTINES) SDL_MixAudio_m68k_S16MSB((short *) dst, (short *) src, (unsigned long) len, (long) volume); #else Sint16 src1, src2; int dst_sample; const int max_audioval = ((1 << (16 - 1)) - 1); const int min_audioval = -(1 << (16 - 1)); len /= 2; while (len--) { src1 = ((src[0]) << 8 | src[1]); ADJUST_VOLUME(src1, volume); src2 = ((dst[0]) << 8 | dst[1]); src += 2; dst_sample = src1 + src2; if (dst_sample > max_audioval) { dst_sample = max_audioval; } else if (dst_sample < min_audioval) { dst_sample = min_audioval; } dst[1] = dst_sample & 0xFF; dst_sample >>= 8; dst[0] = dst_sample & 0xFF; dst += 2; } #endif } break; case AUDIO_U16LSB: { Uint16 src1, src2; int dst_sample; const int max_audioval = 0xFFFF; len /= 2; while (len--) { src1 = ((src[1]) << 8 | src[0]); ADJUST_VOLUME(src1, volume); src2 = ((dst[1]) << 8 | dst[0]); src += 2; dst_sample = src1 + src2; if (dst_sample > max_audioval) { dst_sample = max_audioval; } dst[0] = dst_sample & 0xFF; dst_sample >>= 8; dst[1] = dst_sample & 0xFF; dst += 2; } } break; case AUDIO_U16MSB: { Uint16 src1, src2; int dst_sample; const int max_audioval = 0xFFFF; len /= 2; while (len--) { src1 = ((src[0]) << 8 | src[1]); ADJUST_VOLUME(src1, volume); src2 = ((dst[0]) << 8 | dst[1]); src += 2; dst_sample = src1 + src2; if (dst_sample > max_audioval) { dst_sample = max_audioval; } dst[1] = dst_sample & 0xFF; dst_sample >>= 8; dst[0] = dst_sample & 0xFF; dst += 2; } } break; case AUDIO_S32LSB: { const Uint32 *src32 = (Uint32 *) src; Uint32 *dst32 = (Uint32 *) dst; Sint64 src1, src2; Sint64 dst_sample; const Sint64 max_audioval = ((((Sint64) 1) << (32 - 1)) - 1); const Sint64 min_audioval = -(((Sint64) 1) << (32 - 1)); len /= 4; while (len--) { src1 = (Sint64) ((Sint32) SDL_SwapLE32(*src32)); src32++; ADJUST_VOLUME(src1, volume); src2 = (Sint64) ((Sint32) SDL_SwapLE32(*dst32)); dst_sample = src1 + src2; if (dst_sample > max_audioval) { dst_sample = max_audioval; } else if (dst_sample < min_audioval) { dst_sample = min_audioval; } *(dst32++) = SDL_SwapLE32((Uint32) ((Sint32) dst_sample)); } } break; case AUDIO_S32MSB: { const Uint32 *src32 = (Uint32 *) src; Uint32 *dst32 = (Uint32 *) dst; Sint64 src1, src2; Sint64 dst_sample; const Sint64 max_audioval = ((((Sint64) 1) << (32 - 1)) - 1); const Sint64 min_audioval = -(((Sint64) 1) << (32 - 1)); len /= 4; while (len--) { src1 = (Sint64) ((Sint32) SDL_SwapBE32(*src32)); src32++; ADJUST_VOLUME(src1, volume); src2 = (Sint64) ((Sint32) SDL_SwapBE32(*dst32)); dst_sample = src1 + src2; if (dst_sample > max_audioval) { dst_sample = max_audioval; } else if (dst_sample < min_audioval) { dst_sample = min_audioval; } *(dst32++) = SDL_SwapBE32((Uint32) ((Sint32) dst_sample)); } } break; case AUDIO_F32LSB: { const float fmaxvolume = 1.0f / ((float) SDL_MIX_MAXVOLUME); const float fvolume = (float) volume; const float *src32 = (float *) src; float *dst32 = (float *) dst; float src1, src2; double dst_sample; /* !!! FIXME: are these right? */ const double max_audioval = 3.402823466e+38F; const double min_audioval = -3.402823466e+38F; len /= 4; while (len--) { src1 = ((SDL_SwapFloatLE(*src32) * fvolume) * fmaxvolume); src2 = SDL_SwapFloatLE(*dst32); src32++; dst_sample = ((double) src1) + ((double) src2); if (dst_sample > max_audioval) { dst_sample = max_audioval; } else if (dst_sample < min_audioval) { dst_sample = min_audioval; } *(dst32++) = SDL_SwapFloatLE((float) dst_sample); } } break; case AUDIO_F32MSB: { const float fmaxvolume = 1.0f / ((float) SDL_MIX_MAXVOLUME); const float fvolume = (float) volume; const float *src32 = (float *) src; float *dst32 = (float *) dst; float src1, src2; double dst_sample; /* !!! FIXME: are these right? */ const double max_audioval = 3.402823466e+38F; const double min_audioval = -3.402823466e+38F; len /= 4; while (len--) { src1 = ((SDL_SwapFloatBE(*src32) * fvolume) * fmaxvolume); src2 = SDL_SwapFloatBE(*dst32); src32++; dst_sample = ((double) src1) + ((double) src2); if (dst_sample > max_audioval) { dst_sample = max_audioval; } else if (dst_sample < min_audioval) { dst_sample = min_audioval; } *(dst32++) = SDL_SwapFloatBE((float) dst_sample); } } break; default: /* If this happens... FIXME! */ SDL_SetError("SDL_MixAudioFormat(): unknown audio format"); return; } } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/SDL_mixer.c
C
apache-2.0
14,062
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_sysaudio_h_ #define SDL_sysaudio_h_ #include "SDL_mutex.h" #include "SDL_thread.h" #include "../SDL_dataqueue.h" #include "./SDL_audio_c.h" /* !!! FIXME: These are wordy and unlocalized... */ #define DEFAULT_OUTPUT_DEVNAME "System audio output device" #define DEFAULT_INPUT_DEVNAME "System audio capture device" /* The SDL audio driver */ typedef struct SDL_AudioDevice SDL_AudioDevice; #define _THIS SDL_AudioDevice *_this /* Audio targets should call this as devices are added to the system (such as a USB headset being plugged in), and should also be called for for every device found during DetectDevices(). */ extern void SDL_AddAudioDevice(const int iscapture, const char *name, void *handle); /* Audio targets should call this as devices are removed, so SDL can update its list of available devices. */ extern void SDL_RemoveAudioDevice(const int iscapture, void *handle); /* Audio targets should call this if an opened audio device is lost while being used. This can happen due to i/o errors, or a device being unplugged, etc. If the device is totally gone, please also call SDL_RemoveAudioDevice() as appropriate so SDL's list of devices is accurate. */ extern void SDL_OpenedAudioDeviceDisconnected(SDL_AudioDevice *device); /* This is the size of a packet when using SDL_QueueAudio(). We allocate these as necessary and pool them, under the assumption that we'll eventually end up with a handful that keep recycling, meeting whatever the app needs. We keep packing data tightly as more arrives to avoid wasting space, and if we get a giant block of data, we'll split them into multiple packets behind the scenes. My expectation is that most apps will have 2-3 of these in the pool. 8k should cover most needs, but if this is crippling for some embedded system, we can #ifdef this. The system preallocates enough packets for 2 callbacks' worth of data. */ #define SDL_AUDIOBUFFERQUEUE_PACKETLEN (8 * 1024) typedef struct SDL_AudioDriverImpl { void (*DetectDevices) (void); int (*OpenDevice) (_THIS, void *handle, const char *devname, int iscapture); void (*ThreadInit) (_THIS); /* Called by audio thread at start */ void (*ThreadDeinit) (_THIS); /* Called by audio thread at end */ void (*BeginLoopIteration)(_THIS); /* Called by audio thread at top of loop */ void (*WaitDevice) (_THIS); void (*PlayDevice) (_THIS); Uint8 *(*GetDeviceBuf) (_THIS); int (*CaptureFromDevice) (_THIS, void *buffer, int buflen); void (*FlushCapture) (_THIS); void (*PrepareToClose) (_THIS); /**< Called between run and draining wait for playback devices */ void (*CloseDevice) (_THIS); void (*LockDevice) (_THIS); void (*UnlockDevice) (_THIS); void (*FreeDeviceHandle) (void *handle); /**< SDL is done with handle from SDL_AddAudioDevice() */ void (*Deinitialize) (void); /* !!! FIXME: add pause(), so we can optimize instead of mixing silence. */ /* Some flags to push duplicate code into the core and reduce #ifdefs. */ /* !!! FIXME: these should be SDL_bool */ int ProvidesOwnCallbackThread; int SkipMixerLock; int HasCaptureSupport; int OnlyHasDefaultOutputDevice; int OnlyHasDefaultCaptureDevice; int AllowsArbitraryDeviceNames; } SDL_AudioDriverImpl; typedef struct SDL_AudioDeviceItem { void *handle; char *name; char *original_name; int dupenum; struct SDL_AudioDeviceItem *next; } SDL_AudioDeviceItem; typedef struct SDL_AudioDriver { /* * * */ /* The name of this audio driver */ const char *name; /* * * */ /* The description of this audio driver */ const char *desc; SDL_AudioDriverImpl impl; /* A mutex for device detection */ SDL_mutex *detectionLock; SDL_bool captureDevicesRemoved; SDL_bool outputDevicesRemoved; int outputDeviceCount; int inputDeviceCount; SDL_AudioDeviceItem *outputDevices; SDL_AudioDeviceItem *inputDevices; } SDL_AudioDriver; /* Define the SDL audio driver structure */ struct SDL_AudioDevice { /* * * */ /* Data common to all devices */ SDL_AudioDeviceID id; /* The device's current audio specification */ SDL_AudioSpec spec; /* The callback's expected audio specification (converted vs device's spec). */ SDL_AudioSpec callbackspec; /* Stream that converts and resamples. NULL if not needed. */ SDL_AudioStream *stream; /* Current state flags */ SDL_atomic_t shutdown; /* true if we are signaling the play thread to end. */ SDL_atomic_t enabled; /* true if device is functioning and connected. */ SDL_atomic_t paused; SDL_bool iscapture; /* Scratch buffer used in the bridge between SDL and the user callback. */ Uint8 *work_buffer; /* Size, in bytes, of work_buffer. */ Uint32 work_buffer_len; /* A mutex for locking the mixing buffers */ SDL_mutex *mixer_lock; /* A thread to feed the audio device */ SDL_Thread *thread; SDL_threadID threadid; /* Queued buffers (if app not using callback). */ SDL_DataQueue *buffer_queue; /* * * */ /* Data private to this driver */ struct SDL_PrivateAudioData *hidden; void *handle; }; #undef _THIS typedef struct AudioBootStrap { const char *name; const char *desc; int (*init) (SDL_AudioDriverImpl * impl); int demand_only; /* 1==request explicitly, or it won't be available. */ } AudioBootStrap; /* Not all of these are available in a given build. Use #ifdefs, etc. */ extern AudioBootStrap PULSEAUDIO_bootstrap; extern AudioBootStrap ALSA_bootstrap; extern AudioBootStrap JACK_bootstrap; extern AudioBootStrap SNDIO_bootstrap; extern AudioBootStrap NETBSDAUDIO_bootstrap; extern AudioBootStrap DSP_bootstrap; extern AudioBootStrap QSAAUDIO_bootstrap; extern AudioBootStrap SUNAUDIO_bootstrap; extern AudioBootStrap ARTS_bootstrap; extern AudioBootStrap ESD_bootstrap; extern AudioBootStrap NACLAUDIO_bootstrap; extern AudioBootStrap NAS_bootstrap; extern AudioBootStrap WASAPI_bootstrap; extern AudioBootStrap DSOUND_bootstrap; extern AudioBootStrap WINMM_bootstrap; extern AudioBootStrap PAUDIO_bootstrap; extern AudioBootStrap HAIKUAUDIO_bootstrap; extern AudioBootStrap COREAUDIO_bootstrap; extern AudioBootStrap DISKAUDIO_bootstrap; extern AudioBootStrap DUMMYAUDIO_bootstrap; extern AudioBootStrap FUSIONSOUND_bootstrap; extern AudioBootStrap openslES_bootstrap; extern AudioBootStrap ANDROIDAUDIO_bootstrap; extern AudioBootStrap PSPAUDIO_bootstrap; extern AudioBootStrap EMSCRIPTENAUDIO_bootstrap; extern AudioBootStrap AOSAUDIO_bootstrap; #endif /* SDL_sysaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/SDL_sysaudio.h
C
apache-2.0
7,658
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #ifdef HAVE_LIMITS_H #include <limits.h> #else #ifndef SIZE_MAX #define SIZE_MAX ((size_t)-1) #endif #ifndef INT_MAX /* Make a lucky guess. */ #define INT_MAX SDL_MAX_SINT32 #endif #endif /* Microsoft WAVE file loading routines */ #include "SDL_hints.h" #include "SDL_audio.h" #include "SDL_wave.h" #include "SDL_audio_c.h" /* Reads the value stored at the location of the f1 pointer, multiplies it * with the second argument and then stores the result to f1. * Returns 0 on success, or -1 if the multiplication overflows, in which case f1 * does not get modified. */ static int SafeMult(size_t *f1, size_t f2) { if (*f1 > 0 && SIZE_MAX / *f1 <= f2) { return -1; } *f1 *= f2; return 0; } typedef struct ADPCM_DecoderState { Uint32 channels; /* Number of channels. */ size_t blocksize; /* Size of an ADPCM block in bytes. */ size_t blockheadersize; /* Size of an ADPCM block header in bytes. */ size_t samplesperblock; /* Number of samples per channel in an ADPCM block. */ size_t framesize; /* Size of a sample frame (16-bit PCM) in bytes. */ Sint64 framestotal; /* Total number of sample frames. */ Sint64 framesleft; /* Number of sample frames still to be decoded. */ void *ddata; /* Decoder data from initialization. */ void *cstate; /* Decoding state for each channel. */ /* ADPCM data. */ struct { Uint8 *data; size_t size; size_t pos; } input; /* Current ADPCM block in the ADPCM data above. */ struct { Uint8 *data; size_t size; size_t pos; } block; /* Decoded 16-bit PCM data. */ struct { Sint16 *data; size_t size; size_t pos; } output; } ADPCM_DecoderState; typedef struct MS_ADPCM_CoeffData { Uint16 coeffcount; Sint16 *coeff; Sint16 aligndummy; /* Has to be last member. */ } MS_ADPCM_CoeffData; typedef struct MS_ADPCM_ChannelState { Uint16 delta; Sint16 coeff1; Sint16 coeff2; } MS_ADPCM_ChannelState; #ifdef SDL_WAVE_DEBUG_LOG_FORMAT static void WaveDebugLogFormat(WaveFile *file) { WaveFormat *format = &file->format; const char *fmtstr = "WAVE file: %s, %u Hz, %s, %u bits, %u %s/s"; const char *waveformat, *wavechannel, *wavebpsunit = "B"; Uint32 wavebps = format->byterate; char channelstr[64]; SDL_zeroa(channelstr); switch (format->encoding) { case PCM_CODE: waveformat = "PCM"; break; case IEEE_FLOAT_CODE: waveformat = "IEEE Float"; break; case ALAW_CODE: waveformat = "A-law"; break; case MULAW_CODE: waveformat = "\xc2\xb5-law"; break; case MS_ADPCM_CODE: waveformat = "MS ADPCM"; break; case IMA_ADPCM_CODE: waveformat = "IMA ADPCM"; break; default: waveformat = "Unknown"; break; } #define SDL_WAVE_DEBUG_CHANNELCFG(STR, CODE) case CODE: wavechannel = STR; break; #define SDL_WAVE_DEBUG_CHANNELSTR(STR, CODE) if (format->channelmask & CODE) { \ SDL_strlcat(channelstr, channelstr[0] ? "-" STR : STR, sizeof(channelstr));} if (format->formattag == EXTENSIBLE_CODE && format->channelmask > 0) { switch (format->channelmask) { SDL_WAVE_DEBUG_CHANNELCFG("1.0 Mono", 0x4) SDL_WAVE_DEBUG_CHANNELCFG("1.1 Mono", 0xc) SDL_WAVE_DEBUG_CHANNELCFG("2.0 Stereo", 0x3) SDL_WAVE_DEBUG_CHANNELCFG("2.1 Stereo", 0xb) SDL_WAVE_DEBUG_CHANNELCFG("3.0 Stereo", 0x7) SDL_WAVE_DEBUG_CHANNELCFG("3.1 Stereo", 0xf) SDL_WAVE_DEBUG_CHANNELCFG("3.0 Surround", 0x103) SDL_WAVE_DEBUG_CHANNELCFG("3.1 Surround", 0x10b) SDL_WAVE_DEBUG_CHANNELCFG("4.0 Quad", 0x33) SDL_WAVE_DEBUG_CHANNELCFG("4.1 Quad", 0x3b) SDL_WAVE_DEBUG_CHANNELCFG("4.0 Surround", 0x107) SDL_WAVE_DEBUG_CHANNELCFG("4.1 Surround", 0x10f) SDL_WAVE_DEBUG_CHANNELCFG("5.0", 0x37) SDL_WAVE_DEBUG_CHANNELCFG("5.1", 0x3f) SDL_WAVE_DEBUG_CHANNELCFG("5.0 Side", 0x607) SDL_WAVE_DEBUG_CHANNELCFG("5.1 Side", 0x60f) SDL_WAVE_DEBUG_CHANNELCFG("6.0", 0x137) SDL_WAVE_DEBUG_CHANNELCFG("6.1", 0x13f) SDL_WAVE_DEBUG_CHANNELCFG("6.0 Side", 0x707) SDL_WAVE_DEBUG_CHANNELCFG("6.1 Side", 0x70f) SDL_WAVE_DEBUG_CHANNELCFG("7.0", 0xf7) SDL_WAVE_DEBUG_CHANNELCFG("7.1", 0xff) SDL_WAVE_DEBUG_CHANNELCFG("7.0 Side", 0x6c7) SDL_WAVE_DEBUG_CHANNELCFG("7.1 Side", 0x6cf) SDL_WAVE_DEBUG_CHANNELCFG("7.0 Surround", 0x637) SDL_WAVE_DEBUG_CHANNELCFG("7.1 Surround", 0x63f) SDL_WAVE_DEBUG_CHANNELCFG("9.0 Surround", 0x5637) SDL_WAVE_DEBUG_CHANNELCFG("9.1 Surround", 0x563f) SDL_WAVE_DEBUG_CHANNELCFG("11.0 Surround", 0x56f7) SDL_WAVE_DEBUG_CHANNELCFG("11.1 Surround", 0x56ff) default: SDL_WAVE_DEBUG_CHANNELSTR("FL", 0x1) SDL_WAVE_DEBUG_CHANNELSTR("FR", 0x2) SDL_WAVE_DEBUG_CHANNELSTR("FC", 0x4) SDL_WAVE_DEBUG_CHANNELSTR("LF", 0x8) SDL_WAVE_DEBUG_CHANNELSTR("BL", 0x10) SDL_WAVE_DEBUG_CHANNELSTR("BR", 0x20) SDL_WAVE_DEBUG_CHANNELSTR("FLC", 0x40) SDL_WAVE_DEBUG_CHANNELSTR("FRC", 0x80) SDL_WAVE_DEBUG_CHANNELSTR("BC", 0x100) SDL_WAVE_DEBUG_CHANNELSTR("SL", 0x200) SDL_WAVE_DEBUG_CHANNELSTR("SR", 0x400) SDL_WAVE_DEBUG_CHANNELSTR("TC", 0x800) SDL_WAVE_DEBUG_CHANNELSTR("TFL", 0x1000) SDL_WAVE_DEBUG_CHANNELSTR("TFC", 0x2000) SDL_WAVE_DEBUG_CHANNELSTR("TFR", 0x4000) SDL_WAVE_DEBUG_CHANNELSTR("TBL", 0x8000) SDL_WAVE_DEBUG_CHANNELSTR("TBC", 0x10000) SDL_WAVE_DEBUG_CHANNELSTR("TBR", 0x20000) break; } } else { switch (format->channels) { default: if (SDL_snprintf(channelstr, sizeof(channelstr), "%u channels", format->channels) >= 0) { wavechannel = channelstr; break; } case 0: wavechannel = "Unknown"; break; case 1: wavechannel = "Mono"; break; case 2: wavechannel = "Setero"; break; } } #undef SDL_WAVE_DEBUG_CHANNELCFG #undef SDL_WAVE_DEBUG_CHANNELSTR if (wavebps >= 1024) { wavebpsunit = "KiB"; wavebps = wavebps / 1024 + (wavebps & 0x3ff ? 1 : 0); } SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, fmtstr, waveformat, format->frequency, wavechannel, format->bitspersample, wavebps, wavebpsunit); } #endif #ifdef SDL_WAVE_DEBUG_DUMP_FORMAT static void WaveDebugDumpFormat(WaveFile *file, Uint32 rifflen, Uint32 fmtlen, Uint32 datalen) { WaveFormat *format = &file->format; const char *fmtstr1 = "WAVE chunk dump:\n" "-------------------------------------------\n" "RIFF %11u\n" "-------------------------------------------\n" " fmt %11u\n" " wFormatTag 0x%04x\n" " nChannels %11u\n" " nSamplesPerSec %11u\n" " nAvgBytesPerSec %11u\n" " nBlockAlign %11u\n"; const char *fmtstr2 = " wBitsPerSample %11u\n"; const char *fmtstr3 = " cbSize %11u\n"; const char *fmtstr4a = " wValidBitsPerSample %11u\n"; const char *fmtstr4b = " wSamplesPerBlock %11u\n"; const char *fmtstr5 = " dwChannelMask 0x%08x\n" " SubFormat\n" " %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x\n"; const char *fmtstr6 = "-------------------------------------------\n" " fact\n" " dwSampleLength %11u\n"; const char *fmtstr7 = "-------------------------------------------\n" " data %11u\n" "-------------------------------------------\n"; char *dumpstr; size_t dumppos = 0; const size_t bufsize = 1024; int res; dumpstr = SDL_malloc(bufsize); if (dumpstr == NULL) { return; } dumpstr[0] = 0; res = SDL_snprintf(dumpstr, bufsize, fmtstr1, rifflen, fmtlen, format->formattag, format->channels, format->frequency, format->byterate, format->blockalign); dumppos += res > 0 ? res : 0; if (fmtlen >= 16) { res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr2, format->bitspersample); dumppos += res > 0 ? res : 0; } if (fmtlen >= 18) { res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr3, format->extsize); dumppos += res > 0 ? res : 0; } if (format->formattag == EXTENSIBLE_CODE && fmtlen >= 40 && format->extsize >= 22) { const Uint8 *g = format->subformat; const Uint32 g1 = g[0] | ((Uint32)g[1] << 8) | ((Uint32)g[2] << 16) | ((Uint32)g[3] << 24); const Uint32 g2 = g[4] | ((Uint32)g[5] << 8); const Uint32 g3 = g[6] | ((Uint32)g[7] << 8); switch (format->encoding) { default: res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4a, format->validsamplebits); dumppos += res > 0 ? res : 0; break; case MS_ADPCM_CODE: case IMA_ADPCM_CODE: res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4b, format->samplesperblock); dumppos += res > 0 ? res : 0; break; } res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr5, format->channelmask, g1, g2, g3, g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]); dumppos += res > 0 ? res : 0; } else { switch (format->encoding) { case MS_ADPCM_CODE: case IMA_ADPCM_CODE: if (fmtlen >= 20 && format->extsize >= 2) { res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4b, format->samplesperblock); dumppos += res > 0 ? res : 0; } break; } } if (file->fact.status >= 1) { res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr6, file->fact.samplelength); dumppos += res > 0 ? res : 0; } res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr7, datalen); dumppos += res > 0 ? res : 0; SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, "%s", dumpstr); free(dumpstr); } #endif static Sint64 WaveAdjustToFactValue(WaveFile *file, Sint64 sampleframes) { if (file->fact.status == 2) { if (file->facthint == FactStrict && sampleframes < file->fact.samplelength) { return SDL_SetError("Invalid number of sample frames in WAVE fact chunk (too many)"); } else if (sampleframes > file->fact.samplelength) { return file->fact.samplelength; } } return sampleframes; } static int MS_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength) { WaveFormat *format = &file->format; const size_t blockheadersize = (size_t)file->format.channels * 7; const size_t availableblocks = datalength / file->format.blockalign; const size_t blockframebitsize = (size_t)file->format.bitspersample * file->format.channels; const size_t trailingdata = datalength % file->format.blockalign; if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) { /* The size of the data chunk must be a multiple of the block size. */ if (datalength < blockheadersize || trailingdata > 0) { return SDL_SetError("Truncated MS ADPCM block"); } } /* Calculate number of sample frames that will be decoded. */ file->sampleframes = (Sint64)availableblocks * format->samplesperblock; if (trailingdata > 0) { /* The last block is truncated. Check if we can get any samples out of it. */ if (file->trunchint == TruncDropFrame) { /* Drop incomplete sample frame. */ if (trailingdata >= blockheadersize) { size_t trailingsamples = 2 + (trailingdata - blockheadersize) * 8 / blockframebitsize; if (trailingsamples > format->samplesperblock) { trailingsamples = format->samplesperblock; } file->sampleframes += trailingsamples; } } } file->sampleframes = WaveAdjustToFactValue(file, file->sampleframes); if (file->sampleframes < 0) { return -1; } return 0; } static int MS_ADPCM_Init(WaveFile *file, size_t datalength) { WaveFormat *format = &file->format; WaveChunk *chunk = &file->chunk; const size_t blockheadersize = (size_t)format->channels * 7; const size_t blockdatasize = (size_t)format->blockalign - blockheadersize; const size_t blockframebitsize = (size_t)format->bitspersample * format->channels; const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize; const Sint16 presetcoeffs[14] = {256, 0, 512, -256, 0, 0, 192, 64, 240, 0, 460, -208, 392, -232}; size_t i, coeffcount; MS_ADPCM_CoeffData *coeffdata; /* Sanity checks. */ /* While it's clear how IMA ADPCM handles more than two channels, the nibble * order of MS ADPCM makes it awkward. The Standards Update does not talk * about supporting more than stereo anyway. */ if (format->channels > 2) { return SDL_SetError("Invalid number of channels"); } if (format->bitspersample != 4) { return SDL_SetError("Invalid MS ADPCM bits per sample of %u", (unsigned int)format->bitspersample); } /* The block size must be big enough to contain the block header. */ if (format->blockalign < blockheadersize) { return SDL_SetError("Invalid MS ADPCM block size (nBlockAlign)"); } if (format->formattag == EXTENSIBLE_CODE) { /* Does have a GUID (like all format tags), but there's no specification * for how the data is packed into the extensible header. Making * assumptions here could lead to new formats nobody wants to support. */ return SDL_SetError("MS ADPCM with the extensible header is not supported"); } /* There are wSamplesPerBlock, wNumCoef, and at least 7 coefficient pairs in * the extended part of the header. */ if (chunk->size < 22) { return SDL_SetError("Could not read MS ADPCM format header"); } format->samplesperblock = chunk->data[18] | ((Uint16)chunk->data[19] << 8); /* Number of coefficient pairs. A pair has two 16-bit integers. */ coeffcount = chunk->data[20] | ((size_t)chunk->data[21] << 8); /* bPredictor, the integer offset into the coefficients array, is only * 8 bits. It can only address the first 256 coefficients. Let's limit * the count number here. */ if (coeffcount > 256) { coeffcount = 256; } if (chunk->size < 22 + coeffcount * 4) { return SDL_SetError("Could not read custom coefficients in MS ADPCM format header"); } else if (format->extsize < 4 + coeffcount * 4) { return SDL_SetError("Invalid MS ADPCM format header (too small)"); } else if (coeffcount < 7) { return SDL_SetError("Missing required coefficients in MS ADPCM format header"); } coeffdata = (MS_ADPCM_CoeffData *)SDL_malloc(sizeof(MS_ADPCM_CoeffData) + coeffcount * 4); file->decoderdata = coeffdata; /* Freed in cleanup. */ if (coeffdata == NULL) { return SDL_OutOfMemory(); } coeffdata->coeff = &coeffdata->aligndummy; coeffdata->coeffcount = (Uint16)coeffcount; /* Copy the 16-bit pairs. */ for (i = 0; i < coeffcount * 2; i++) { Sint32 c = chunk->data[22 + i * 2] | ((Sint32)chunk->data[23 + i * 2] << 8); if (c >= 0x8000) { c -= 0x10000; } if (i < 14 && c != presetcoeffs[i]) { return SDL_SetError("Wrong preset coefficients in MS ADPCM format header"); } coeffdata->coeff[i] = (Sint16)c; } /* Technically, wSamplesPerBlock is required, but we have all the * information in the other fields to calculate it, if it's zero. */ if (format->samplesperblock == 0) { /* Let's be nice to the encoders that didn't know how to fill this. * The Standards Update calculates it this way: * * x = Block size (in bits) minus header size (in bits) * y = Bit depth multiplied by channel count * z = Number of samples per channel in block header * wSamplesPerBlock = x / y + z */ format->samplesperblock = (Uint32)blockdatasamples + 2; } /* nBlockAlign can be in conflict with wSamplesPerBlock. For example, if * the number of samples doesn't fit into the block. The Standards Update * also describes wSamplesPerBlock with a formula that makes it necessary to * always fill the block with the maximum amount of samples, but this is not * enforced here as there are no compatibility issues. * A truncated block header with just one sample is not supported. */ if (format->samplesperblock == 1 || blockdatasamples < format->samplesperblock - 2) { return SDL_SetError("Invalid number of samples per MS ADPCM block (wSamplesPerBlock)"); } if (MS_ADPCM_CalculateSampleFrames(file, datalength) < 0) { return -1; } return 0; } static Sint16 MS_ADPCM_ProcessNibble(MS_ADPCM_ChannelState *cstate, Sint32 sample1, Sint32 sample2, Uint8 nybble) { const Sint32 max_audioval = 32767; const Sint32 min_audioval = -32768; const Uint16 max_deltaval = 65535; const Uint16 adaptive[] = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }; Sint32 new_sample; Sint32 errordelta; Uint32 delta = cstate->delta; new_sample = (sample1 * cstate->coeff1 + sample2 * cstate->coeff2) / 256; /* The nibble is a signed 4-bit error delta. */ errordelta = (Sint32)nybble - (nybble >= 0x08 ? 0x10 : 0); new_sample += (Sint32)delta * errordelta; if (new_sample < min_audioval) { new_sample = min_audioval; } else if (new_sample > max_audioval) { new_sample = max_audioval; } delta = (delta * adaptive[nybble]) / 256; if (delta < 16) { delta = 16; } else if (delta > max_deltaval) { /* This issue is not described in the Standards Update and therefore * undefined. It seems sensible to prevent overflows with a limit. */ delta = max_deltaval; } cstate->delta = (Uint16)delta; return (Sint16)new_sample; } static int MS_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state) { Uint8 coeffindex; const Uint32 channels = state->channels; Sint32 sample; Uint32 c; MS_ADPCM_ChannelState *cstate = (MS_ADPCM_ChannelState *)state->cstate; MS_ADPCM_CoeffData *ddata = (MS_ADPCM_CoeffData *)state->ddata; for (c = 0; c < channels; c++) { size_t o = c; /* Load the coefficient pair into the channel state. */ coeffindex = state->block.data[o]; if (coeffindex > ddata->coeffcount) { return SDL_SetError("Invalid MS ADPCM coefficient index in block header"); } cstate[c].coeff1 = ddata->coeff[coeffindex * 2]; cstate[c].coeff2 = ddata->coeff[coeffindex * 2 + 1]; /* Initial delta value. */ o = channels + c * 2; cstate[c].delta = state->block.data[o] | ((Uint16)state->block.data[o + 1] << 8); /* Load the samples from the header. Interestingly, the sample later in * the output stream comes first. */ o = channels * 3 + c * 2; sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8); if (sample >= 0x8000) { sample -= 0x10000; } state->output.data[state->output.pos + channels] = (Sint16)sample; o = channels * 5 + c * 2; sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8); if (sample >= 0x8000) { sample -= 0x10000; } state->output.data[state->output.pos] = (Sint16)sample; state->output.pos++; } state->block.pos += state->blockheadersize; /* Skip second sample frame that came from the header. */ state->output.pos += state->channels; /* Header provided two sample frames. */ state->framesleft -= 2; return 0; } /* Decodes the data of the MS ADPCM block. Decoding will stop if a block is too * short, returning with none or partially decoded data. The partial data * will always contain full sample frames (same sample count for each channel). * Incomplete sample frames are discarded. */ static int MS_ADPCM_DecodeBlockData(ADPCM_DecoderState *state) { Uint16 nybble = 0; Sint16 sample1, sample2; const Uint32 channels = state->channels; Uint32 c; MS_ADPCM_ChannelState *cstate = (MS_ADPCM_ChannelState *)state->cstate; size_t blockpos = state->block.pos; size_t blocksize = state->block.size; size_t outpos = state->output.pos; Sint64 blockframesleft = state->samplesperblock - 2; if (blockframesleft > state->framesleft) { blockframesleft = state->framesleft; } while (blockframesleft > 0) { for (c = 0; c < channels; c++) { if (nybble & 0x4000) { nybble <<= 4; } else if (blockpos < blocksize) { nybble = state->block.data[blockpos++] | 0x4000; } else { /* Out of input data. Drop the incomplete frame and return. */ state->output.pos = outpos - c; return -1; } /* Load previous samples which may come from the block header. */ sample1 = state->output.data[outpos - channels]; sample2 = state->output.data[outpos - channels * 2]; sample1 = MS_ADPCM_ProcessNibble(cstate + c, sample1, sample2, (nybble >> 4) & 0x0f); state->output.data[outpos++] = sample1; } state->framesleft--; blockframesleft--; } state->output.pos = outpos; return 0; } static int MS_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len) { int result; size_t bytesleft, outputsize; WaveChunk *chunk = &file->chunk; ADPCM_DecoderState state; MS_ADPCM_ChannelState cstate[2]; SDL_zero(state); SDL_zeroa(cstate); if (chunk->size != chunk->length) { /* Could not read everything. Recalculate number of sample frames. */ if (MS_ADPCM_CalculateSampleFrames(file, chunk->size) < 0) { return -1; } } /* Nothing to decode, nothing to return. */ if (file->sampleframes == 0) { *audio_buf = NULL; *audio_len = 0; return 0; } state.blocksize = file->format.blockalign; state.channels = file->format.channels; state.blockheadersize = (size_t)state.channels * 7; state.samplesperblock = file->format.samplesperblock; state.framesize = state.channels * sizeof(Sint16); state.ddata = file->decoderdata; state.framestotal = file->sampleframes; state.framesleft = state.framestotal; state.input.data = chunk->data; state.input.size = chunk->size; state.input.pos = 0; /* The output size in bytes. May get modified if data is truncated. */ outputsize = (size_t)state.framestotal; if (SafeMult(&outputsize, state.framesize)) { return SDL_OutOfMemory(); } else if (outputsize > SDL_MAX_UINT32 || state.framestotal > SIZE_MAX) { return SDL_SetError("WAVE file too big"); } state.output.pos = 0; state.output.size = outputsize / sizeof(Sint16); state.output.data = (Sint16 *)SDL_malloc(outputsize); if (state.output.data == NULL) { return SDL_OutOfMemory(); } state.cstate = cstate; /* Decode block by block. A truncated block will stop the decoding. */ bytesleft = state.input.size - state.input.pos; while (state.framesleft > 0 && bytesleft >= state.blockheadersize) { state.block.data = state.input.data + state.input.pos; state.block.size = bytesleft < state.blocksize ? bytesleft : state.blocksize; state.block.pos = 0; if (state.output.size - state.output.pos < (Uint64)state.framesleft * state.channels) { /* Somehow didn't allocate enough space for the output. */ SDL_free(state.output.data); return SDL_SetError("Unexpected overflow in MS ADPCM decoder"); } /* Initialize decoder with the values from the block header. */ result = MS_ADPCM_DecodeBlockHeader(&state); if (result == -1) { SDL_free(state.output.data); return -1; } /* Decode the block data. It stores the samples directly in the output. */ result = MS_ADPCM_DecodeBlockData(&state); if (result == -1) { /* Unexpected end. Stop decoding and return partial data if necessary. */ if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) { SDL_free(state.output.data); return SDL_SetError("Truncated data chunk"); } else if (file->trunchint != TruncDropFrame) { state.output.pos -= state.output.pos % (state.samplesperblock * state.channels); } outputsize = state.output.pos * sizeof(Sint16); /* Can't overflow, is always smaller. */ break; } state.input.pos += state.block.size; bytesleft = state.input.size - state.input.pos; } *audio_buf = (Uint8 *)state.output.data; *audio_len = (Uint32)outputsize; return 0; } static int IMA_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength) { WaveFormat *format = &file->format; const size_t blockheadersize = (size_t)format->channels * 4; const size_t subblockframesize = (size_t)format->channels * 4; const size_t availableblocks = datalength / format->blockalign; const size_t trailingdata = datalength % format->blockalign; if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) { /* The size of the data chunk must be a multiple of the block size. */ if (datalength < blockheadersize || trailingdata > 0) { return SDL_SetError("Truncated IMA ADPCM block"); } } /* Calculate number of sample frames that will be decoded. */ file->sampleframes = (Uint64)availableblocks * format->samplesperblock; if (trailingdata > 0) { /* The last block is truncated. Check if we can get any samples out of it. */ if (file->trunchint == TruncDropFrame && trailingdata > blockheadersize - 2) { /* The sample frame in the header of the truncated block is present. * Drop incomplete sample frames. */ size_t trailingsamples = 1; if (trailingdata > blockheadersize) { /* More data following after the header. */ const size_t trailingblockdata = trailingdata - blockheadersize; const size_t trailingsubblockdata = trailingblockdata % subblockframesize; trailingsamples += (trailingblockdata / subblockframesize) * 8; /* Due to the interleaved sub-blocks, the last 4 bytes determine * how many samples of the truncated sub-block are lost. */ if (trailingsubblockdata > subblockframesize - 4) { trailingsamples += (trailingsubblockdata % 4) * 2; } } if (trailingsamples > format->samplesperblock) { trailingsamples = format->samplesperblock; } file->sampleframes += trailingsamples; } } file->sampleframes = WaveAdjustToFactValue(file, file->sampleframes); if (file->sampleframes < 0) { return -1; } return 0; } static int IMA_ADPCM_Init(WaveFile *file, size_t datalength) { WaveFormat *format = &file->format; WaveChunk *chunk = &file->chunk; const size_t blockheadersize = (size_t)format->channels * 4; const size_t blockdatasize = (size_t)format->blockalign - blockheadersize; const size_t blockframebitsize = (size_t)format->bitspersample * format->channels; const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize; /* Sanity checks. */ /* IMA ADPCM can also have 3-bit samples, but it's not supported by SDL at this time. */ if (format->bitspersample == 3) { return SDL_SetError("3-bit IMA ADPCM currently not supported"); } else if (format->bitspersample != 4) { return SDL_SetError("Invalid IMA ADPCM bits per sample of %u", (unsigned int)format->bitspersample); } /* The block size is required to be a multiple of 4 and it must be able to * hold a block header. */ if (format->blockalign < blockheadersize || format->blockalign % 4) { return SDL_SetError("Invalid IMA ADPCM block size (nBlockAlign)"); } if (format->formattag == EXTENSIBLE_CODE) { /* There's no specification for this, but it's basically the same * format because the extensible header has wSampePerBlocks too. */ } else { /* The Standards Update says there 'should' be 2 bytes for wSamplesPerBlock. */ if (chunk->size >= 20 && format->extsize >= 2) { format->samplesperblock = chunk->data[18] | ((Uint16)chunk->data[19] << 8); } } if (format->samplesperblock == 0) { /* Field zero? No problem. We just assume the encoder packed the block. * The specification calculates it this way: * * x = Block size (in bits) minus header size (in bits) * y = Bit depth multiplied by channel count * z = Number of samples per channel in header * wSamplesPerBlock = x / y + z */ format->samplesperblock = (Uint32)blockdatasamples + 1; } /* nBlockAlign can be in conflict with wSamplesPerBlock. For example, if * the number of samples doesn't fit into the block. The Standards Update * also describes wSamplesPerBlock with a formula that makes it necessary * to always fill the block with the maximum amount of samples, but this is * not enforced here as there are no compatibility issues. */ if (blockdatasamples < format->samplesperblock - 1) { return SDL_SetError("Invalid number of samples per IMA ADPCM block (wSamplesPerBlock)"); } if (IMA_ADPCM_CalculateSampleFrames(file, datalength) < 0) { return -1; } return 0; } static Sint16 IMA_ADPCM_ProcessNibble(Sint8 *cindex, Sint16 lastsample, Uint8 nybble) { const Sint32 max_audioval = 32767; const Sint32 min_audioval = -32768; const Sint8 index_table_4b[16] = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8 }; const Uint16 step_table[89] = { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 }; Uint32 step; Sint32 sample, delta; Sint8 index = *cindex; /* Clamp index into valid range. */ if (index > 88) { index = 88; } else if (index < 0) { index = 0; } /* explicit cast to avoid gcc warning about using 'char' as array index */ step = step_table[(size_t)index]; /* Update index value */ *cindex = index + index_table_4b[nybble]; /* This calculation uses shifts and additions because multiplications were * much slower back then. Sadly, this can't just be replaced with an actual * multiplication now as the old algorithm drops some bits. The closest * approximation I could find is something like this: * (nybble & 0x8 ? -1 : 1) * ((nybble & 0x7) * step / 4 + step / 8) */ delta = step >> 3; if (nybble & 0x04) delta += step; if (nybble & 0x02) delta += step >> 1; if (nybble & 0x01) delta += step >> 2; if (nybble & 0x08) delta = -delta; sample = lastsample + delta; /* Clamp output sample */ if (sample > max_audioval) { sample = max_audioval; } else if (sample < min_audioval) { sample = min_audioval; } return (Sint16)sample; } static int IMA_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state) { Sint16 step; Uint32 c; Uint8 *cstate = state->cstate; for (c = 0; c < state->channels; c++) { size_t o = state->block.pos + c * 4; /* Extract the sample from the header. */ Sint32 sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8); if (sample >= 0x8000) { sample -= 0x10000; } state->output.data[state->output.pos++] = (Sint16)sample; /* Channel step index. */ step = (Sint16)state->block.data[o + 2]; cstate[c] = (Sint8)(step > 0x80 ? step - 0x100 : step); /* Reserved byte in block header, should be 0. */ if (state->block.data[o + 3] != 0) { /* Uh oh, corrupt data? Buggy code? */ ; } } state->block.pos += state->blockheadersize; /* Header provided one sample frame. */ state->framesleft--; return 0; } /* Decodes the data of the IMA ADPCM block. Decoding will stop if a block is too * short, returning with none or partially decoded data. The partial data always * contains full sample frames (same sample count for each channel). * Incomplete sample frames are discarded. */ static int IMA_ADPCM_DecodeBlockData(ADPCM_DecoderState *state) { size_t i; int retval = 0; const Uint32 channels = state->channels; const size_t subblockframesize = channels * 4; Uint64 bytesrequired; Uint32 c; size_t blockpos = state->block.pos; size_t blocksize = state->block.size; size_t blockleft = blocksize - blockpos; size_t outpos = state->output.pos; Sint64 blockframesleft = state->samplesperblock - 1; if (blockframesleft > state->framesleft) { blockframesleft = state->framesleft; } bytesrequired = (blockframesleft + 7) / 8 * subblockframesize; if (blockleft < bytesrequired) { /* Data truncated. Calculate how many samples we can get out if it. */ const size_t guaranteedframes = blockleft / subblockframesize; const size_t remainingbytes = blockleft % subblockframesize; blockframesleft = guaranteedframes; if (remainingbytes > subblockframesize - 4) { blockframesleft += (remainingbytes % 4) * 2; } /* Signal the truncation. */ retval = -1; } /* Each channel has their nibbles packed into 32-bit blocks. These blocks * are interleaved and make up the data part of the ADPCM block. This loop * decodes the samples as they come from the input data and puts them at * the appropriate places in the output data. */ while (blockframesleft > 0) { const size_t subblocksamples = blockframesleft < 8 ? (size_t)blockframesleft : 8; for (c = 0; c < channels; c++) { Uint8 nybble = 0; /* Load previous sample which may come from the block header. */ Sint16 sample = state->output.data[outpos + c - channels]; for (i = 0; i < subblocksamples; i++) { if (i & 1) { nybble >>= 4; } else { nybble = state->block.data[blockpos++]; } sample = IMA_ADPCM_ProcessNibble((Sint8 *)state->cstate + c, sample, nybble & 0x0f); state->output.data[outpos + c + i * channels] = sample; } } outpos += channels * subblocksamples; state->framesleft -= subblocksamples; blockframesleft -= subblocksamples; } state->block.pos = blockpos; state->output.pos = outpos; return retval; } static int IMA_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len) { int result; size_t bytesleft, outputsize; WaveChunk *chunk = &file->chunk; ADPCM_DecoderState state; Sint8 *cstate; if (chunk->size != chunk->length) { /* Could not read everything. Recalculate number of sample frames. */ if (IMA_ADPCM_CalculateSampleFrames(file, chunk->size) < 0) { return -1; } } /* Nothing to decode, nothing to return. */ if (file->sampleframes == 0) { *audio_buf = NULL; *audio_len = 0; return 0; } SDL_zero(state); state.channels = file->format.channels; state.blocksize = file->format.blockalign; state.blockheadersize = (size_t)state.channels * 4; state.samplesperblock = file->format.samplesperblock; state.framesize = state.channels * sizeof(Sint16); state.framestotal = file->sampleframes; state.framesleft = state.framestotal; state.input.data = chunk->data; state.input.size = chunk->size; state.input.pos = 0; /* The output size in bytes. May get modified if data is truncated. */ outputsize = (size_t)state.framestotal; if (SafeMult(&outputsize, state.framesize)) { return SDL_OutOfMemory(); } else if (outputsize > SDL_MAX_UINT32 || state.framestotal > SIZE_MAX) { return SDL_SetError("WAVE file too big"); } state.output.pos = 0; state.output.size = outputsize / sizeof(Sint16); state.output.data = (Sint16 *)SDL_malloc(outputsize); if (state.output.data == NULL) { return SDL_OutOfMemory(); } cstate = (Sint8 *)SDL_calloc(state.channels, sizeof(Sint8)); if (cstate == NULL) { SDL_free(state.output.data); return SDL_OutOfMemory(); } state.cstate = cstate; /* Decode block by block. A truncated block will stop the decoding. */ bytesleft = state.input.size - state.input.pos; while (state.framesleft > 0 && bytesleft >= state.blockheadersize) { state.block.data = state.input.data + state.input.pos; state.block.size = bytesleft < state.blocksize ? bytesleft : state.blocksize; state.block.pos = 0; if (state.output.size - state.output.pos < (Uint64)state.framesleft * state.channels) { /* Somehow didn't allocate enough space for the output. */ SDL_free(state.output.data); SDL_free(cstate); return SDL_SetError("Unexpected overflow in IMA ADPCM decoder"); } /* Initialize decoder with the values from the block header. */ result = IMA_ADPCM_DecodeBlockHeader(&state); if (result == 0) { /* Decode the block data. It stores the samples directly in the output. */ result = IMA_ADPCM_DecodeBlockData(&state); } if (result == -1) { /* Unexpected end. Stop decoding and return partial data if necessary. */ if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) { SDL_free(state.output.data); SDL_free(cstate); return SDL_SetError("Truncated data chunk"); } else if (file->trunchint != TruncDropFrame) { state.output.pos -= state.output.pos % (state.samplesperblock * state.channels); } outputsize = state.output.pos * sizeof(Sint16); /* Can't overflow, is always smaller. */ break; } state.input.pos += state.block.size; bytesleft = state.input.size - state.input.pos; } *audio_buf = (Uint8 *)state.output.data; *audio_len = (Uint32)outputsize; SDL_free(cstate); return 0; } static int LAW_Init(WaveFile *file, size_t datalength) { WaveFormat *format = &file->format; /* Standards Update requires this to be 8. */ if (format->bitspersample != 8) { return SDL_SetError("Invalid companded bits per sample of %u", (unsigned int)format->bitspersample); } /* Not going to bother with weird padding. */ if (format->blockalign != format->channels) { return SDL_SetError("Unsupported block alignment"); } if ((file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict)) { if (format->blockalign > 1 && datalength % format->blockalign) { return SDL_SetError("Truncated data chunk in WAVE file"); } } file->sampleframes = WaveAdjustToFactValue(file, datalength / format->blockalign); if (file->sampleframes < 0) { return -1; } return 0; } static int LAW_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len) { #ifdef SDL_WAVE_LAW_LUT const Sint16 alaw_lut[256] = { -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784, -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368, -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392, -22016, -20992, -24064, -23040, -17920, -16896, -19968, -18944, -30208, -29184, -32256, -31232, -26112, -25088, -28160, -27136, -11008, -10496, -12032, -11520, -8960, -8448, -9984, -9472, -15104, -14592, -16128, -15616, -13056, -12544, -14080, -13568, -344, -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408, -392, -440, -424, -88, -72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136, -184, -168, -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, -688, -656, -752, -720, -560, -528, -624, -592, -944, -912, -1008, -976, -816, -784, -880, -848, 5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736, 7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784, 2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392, 22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944, 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136, 11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568, 344, 328, 376, 360, 280, 264, 312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88, 72, 120, 104, 24, 8, 56, 40, 216, 200, 248, 232, 152, 136, 184, 168, 1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696, 688, 656, 752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816, 784, 880, 848 }; const Sint16 mulaw_lut[256] = { -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956, -23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764, -15996, -15484, -14972, -14460, -13948, -13436, -12924, -12412, -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316, -7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140, -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, -3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004, -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, -1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436, -1372, -1308, -1244, -1180, -1116, -1052, -988, -924, -876, -844, -812, -780, -748, -716, -684, -652, -620, -588, -556, -524, -492, -460, -428, -396, -372, -356, -340, -324, -308, -292, -276, -260, -244, -228, -212, -196, -180, -164, -148, -132, -120, -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, -8, 0, 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, 7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140, 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, 3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004, 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, 1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436, 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, 876, 844, 812, 780, 748, 716, 684, 652, 620, 588, 556, 524, 492, 460, 428, 396, 372, 356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0 }; #endif WaveFormat *format = &file->format; WaveChunk *chunk = &file->chunk; size_t i, sample_count, expanded_len; Uint8 *src; Sint16 *dst; if (chunk->length != chunk->size) { file->sampleframes = WaveAdjustToFactValue(file, chunk->size / format->blockalign); if (file->sampleframes < 0) { return -1; } } /* Nothing to decode, nothing to return. */ if (file->sampleframes == 0) { *audio_buf = NULL; *audio_len = 0; return 0; } sample_count = (size_t)file->sampleframes; if (SafeMult(&sample_count, format->channels)) { return SDL_OutOfMemory(); } expanded_len = sample_count; if (SafeMult(&expanded_len, sizeof(Sint16))) { return SDL_OutOfMemory(); } else if (expanded_len > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) { return SDL_SetError("WAVE file too big"); } /* 1 to avoid allocating zero bytes, to keep static analysis happy. */ src = (Uint8 *)SDL_realloc(chunk->data, expanded_len ? expanded_len : 1); if (src == NULL) { return SDL_OutOfMemory(); } chunk->data = NULL; chunk->size = 0; dst = (Sint16 *)src; /* Work backwards, since we're expanding in-place. SDL_AudioSpec.format will * inform the caller about the byte order. */ i = sample_count; switch (file->format.encoding) { #ifdef SDL_WAVE_LAW_LUT case ALAW_CODE: while (i--) { dst[i] = alaw_lut[src[i]]; } break; case MULAW_CODE: while (i--) { dst[i] = mulaw_lut[src[i]]; } break; #else case ALAW_CODE: while (i--) { Uint8 nibble = src[i]; Uint8 exponent = (nibble & 0x7f) ^ 0x55; Sint16 mantissa = exponent & 0xf; exponent >>= 4; if (exponent > 0) { mantissa |= 0x10; } mantissa = (mantissa << 4) | 0x8; if (exponent > 1) { mantissa <<= exponent - 1; } dst[i] = nibble & 0x80 ? mantissa : -mantissa; } break; case MULAW_CODE: while (i--) { Uint8 nibble = ~src[i]; Sint16 mantissa = nibble & 0xf; Uint8 exponent = (nibble >> 4) & 0x7; Sint16 step = 4 << (exponent + 1); mantissa = (0x80 << exponent) + step * mantissa + step / 2 - 132; dst[i] = nibble & 0x80 ? -mantissa : mantissa; } break; #endif default: SDL_free(src); return SDL_SetError("Unknown companded encoding"); } *audio_buf = src; *audio_len = (Uint32)expanded_len; return 0; } static int PCM_Init(WaveFile *file, size_t datalength) { WaveFormat *format = &file->format; if (format->encoding == PCM_CODE) { switch (format->bitspersample) { case 8: case 16: case 24: case 32: /* These are supported. */ break; default: return SDL_SetError("%u-bit PCM format not supported", (unsigned int)format->bitspersample); } } else if (format->encoding == IEEE_FLOAT_CODE) { if (format->bitspersample != 32) { return SDL_SetError("%u-bit IEEE floating-point format not supported", (unsigned int)format->bitspersample); } } /* It wouldn't be that hard to support more exotic block sizes, but * the most common formats should do for now. */ if (format->blockalign * 8 != format->channels * format->bitspersample) { return SDL_SetError("Unsupported block alignment"); } if ((file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict)) { if (format->blockalign > 1 && datalength % format->blockalign) { return SDL_SetError("Truncated data chunk in WAVE file"); } } file->sampleframes = WaveAdjustToFactValue(file, datalength / format->blockalign); if (file->sampleframes < 0) { return -1; } return 0; } static int PCM_ConvertSint24ToSint32(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len) { WaveFormat *format = &file->format; WaveChunk *chunk = &file->chunk; size_t i, expanded_len, sample_count; Uint8 *ptr; sample_count = (size_t)file->sampleframes; if (SafeMult(&sample_count, format->channels)) { return SDL_OutOfMemory(); } expanded_len = sample_count; if (SafeMult(&expanded_len, sizeof(Sint32))) { return SDL_OutOfMemory(); } else if (expanded_len > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) { return SDL_SetError("WAVE file too big"); } /* 1 to avoid allocating zero bytes, to keep static analysis happy. */ ptr = (Uint8 *)SDL_realloc(chunk->data, expanded_len ? expanded_len : 1); if (ptr == NULL) { return SDL_OutOfMemory(); } /* This pointer is now invalid. */ chunk->data = NULL; chunk->size = 0; *audio_buf = ptr; *audio_len = (Uint32)expanded_len; /* work from end to start, since we're expanding in-place. */ for (i = sample_count; i > 0; i--) { const size_t o = i - 1; uint8_t b[4]; b[0] = 0; b[1] = ptr[o * 3]; b[2] = ptr[o * 3 + 1]; b[3] = ptr[o * 3 + 2]; ptr[o * 4 + 0] = b[0]; ptr[o * 4 + 1] = b[1]; ptr[o * 4 + 2] = b[2]; ptr[o * 4 + 3] = b[3]; } return 0; } static int PCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len) { WaveFormat *format = &file->format; WaveChunk *chunk = &file->chunk; size_t outputsize; if (chunk->length != chunk->size) { file->sampleframes = WaveAdjustToFactValue(file, chunk->size / format->blockalign); if (file->sampleframes < 0) { return -1; } } /* Nothing to decode, nothing to return. */ if (file->sampleframes == 0) { *audio_buf = NULL; *audio_len = 0; return 0; } /* 24-bit samples get shifted to 32 bits. */ if (format->encoding == PCM_CODE && format->bitspersample == 24) { return PCM_ConvertSint24ToSint32(file, audio_buf, audio_len); } outputsize = (size_t)file->sampleframes; if (SafeMult(&outputsize, format->blockalign)) { return SDL_OutOfMemory(); } else if (outputsize > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) { return SDL_SetError("WAVE file too big"); } *audio_buf = chunk->data; *audio_len = (Uint32)outputsize; /* This pointer is going to be returned to the caller. Prevent free in cleanup. */ chunk->data = NULL; chunk->size = 0; return 0; } static WaveRiffSizeHint WaveGetRiffSizeHint() { const char *hint = SDL_GetHint(SDL_HINT_WAVE_RIFF_CHUNK_SIZE); if (hint != NULL) { if (SDL_strcmp(hint, "force") == 0) { return RiffSizeForce; } else if (SDL_strcmp(hint, "ignore") == 0) { return RiffSizeIgnore; } else if (SDL_strcmp(hint, "ignorezero") == 0) { return RiffSizeIgnoreZero; } else if (SDL_strcmp(hint, "maximum") == 0) { return RiffSizeMaximum; } } return RiffSizeNoHint; } static WaveTruncationHint WaveGetTruncationHint() { const char *hint = SDL_GetHint(SDL_HINT_WAVE_TRUNCATION); if (hint != NULL) { if (SDL_strcmp(hint, "verystrict") == 0) { return TruncVeryStrict; } else if (SDL_strcmp(hint, "strict") == 0) { return TruncStrict; } else if (SDL_strcmp(hint, "dropframe") == 0) { return TruncDropFrame; } else if (SDL_strcmp(hint, "dropblock") == 0) { return TruncDropBlock; } } return TruncNoHint; } static WaveFactChunkHint WaveGetFactChunkHint() { const char *hint = SDL_GetHint(SDL_HINT_WAVE_FACT_CHUNK); if (hint != NULL) { if (SDL_strcmp(hint, "truncate") == 0) { return FactTruncate; } else if (SDL_strcmp(hint, "strict") == 0) { return FactStrict; } else if (SDL_strcmp(hint, "ignorezero") == 0) { return FactIgnoreZero; } else if (SDL_strcmp(hint, "ignore") == 0) { return FactIgnore; } } return FactNoHint; } static void WaveFreeChunkData(WaveChunk *chunk) { if (chunk->data != NULL) { SDL_free(chunk->data); chunk->data = NULL; } chunk->size = 0; } static int WaveNextChunk(SDL_RWops *src, WaveChunk *chunk) { Uint32 chunkheader[2]; Sint64 nextposition = chunk->position + chunk->length; /* Data is no longer valid after this function returns. */ WaveFreeChunkData(chunk); /* Error on overflows. */ if (SDL_MAX_SINT64 - chunk->length < chunk->position || SDL_MAX_SINT64 - 8 < nextposition) { return -1; } /* RIFF chunks have a 2-byte alignment. Skip padding byte. */ if (chunk->length & 1) { nextposition++; } if (SDL_RWseek(src, nextposition, RW_SEEK_SET) != nextposition) { /* Not sure how we ended up here. Just abort. */ return -2; } else if (SDL_RWread(src, chunkheader, 4, 2) != 2) { return -1; } chunk->fourcc = SDL_SwapLE32(chunkheader[0]); chunk->length = SDL_SwapLE32(chunkheader[1]); chunk->position = nextposition + 8; return 0; } static int WaveReadPartialChunkData(SDL_RWops *src, WaveChunk *chunk, size_t length) { WaveFreeChunkData(chunk); if (length > chunk->length) { length = chunk->length; } if (length > 0) { chunk->data = SDL_malloc(length); if (chunk->data == NULL) { return SDL_OutOfMemory(); } if (SDL_RWseek(src, chunk->position, RW_SEEK_SET) != chunk->position) { /* Not sure how we ended up here. Just abort. */ return -2; } chunk->size = SDL_RWread(src, chunk->data, 1, length); if (chunk->size != length) { /* Expected to be handled by the caller. */ } } return 0; } static int WaveReadChunkData(SDL_RWops *src, WaveChunk *chunk) { return WaveReadPartialChunkData(src, chunk, chunk->length); } typedef struct WaveExtensibleGUID { Uint16 encoding; Uint8 guid[16]; } WaveExtensibleGUID; /* Some of the GUIDs that are used by WAVEFORMATEXTENSIBLE. */ #define WAVE_FORMATTAG_GUID(tag) {(tag) & 0xff, (tag) >> 8, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113} static WaveExtensibleGUID extensible_guids[] = { {PCM_CODE, WAVE_FORMATTAG_GUID(PCM_CODE)}, {MS_ADPCM_CODE, WAVE_FORMATTAG_GUID(MS_ADPCM_CODE)}, {IEEE_FLOAT_CODE, WAVE_FORMATTAG_GUID(IEEE_FLOAT_CODE)}, {ALAW_CODE, WAVE_FORMATTAG_GUID(ALAW_CODE)}, {MULAW_CODE, WAVE_FORMATTAG_GUID(MULAW_CODE)}, {IMA_ADPCM_CODE, WAVE_FORMATTAG_GUID(IMA_ADPCM_CODE)} }; static Uint16 WaveGetFormatGUIDEncoding(WaveFormat *format) { size_t i; for (i = 0; i < SDL_arraysize(extensible_guids); i++) { if (SDL_memcmp(format->subformat, extensible_guids[i].guid, 16) == 0) { return extensible_guids[i].encoding; } } return UNKNOWN_CODE; } static int WaveReadFormat(WaveFile *file) { WaveChunk *chunk = &file->chunk; WaveFormat *format = &file->format; SDL_RWops *fmtsrc; size_t fmtlen = chunk->size; if (fmtlen > SDL_MAX_SINT32) { /* Limit given by SDL_RWFromConstMem. */ return SDL_SetError("Data of WAVE fmt chunk too big"); } fmtsrc = SDL_RWFromConstMem(chunk->data, (int)chunk->size); if (fmtsrc == NULL) { return SDL_OutOfMemory(); } format->formattag = SDL_ReadLE16(fmtsrc); format->encoding = format->formattag; format->channels = SDL_ReadLE16(fmtsrc); format->frequency = SDL_ReadLE32(fmtsrc); format->byterate = SDL_ReadLE32(fmtsrc); format->blockalign = SDL_ReadLE16(fmtsrc); /* This is PCM specific in the first version of the specification. */ if (fmtlen >= 16) { format->bitspersample = SDL_ReadLE16(fmtsrc); } else if (format->encoding == PCM_CODE) { SDL_RWclose(fmtsrc); return SDL_SetError("Missing wBitsPerSample field in WAVE fmt chunk"); } /* The earlier versions also don't have this field. */ if (fmtlen >= 18) { format->extsize = SDL_ReadLE16(fmtsrc); } if (format->formattag == EXTENSIBLE_CODE) { /* note that this ignores channel masks, smaller valid bit counts * inside a larger container, and most subtypes. This is just enough * to get things that didn't really _need_ WAVE_FORMAT_EXTENSIBLE * to be useful working when they use this format flag. */ /* Extensible header must be at least 22 bytes. */ if (fmtlen < 40 || format->extsize < 22) { SDL_RWclose(fmtsrc); return SDL_SetError("Extensible WAVE header too small"); } format->validsamplebits = SDL_ReadLE16(fmtsrc); format->samplesperblock = format->validsamplebits; format->channelmask = SDL_ReadLE32(fmtsrc); SDL_RWread(fmtsrc, format->subformat, 1, 16); format->encoding = WaveGetFormatGUIDEncoding(format); } SDL_RWclose(fmtsrc); return 0; } static int WaveCheckFormat(WaveFile *file, size_t datalength) { WaveFormat *format = &file->format; /* Check for some obvious issues. */ if (format->channels == 0) { return SDL_SetError("Invalid number of channels"); } else if (format->channels > 255) { /* Limit given by SDL_AudioSpec.channels. */ return SDL_SetError("Number of channels exceeds limit of 255"); } if (format->frequency == 0) { return SDL_SetError("Invalid sample rate"); } else if (format->frequency > INT_MAX) { /* Limit given by SDL_AudioSpec.freq. */ return SDL_SetError("Sample rate exceeds limit of %d", INT_MAX); } /* Reject invalid fact chunks in strict mode. */ if (file->facthint == FactStrict && file->fact.status == -1) { return SDL_SetError("Invalid fact chunk in WAVE file"); } /* Check for issues common to all encodings. Some unsupported formats set * the bits per sample to zero. These fall through to the 'unsupported * format' error. */ switch (format->encoding) { case IEEE_FLOAT_CODE: case ALAW_CODE: case MULAW_CODE: case MS_ADPCM_CODE: case IMA_ADPCM_CODE: /* These formats require a fact chunk. */ if (file->facthint == FactStrict && file->fact.status <= 0) { return SDL_SetError("Missing fact chunk in WAVE file"); } /* fallthrough */ case PCM_CODE: /* All supported formats require a non-zero bit depth. */ if (file->chunk.size < 16) { return SDL_SetError("Missing wBitsPerSample field in WAVE fmt chunk"); } else if (format->bitspersample == 0) { return SDL_SetError("Invalid bits per sample"); } /* All supported formats must have a proper block size. */ if (format->blockalign == 0) { return SDL_SetError("Invalid block alignment"); } /* If the fact chunk is valid and the appropriate hint is set, the * decoders will use the number of sample frames from the fact chunk. */ if (file->fact.status == 1) { WaveFactChunkHint hint = file->facthint; Uint32 samples = file->fact.samplelength; if (hint == FactTruncate || hint == FactStrict || (hint == FactIgnoreZero && samples > 0)) { file->fact.status = 2; } } } /* Check the format for encoding specific issues and initialize decoders. */ switch (format->encoding) { case PCM_CODE: case IEEE_FLOAT_CODE: if (PCM_Init(file, datalength) < 0) { return -1; } break; case ALAW_CODE: case MULAW_CODE: if (LAW_Init(file, datalength) < 0) { return -1; } break; case MS_ADPCM_CODE: if (MS_ADPCM_Init(file, datalength) < 0) { return -1; } break; case IMA_ADPCM_CODE: if (IMA_ADPCM_Init(file, datalength) < 0) { return -1; } break; case MPEG_CODE: case MPEGLAYER3_CODE: return SDL_SetError("MPEG formats not supported"); default: if (format->formattag == EXTENSIBLE_CODE) { const char *errstr = "Unknown WAVE format GUID: %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x"; const Uint8 *g = format->subformat; const Uint32 g1 = g[0] | ((Uint32)g[1] << 8) | ((Uint32)g[2] << 16) | ((Uint32)g[3] << 24); const Uint32 g2 = g[4] | ((Uint32)g[5] << 8); const Uint32 g3 = g[6] | ((Uint32)g[7] << 8); return SDL_SetError(errstr, g1, g2, g3, g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]); } return SDL_SetError("Unknown WAVE format tag: 0x%04x", (unsigned int)format->encoding); } return 0; } static int WaveLoad(SDL_RWops *src, WaveFile *file, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len) { int result; Uint32 chunkcount = 0; Uint32 chunkcountlimit = 10000; char *envchunkcountlimit; Sint64 RIFFstart, RIFFend, lastchunkpos; SDL_bool RIFFlengthknown = SDL_FALSE; WaveFormat *format = &file->format; WaveChunk *chunk = &file->chunk; WaveChunk RIFFchunk; WaveChunk fmtchunk; WaveChunk datachunk; SDL_zero(RIFFchunk); SDL_zero(fmtchunk); SDL_zero(datachunk); envchunkcountlimit = SDL_getenv("SDL_WAVE_CHUNK_LIMIT"); if (envchunkcountlimit != NULL) { unsigned int count; if (SDL_sscanf(envchunkcountlimit, "%u", &count) == 1) { chunkcountlimit = count <= SDL_MAX_UINT32 ? count : SDL_MAX_UINT32; } } RIFFstart = SDL_RWtell(src); if (RIFFstart < 0) { return SDL_SetError("Could not seek in file"); } RIFFchunk.position = RIFFstart; if (WaveNextChunk(src, &RIFFchunk) < 0) { return SDL_SetError("Could not read RIFF header"); } /* Check main WAVE file identifiers. */ if (RIFFchunk.fourcc == RIFF) { Uint32 formtype; /* Read the form type. "WAVE" expected. */ if (SDL_RWread(src, &formtype, sizeof(Uint32), 1) != 1) { return SDL_SetError("Could not read RIFF form type"); } else if (SDL_SwapLE32(formtype) != WAVE) { return SDL_SetError("RIFF form type is not WAVE (not a Waveform file)"); } } else if (RIFFchunk.fourcc == WAVE) { /* RIFF chunk missing or skipped. Length unknown. */ RIFFchunk.position = 0; RIFFchunk.length = 0; } else { return SDL_SetError("Could not find RIFF or WAVE identifiers (not a Waveform file)"); } /* The 4-byte form type is immediately followed by the first chunk.*/ chunk->position = RIFFchunk.position + 4; /* Use the RIFF chunk size to limit the search for the chunks. This is not * always reliable and the hint can be used to tune the behavior. By * default, it will never search past 4 GiB. */ switch (file->riffhint) { case RiffSizeIgnore: RIFFend = RIFFchunk.position + SDL_MAX_UINT32; break; default: case RiffSizeIgnoreZero: if (RIFFchunk.length == 0) { RIFFend = RIFFchunk.position + SDL_MAX_UINT32; break; } /* fallthrough */ case RiffSizeForce: RIFFend = RIFFchunk.position + RIFFchunk.length; RIFFlengthknown = SDL_TRUE; break; case RiffSizeMaximum: RIFFend = SDL_MAX_SINT64; break; } /* Step through all chunks and save information on the fmt, data, and fact * chunks. Ignore the chunks we don't know as per specification. This * currently also ignores cue, list, and slnt chunks. */ while ((Uint64)RIFFend > (Uint64)chunk->position + chunk->length + (chunk->length & 1)) { /* Abort after too many chunks or else corrupt files may waste time. */ if (chunkcount++ >= chunkcountlimit) { return SDL_SetError("Chunk count in WAVE file exceeds limit of %u", chunkcountlimit); } result = WaveNextChunk(src, chunk); if (result == -1) { /* Unexpected EOF. Corrupt file or I/O issues. */ if (file->trunchint == TruncVeryStrict) { return SDL_SetError("Unexpected end of WAVE file"); } /* Let the checks after this loop sort this issue out. */ break; } else if (result == -2) { return SDL_SetError("Could not seek to WAVE chunk header"); } if (chunk->fourcc == FMT) { if (fmtchunk.fourcc == FMT) { /* Multiple fmt chunks. Ignore or error? */ } else { /* The fmt chunk must occur before the data chunk. */ if (datachunk.fourcc == DATA) { return SDL_SetError("fmt chunk after data chunk in WAVE file"); } fmtchunk = *chunk; } } else if (chunk->fourcc == DATA) { /* Only use the first data chunk. Handling the wavl list madness * may require a different approach. */ if (datachunk.fourcc != DATA) { datachunk = *chunk; } } else if (chunk->fourcc == FACT) { /* The fact chunk data must be at least 4 bytes for the * dwSampleLength field. Ignore all fact chunks after the first one. */ if (file->fact.status == 0) { if (chunk->length < 4) { file->fact.status = -1; } else { /* Let's use src directly, it's just too convenient. */ Sint64 position = SDL_RWseek(src, chunk->position, RW_SEEK_SET); Uint32 samplelength; if (position == chunk->position && SDL_RWread(src, &samplelength, sizeof(Uint32), 1) == 1) { file->fact.status = 1; file->fact.samplelength = SDL_SwapLE32(samplelength); } else { file->fact.status = -1; } } } } /* Go through all chunks in verystrict mode or stop the search early if * all required chunks were found. */ if (file->trunchint == TruncVeryStrict) { if ((Uint64)RIFFend < (Uint64)chunk->position + chunk->length) { return SDL_SetError("RIFF size truncates chunk"); } } else if (fmtchunk.fourcc == FMT && datachunk.fourcc == DATA) { if (file->fact.status == 1 || file->facthint == FactIgnore || file->facthint == FactNoHint) { break; } } } /* Save the position after the last chunk. This position will be used if the * RIFF length is unknown. */ lastchunkpos = chunk->position + chunk->length; /* The fmt chunk is mandatory. */ if (fmtchunk.fourcc != FMT) { return SDL_SetError("Missing fmt chunk in WAVE file"); } /* A data chunk must be present. */ if (datachunk.fourcc != DATA) { return SDL_SetError("Missing data chunk in WAVE file"); } /* Check if the last chunk has all of its data in verystrict mode. */ if (file->trunchint == TruncVeryStrict) { /* data chunk is handled later. */ if (chunk->fourcc != DATA && chunk->length > 0) { Uint8 tmp; Uint64 position = (Uint64)chunk->position + chunk->length - 1; if (position > SDL_MAX_SINT64 || SDL_RWseek(src, (Sint64)position, RW_SEEK_SET) != (Sint64)position) { return SDL_SetError("Could not seek to WAVE chunk data"); } else if (SDL_RWread(src, &tmp, 1, 1) != 1) { return SDL_SetError("RIFF size truncates chunk"); } } } /* Process fmt chunk. */ *chunk = fmtchunk; /* No need to read more than 1046 bytes of the fmt chunk data with the * formats that are currently supported. (1046 because of MS ADPCM coefficients) */ if (WaveReadPartialChunkData(src, chunk, 1046) < 0) { return SDL_SetError("Could not read data of WAVE fmt chunk"); } /* The fmt chunk data must be at least 14 bytes to include all common fields. * It usually is 16 and larger depending on the header and encoding. */ if (chunk->length < 14) { return SDL_SetError("Invalid WAVE fmt chunk length (too small)"); } else if (chunk->size < 14) { return SDL_SetError("Could not read data of WAVE fmt chunk"); } else if (WaveReadFormat(file) < 0) { return -1; } else if (WaveCheckFormat(file, (size_t)datachunk.length) < 0) { return -1; } #ifdef SDL_WAVE_DEBUG_LOG_FORMAT WaveDebugLogFormat(file); #endif #ifdef SDL_WAVE_DEBUG_DUMP_FORMAT WaveDebugDumpFormat(file, RIFFchunk.length, fmtchunk.length, datachunk.length); #endif WaveFreeChunkData(chunk); /* Process data chunk. */ *chunk = datachunk; if (chunk->length > 0) { result = WaveReadChunkData(src, chunk); if (result == -1) { return -1; } else if (result == -2) { return SDL_SetError("Could not seek data of WAVE data chunk"); } } if (chunk->length != chunk->size) { /* I/O issues or corrupt file. */ if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) { return SDL_SetError("Could not read data of WAVE data chunk"); } /* The decoders handle this truncation. */ } /* Decode or convert the data if necessary. */ switch (format->encoding) { case PCM_CODE: case IEEE_FLOAT_CODE: if (PCM_Decode(file, audio_buf, audio_len) < 0) { return -1; } break; case ALAW_CODE: case MULAW_CODE: if (LAW_Decode(file, audio_buf, audio_len) < 0) { return -1; } break; case MS_ADPCM_CODE: if (MS_ADPCM_Decode(file, audio_buf, audio_len) < 0) { return -1; } break; case IMA_ADPCM_CODE: if (IMA_ADPCM_Decode(file, audio_buf, audio_len) < 0) { return -1; } break; } /* Setting up the SDL_AudioSpec. All unsupported formats were filtered out * by checks earlier in this function. */ SDL_zerop(spec); spec->freq = format->frequency; spec->channels = (Uint8)format->channels; spec->samples = 4096; /* Good default buffer size */ switch (format->encoding) { case MS_ADPCM_CODE: case IMA_ADPCM_CODE: case ALAW_CODE: case MULAW_CODE: /* These can be easily stored in the byte order of the system. */ spec->format = AUDIO_S16SYS; break; case IEEE_FLOAT_CODE: spec->format = AUDIO_F32LSB; break; case PCM_CODE: switch (format->bitspersample) { case 8: spec->format = AUDIO_U8; break; case 16: spec->format = AUDIO_S16LSB; break; case 24: /* Has been shifted to 32 bits. */ case 32: spec->format = AUDIO_S32LSB; break; default: /* Just in case something unexpected happened in the checks. */ return SDL_SetError("Unexpected %u-bit PCM data format", (unsigned int)format->bitspersample); } break; } spec->silence = SDL_SilenceValueForFormat(spec->format); /* Report the end position back to the cleanup code. */ if (RIFFlengthknown) { chunk->position = RIFFend; } else { chunk->position = lastchunkpos; } return 0; } SDL_AudioSpec * SDL_LoadWAV_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len) { int result; WaveFile file; SDL_zero(file); /* Make sure we are passed a valid data source */ if (src == NULL) { /* Error may come from RWops. */ return NULL; } else if (spec == NULL) { SDL_InvalidParamError("spec"); return NULL; } else if (audio_buf == NULL) { SDL_InvalidParamError("audio_buf"); return NULL; } else if (audio_len == NULL) { SDL_InvalidParamError("audio_len"); return NULL; } *audio_buf = NULL; *audio_len = 0; file.riffhint = WaveGetRiffSizeHint(); file.trunchint = WaveGetTruncationHint(); file.facthint = WaveGetFactChunkHint(); result = WaveLoad(src, &file, spec, audio_buf, audio_len); if (result < 0) { SDL_free(*audio_buf); spec = NULL; audio_buf = NULL; audio_len = 0; } /* Cleanup */ if (freesrc) { SDL_RWclose(src); } else { SDL_RWseek(src, file.chunk.position, RW_SEEK_SET); } WaveFreeChunkData(&file.chunk); SDL_free(file.decoderdata); return spec; } /* Since the WAV memory is allocated in the shared library, it must also be freed here. (Necessary under Win32, VC++) */ void SDL_FreeWAV(Uint8 *audio_buf) { SDL_free(audio_buf); } /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/SDL_wave.c
C
apache-2.0
75,718
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" /* RIFF WAVE files are little-endian */ /*******************************************/ /* Define values for Microsoft WAVE format */ /*******************************************/ /* FOURCC */ #define RIFF 0x46464952 /* "RIFF" */ #define WAVE 0x45564157 /* "WAVE" */ #define FACT 0x74636166 /* "fact" */ #define LIST 0x5453494c /* "LIST" */ #define BEXT 0x74786562 /* "bext" */ #define JUNK 0x4B4E554A /* "JUNK" */ #define FMT 0x20746D66 /* "fmt " */ #define DATA 0x61746164 /* "data" */ /* Format tags */ #define UNKNOWN_CODE 0x0000 #define PCM_CODE 0x0001 #define MS_ADPCM_CODE 0x0002 #define IEEE_FLOAT_CODE 0x0003 #define ALAW_CODE 0x0006 #define MULAW_CODE 0x0007 #define IMA_ADPCM_CODE 0x0011 #define MPEG_CODE 0x0050 #define MPEGLAYER3_CODE 0x0055 #define EXTENSIBLE_CODE 0xFFFE /* Stores the WAVE format information. */ typedef struct WaveFormat { Uint16 formattag; /* Raw value of the first field in the fmt chunk data. */ Uint16 encoding; /* Actual encoding, possibly from the extensible header. */ Uint16 channels; /* Number of channels. */ Uint32 frequency; /* Sampling rate in Hz. */ Uint32 byterate; /* Average bytes per second. */ Uint16 blockalign; /* Bytes per block. */ Uint16 bitspersample; /* Currently supported are 8, 16, 24, 32, and 4 for ADPCM. */ /* Extra information size. Number of extra bytes starting at byte 18 in the * fmt chunk data. This is at least 22 for the extensible header. */ Uint16 extsize; /* Extensible WAVE header fields */ Uint16 validsamplebits; Uint32 samplesperblock; /* For compressed formats. Can be zero. Actually 16 bits in the header. */ Uint32 channelmask; Uint8 subformat[16]; /* A format GUID. */ } WaveFormat; /* Stores information on the fact chunk. */ typedef struct WaveFact { /* Represents the state of the fact chunk in the WAVE file. * Set to -1 if the fact chunk is invalid. * Set to 0 if the fact chunk is not present * Set to 1 if the fact chunk is present and valid. * Set to 2 if samplelength is going to be used as the number of sample frames. */ Sint32 status; /* Version 1 of the RIFF specification calls the field in the fact chunk * dwFileSize. The Standards Update then calls it dwSampleLength and specifies * that it is 'the length of the data in samples'. WAVE files from Windows * with this chunk have it set to the samples per channel (sample frames). * This is useful to truncate compressed audio to a specific sample count * because a compressed block is usually decoded to a fixed number of * sample frames. */ Uint32 samplelength; /* Raw sample length value from the fact chunk. */ } WaveFact; /* Generic struct for the chunks in the WAVE file. */ typedef struct WaveChunk { Uint32 fourcc; /* FOURCC of the chunk. */ Uint32 length; /* Size of the chunk data. */ Sint64 position; /* Position of the data in the stream. */ Uint8 *data; /* When allocated, this points to the chunk data. length is used for the malloc size. */ size_t size; /* Number of bytes in data that could be read from the stream. Can be smaller than length. */ } WaveChunk; /* Controls how the size of the RIFF chunk affects the loading of a WAVE file. */ typedef enum WaveRiffSizeHint { RiffSizeNoHint, RiffSizeForce, RiffSizeIgnoreZero, RiffSizeIgnore, RiffSizeMaximum } WaveRiffSizeHint; /* Controls how a truncated WAVE file is handled. */ typedef enum WaveTruncationHint { TruncNoHint, TruncVeryStrict, TruncStrict, TruncDropFrame, TruncDropBlock } WaveTruncationHint; /* Controls how the fact chunk affects the loading of a WAVE file. */ typedef enum WaveFactChunkHint { FactNoHint, FactTruncate, FactStrict, FactIgnoreZero, FactIgnore } WaveFactChunkHint; typedef struct WaveFile { WaveChunk chunk; WaveFormat format; WaveFact fact; /* Number of sample frames that will be decoded. Calculated either with the * size of the data chunk or, if the appropriate hint is enabled, with the * sample length value from the fact chunk. */ Sint64 sampleframes; void *decoderdata; /* Some decoders require extra data for a state. */ WaveRiffSizeHint riffhint; WaveTruncationHint trunchint; WaveFactChunkHint facthint; } WaveFile; /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/SDL_wave.h
C
apache-2.0
5,582
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_ALIOS #include <stdio.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #include "SDL_audio.h" #include "SDL_error.h" #include "SDL_timer.h" #include "../SDL_audio_c.h" #include "../SDL_audiodev_c.h" #include "../SDL_sysaudio.h" #include "SDL_alios_audio.h" #include "ulog/ulog.h" #define LOG_TAG "[SDL_alios]" #define ALIOS_AUDIO_DRIVER_NAME "alios_sound" static SDL_atomic_t ALSA_hotplug_shutdown; static SDL_Thread *ALSA_hotplug_thread; static int fBusyFlag = 0; hint_list_t node; static int SDLCALL ALSA_HotplugThread(void *arg) { int ret = -1; SDL_sem *first_run_semaphore = (SDL_sem *) arg; hint_list_t *hints = NULL; Uint32 ticks; SDL_SetThreadPriority(SDL_THREAD_PRIORITY_LOW); while (!SDL_AtomicGet(&ALSA_hotplug_shutdown)) { if(!hints) { LOGD(LOG_TAG, "%s:%d, search sound card ...", __func__, __LINE__); //ret = snd_device_name_hint(-1, "pcm", node); if(1) { hints = (hint_list_t *)&node; strncpy(hints->name, "/dev/pcmC0D0p", sizeof(hints->name)); if(hints) { LOGD(LOG_TAG, "%s:%d, SDL_AddAudioDevice %s", __func__, __LINE__, hints->name); SDL_AddAudioDevice(0, hints->name, (void *)hints); SDL_SemPost(first_run_semaphore); } } } /* Block awhile before checking again, unless we're told to stop. */ ticks = SDL_GetTicks() + 5000; while (!SDL_AtomicGet(&ALSA_hotplug_shutdown) && !SDL_TICKS_PASSED(SDL_GetTicks(), ticks)) { SDL_Delay(1000); } } return 0; } static void AOS_DetectDevices(void) { /* Start the device detection thread here, wait for an initial iteration to complete. */ SDL_sem *semaphore = SDL_CreateSemaphore(0); if (!semaphore) { return; /* oh well. */ } SDL_AtomicSet(&ALSA_hotplug_shutdown, 0); ALSA_hotplug_thread = SDL_CreateThread(ALSA_HotplugThread, "SDLHotplugALSA", semaphore); if (ALSA_hotplug_thread) { SDL_SemWait(semaphore); /* wait for the first iteration to finish. */ } SDL_DestroySemaphore(semaphore); } static int AOS_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { int status = 0; snd_pcm_t *pcm_handle = NULL; snd_pcm_hw_params_t *hwparams = NULL; snd_pcm_sw_params_t *swparams = NULL; snd_pcm_format_t format = SNDRV_PCM_FORMAT_ALL; SDL_AudioFormat test_format = 0; unsigned int rate = 0; unsigned int channels = 0; this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc(sizeof(*this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); status = snd_pcm_open(&pcm_handle, "hw", iscapture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); if (status < 0) { LOGE(LOG_TAG, "%s:%d, ALSA: Couldn't open audio device", __func__, __LINE__); return -1; } this->hidden->pcm_handle = pcm_handle; /* Try for a closest match on audio format */ status = -1; for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format && (status < 0);) { status = 0; /* if we can't support a format, it'll become -1. */ switch (test_format) { case AUDIO_S8: format = SNDRV_PCM_FORMAT_S8; break; case AUDIO_S16LSB: format = SNDRV_PCM_FORMAT_S16_LE; break; case AUDIO_S32LSB: format = SNDRV_PCM_FORMAT_S32_LE; break; default: status = -1; break; } if (status < 0) { test_format = SDL_NextAudioFormat(); } } if (status < 0) { LOGE(LOG_TAG, "%s:%d, status %d", __func__, __LINE__, status); return -1; } this->spec.format = test_format; /* Set the number of channels */ channels = this->spec.channels; /* Set the audio rate */ rate = this->spec.freq; /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&this->spec); /* Allocate mixing buffer */ if (!iscapture) { this->hidden->mixlen = this->spec.size; this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->mixbuf, this->spec.silence, this->hidden->mixlen); } snd_pcm_set_params(this->hidden->pcm_handle, format, SNDRV_PCM_ACCESS_RW_NONINTERLEAVED, channels, rate, 0, 0); snd_pcm_prepare(this->hidden->pcm_handle); return 0; } /* This function waits until it is possible to write a full sound buffer */ static void AOS_WaitDevice(_THIS) { //LOGD(LOG_TAG, "%s:%d", __func__, __LINE__); } static Uint8 * AOS_GetDeviceBuf(_THIS) { //LOGD(LOG_TAG, "%s:%d", __func__, __LINE__); return (this->hidden->mixbuf); } static void ALSA_PlayDevice(_THIS) { const Uint8 *sample_buf = (const Uint8 *) this->hidden->mixbuf; const int frame_size = ((SDL_AUDIO_BITSIZE(this->spec.format)) / 8) * this->spec.channels; snd_pcm_uframes_t frames_left = ((snd_pcm_uframes_t) this->spec.samples); if(this->hidden->swizzle_func) this->hidden->swizzle_func(this, this->hidden->mixbuf, frames_left); if(0 == fBusyFlag) { fBusyFlag = 1; snd_pcm_start(this->hidden->pcm_handle); } while ( frames_left > 0 && SDL_AtomicGet(&this->enabled) ) { int status = snd_pcm_writei(this->hidden->pcm_handle, sample_buf, frames_left); if (status > 0) { sample_buf += status * frame_size; frames_left -= status; //Uint32 delay = (frames_left / 2 * 1000) / this->spec.freq; //SDL_Delay(delay); } } } static void AOS_Deinitialize(void) { if (ALSA_hotplug_thread != NULL) { SDL_AtomicSet(&ALSA_hotplug_shutdown, 1); SDL_WaitThread(ALSA_hotplug_thread, NULL); ALSA_hotplug_thread = NULL; } } static void AOS_CloseDevice(_THIS) { if (this->hidden->pcm_handle) { /* 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; SDL_Delay(delay); snd_pcm_drop(this->hidden->pcm_handle); snd_pcm_close(this->hidden->pcm_handle); } SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); fBusyFlag = 0; } static int AOSAUDIO_Init(SDL_AudioDriverImpl * impl) { /* Set the function pointers */ impl->DetectDevices = AOS_DetectDevices; impl->OpenDevice = AOS_OpenDevice; impl->WaitDevice = AOS_WaitDevice; impl->GetDeviceBuf = AOS_GetDeviceBuf; impl->PlayDevice = ALSA_PlayDevice; impl->CloseDevice = AOS_CloseDevice; impl->Deinitialize = AOS_Deinitialize; //impl->CaptureFromDevice = ALSA_CaptureFromDevice; //impl->FlushCapture = ALSA_FlushCapture; impl->HasCaptureSupport = SDL_FALSE; return 1; /* this audio target is available. */ } AudioBootStrap AOSAUDIO_bootstrap = { "aos", "AOS audio driver", AOSAUDIO_Init, 0 }; /* SDL_AUDI */ #endif /* SDL_AUDIO_DRIVER_PSP */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/alios/SDL_alios_audio.c
C
apache-2.0
8,488
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include "../../SDL_internal.h" #ifndef SDL_AOS_audio_h_ #define SDL_AOS_audio_h_ #include "sound_pcm.h" #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this #define NUM_BUFFERS 2 struct SDL_PrivateAudioData { /* The audio device handle */ snd_pcm_t *pcm_handle; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; /* swizzle function */ void (*swizzle_func)(_THIS, void *buffer, Uint32 bufferlen); }; #endif /* SDL_AOS_audio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/alios/SDL_alios_audio.h
C
apache-2.0
634
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #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> #include <signal.h> /* For kill() */ #include <string.h> #include "SDL_assert.h" #include "SDL_timer.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_alsa_audio.h" #ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC #include "SDL_loadso.h" #endif static int (*ALSA_snd_pcm_open) (snd_pcm_t **, const char *, snd_pcm_stream_t, int); static int (*ALSA_snd_pcm_close) (snd_pcm_t * pcm); static snd_pcm_sframes_t (*ALSA_snd_pcm_writei) (snd_pcm_t *, const void *, snd_pcm_uframes_t); static snd_pcm_sframes_t (*ALSA_snd_pcm_readi) (snd_pcm_t *, void *, snd_pcm_uframes_t); static int (*ALSA_snd_pcm_recover) (snd_pcm_t *, int, int); static int (*ALSA_snd_pcm_prepare) (snd_pcm_t *); static int (*ALSA_snd_pcm_drain) (snd_pcm_t *); static const char *(*ALSA_snd_strerror) (int); static size_t(*ALSA_snd_pcm_hw_params_sizeof) (void); static size_t(*ALSA_snd_pcm_sw_params_sizeof) (void); static void (*ALSA_snd_pcm_hw_params_copy) (snd_pcm_hw_params_t *, const snd_pcm_hw_params_t *); static int (*ALSA_snd_pcm_hw_params_any) (snd_pcm_t *, snd_pcm_hw_params_t *); static int (*ALSA_snd_pcm_hw_params_set_access) (snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_access_t); static int (*ALSA_snd_pcm_hw_params_set_format) (snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_format_t); static int (*ALSA_snd_pcm_hw_params_set_channels) (snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int); static int (*ALSA_snd_pcm_hw_params_get_channels) (const snd_pcm_hw_params_t *, unsigned int *); static int (*ALSA_snd_pcm_hw_params_set_rate_near) (snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *); static int (*ALSA_snd_pcm_hw_params_set_period_size_near) (snd_pcm_t *, snd_pcm_hw_params_t *, snd_pcm_uframes_t *, int *); static int (*ALSA_snd_pcm_hw_params_get_period_size) (const snd_pcm_hw_params_t *, snd_pcm_uframes_t *, int *); static int (*ALSA_snd_pcm_hw_params_set_periods_min) (snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *); static int (*ALSA_snd_pcm_hw_params_set_periods_first) (snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *, int *); static int (*ALSA_snd_pcm_hw_params_get_periods) (const snd_pcm_hw_params_t *, unsigned int *, int *); static int (*ALSA_snd_pcm_hw_params_set_buffer_size_near) (snd_pcm_t *pcm, snd_pcm_hw_params_t *, snd_pcm_uframes_t *); static int (*ALSA_snd_pcm_hw_params_get_buffer_size) (const snd_pcm_hw_params_t *, snd_pcm_uframes_t *); static int (*ALSA_snd_pcm_hw_params) (snd_pcm_t *, snd_pcm_hw_params_t *); static int (*ALSA_snd_pcm_sw_params_current) (snd_pcm_t *, snd_pcm_sw_params_t *); static int (*ALSA_snd_pcm_sw_params_set_start_threshold) (snd_pcm_t *, snd_pcm_sw_params_t *, snd_pcm_uframes_t); static int (*ALSA_snd_pcm_sw_params) (snd_pcm_t *, snd_pcm_sw_params_t *); static int (*ALSA_snd_pcm_nonblock) (snd_pcm_t *, int); static int (*ALSA_snd_pcm_wait)(snd_pcm_t *, int); static int (*ALSA_snd_pcm_sw_params_set_avail_min) (snd_pcm_t *, snd_pcm_sw_params_t *, snd_pcm_uframes_t); static int (*ALSA_snd_pcm_reset)(snd_pcm_t *); static int (*ALSA_snd_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); #endif #ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC #define snd_pcm_hw_params_sizeof ALSA_snd_pcm_hw_params_sizeof #define snd_pcm_sw_params_sizeof ALSA_snd_pcm_sw_params_sizeof static const char *alsa_library = SDL_AUDIO_DRIVER_ALSA_DYNAMIC; static void *alsa_handle = NULL; static int load_alsa_sym(const char *fn, void **addr) { *addr = SDL_LoadFunction(alsa_handle, fn); if (*addr == NULL) { /* Don't call SDL_SetError(): SDL_LoadFunction already did. */ return 0; } return 1; } /* cast funcs to char* first, to please GCC's strict aliasing rules. */ #define SDL_ALSA_SYM(x) \ if (!load_alsa_sym(#x, (void **) (char *) &ALSA_##x)) return -1 #else #define SDL_ALSA_SYM(x) ALSA_##x = x #endif static int load_alsa_syms(void) { SDL_ALSA_SYM(snd_pcm_open); SDL_ALSA_SYM(snd_pcm_close); SDL_ALSA_SYM(snd_pcm_writei); SDL_ALSA_SYM(snd_pcm_readi); SDL_ALSA_SYM(snd_pcm_recover); SDL_ALSA_SYM(snd_pcm_prepare); SDL_ALSA_SYM(snd_pcm_drain); SDL_ALSA_SYM(snd_strerror); SDL_ALSA_SYM(snd_pcm_hw_params_sizeof); SDL_ALSA_SYM(snd_pcm_sw_params_sizeof); SDL_ALSA_SYM(snd_pcm_hw_params_copy); SDL_ALSA_SYM(snd_pcm_hw_params_any); SDL_ALSA_SYM(snd_pcm_hw_params_set_access); SDL_ALSA_SYM(snd_pcm_hw_params_set_format); SDL_ALSA_SYM(snd_pcm_hw_params_set_channels); SDL_ALSA_SYM(snd_pcm_hw_params_get_channels); SDL_ALSA_SYM(snd_pcm_hw_params_set_rate_near); SDL_ALSA_SYM(snd_pcm_hw_params_set_period_size_near); SDL_ALSA_SYM(snd_pcm_hw_params_get_period_size); SDL_ALSA_SYM(snd_pcm_hw_params_set_periods_min); SDL_ALSA_SYM(snd_pcm_hw_params_set_periods_first); SDL_ALSA_SYM(snd_pcm_hw_params_get_periods); SDL_ALSA_SYM(snd_pcm_hw_params_set_buffer_size_near); SDL_ALSA_SYM(snd_pcm_hw_params_get_buffer_size); SDL_ALSA_SYM(snd_pcm_hw_params); SDL_ALSA_SYM(snd_pcm_sw_params_current); SDL_ALSA_SYM(snd_pcm_sw_params_set_start_threshold); SDL_ALSA_SYM(snd_pcm_sw_params); SDL_ALSA_SYM(snd_pcm_nonblock); SDL_ALSA_SYM(snd_pcm_wait); SDL_ALSA_SYM(snd_pcm_sw_params_set_avail_min); SDL_ALSA_SYM(snd_pcm_reset); 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); #endif return 0; } #undef SDL_ALSA_SYM #ifdef SDL_AUDIO_DRIVER_ALSA_DYNAMIC static void UnloadALSALibrary(void) { if (alsa_handle != NULL) { SDL_UnloadObject(alsa_handle); alsa_handle = NULL; } } static int LoadALSALibrary(void) { int retval = 0; if (alsa_handle == NULL) { alsa_handle = SDL_LoadObject(alsa_library); if (alsa_handle == NULL) { retval = -1; /* Don't call SDL_SetError(): SDL_LoadObject already did. */ } else { retval = load_alsa_syms(); if (retval < 0) { UnloadALSALibrary(); } } } return retval; } #else static void UnloadALSALibrary(void) { } static int LoadALSALibrary(void) { load_alsa_syms(); return 0; } #endif /* SDL_AUDIO_DRIVER_ALSA_DYNAMIC */ static const char * get_audio_device(void *handle, const int channels) { const char *device; if (handle != NULL) { return (const char *) handle; } /* !!! FIXME: we also check "SDL_AUDIO_DEVICE_NAME" at the higher level. */ device = SDL_getenv("AUDIODEV"); /* Is there a standard variable name? */ if (device != NULL) { return device; } if (channels == 6) { return "plug:surround51"; } else if (channels == 4) { return "plug:surround40"; } return "default"; } /* This function waits until it is possible to write a full sound buffer */ 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 } /* !!! FIXME: is there a channel swizzler in alsalib instead? */ /* * http://bugzilla.libsdl.org/show_bug.cgi?id=110 * "For Linux ALSA, this is FL-FR-RL-RR-C-LFE * and for Windows DirectX [and CoreAudio], this is FL-FR-C-LFE-RL-RR" */ #define SWIZ6(T, buf, numframes) \ T *ptr = (T *) buf; \ Uint32 i; \ for (i = 0; i < numframes; i++, ptr += 6) { \ T tmp; \ tmp = ptr[2]; ptr[2] = ptr[4]; ptr[4] = tmp; \ tmp = ptr[3]; ptr[3] = ptr[5]; ptr[5] = tmp; \ } static void swizzle_alsa_channels_6_64bit(void *buffer, Uint32 bufferlen) { SWIZ6(Uint64, buffer, bufferlen); } static void swizzle_alsa_channels_6_32bit(void *buffer, Uint32 bufferlen) { SWIZ6(Uint32, buffer, bufferlen); } static void swizzle_alsa_channels_6_16bit(void *buffer, Uint32 bufferlen) { SWIZ6(Uint16, buffer, bufferlen); } static void swizzle_alsa_channels_6_8bit(void *buffer, Uint32 bufferlen) { SWIZ6(Uint8, buffer, bufferlen); } #undef SWIZ6 /* * Called right before feeding this->hidden->mixbuf to the hardware. Swizzle * channels from Windows/Mac order to the format alsalib will want. */ static void swizzle_alsa_channels(_THIS, void *buffer, Uint32 bufferlen) { if (this->spec.channels == 6) { switch (SDL_AUDIO_BITSIZE(this->spec.format)) { case 8: swizzle_alsa_channels_6_8bit(buffer, bufferlen); break; case 16: swizzle_alsa_channels_6_16bit(buffer, bufferlen); break; case 32: swizzle_alsa_channels_6_32bit(buffer, bufferlen); break; case 64: swizzle_alsa_channels_6_64bit(buffer, bufferlen); break; default: SDL_assert(!"unhandled bitsize"); break; } } /* !!! FIXME: update this for 7.1 if needed, later. */ } #ifdef SND_CHMAP_API_VERSION /* Some devices have the right channel map, no swizzling necessary */ static void no_swizzle(_THIS, void *buffer, Uint32 bufferlen) { } #endif /* SND_CHMAP_API_VERSION */ static void ALSA_PlayDevice(_THIS) { const Uint8 *sample_buf = (const Uint8 *) this->hidden->mixbuf; const int frame_size = ((SDL_AUDIO_BITSIZE(this->spec.format)) / 8) * this->spec.channels; snd_pcm_uframes_t frames_left = ((snd_pcm_uframes_t) this->spec.samples); this->hidden->swizzle_func(this, this->hidden->mixbuf, frames_left); while ( frames_left > 0 && SDL_AtomicGet(&this->enabled) ) { int status = ALSA_snd_pcm_writei(this->hidden->pcm_handle, sample_buf, frames_left); if (status < 0) { if (status == -EAGAIN) { /* Apparently snd_pcm_recover() doesn't handle this case - does it assume snd_pcm_wait() above? */ SDL_Delay(1); continue; } status = ALSA_snd_pcm_recover(this->hidden->pcm_handle, status, 0); if (status < 0) { /* Hmm, not much we can do - abort */ fprintf(stderr, "ALSA write failed (unrecoverable): %s\n", ALSA_snd_strerror(status)); SDL_OpenedAudioDeviceDisconnected(this); return; } continue; } else if (status == 0) { /* No frames were written (no available space in pcm device). Allow other threads to catch up. */ Uint32 delay = (frames_left / 2 * 1000) / this->spec.freq; SDL_Delay(delay); } sample_buf += status * frame_size; frames_left -= status; } } static Uint8 * ALSA_GetDeviceBuf(_THIS) { return (this->hidden->mixbuf); } static int ALSA_CaptureFromDevice(_THIS, void *buffer, int buflen) { Uint8 *sample_buf = (Uint8 *) buffer; const int frame_size = ((SDL_AUDIO_BITSIZE(this->spec.format)) / 8) * this->spec.channels; const int total_frames = buflen / frame_size; snd_pcm_uframes_t frames_left = total_frames; snd_pcm_uframes_t wait_time = frame_size / 2; SDL_assert((buflen % frame_size) == 0); while ( frames_left > 0 && SDL_AtomicGet(&this->enabled) ) { int status; status = ALSA_snd_pcm_readi(this->hidden->pcm_handle, sample_buf, frames_left); if (status == -EAGAIN) { ALSA_snd_pcm_wait(this->hidden->pcm_handle, wait_time); status = 0; } else if (status < 0) { /*printf("ALSA: capture error %d\n", status);*/ status = ALSA_snd_pcm_recover(this->hidden->pcm_handle, status, 0); if (status < 0) { /* Hmm, not much we can do - abort */ fprintf(stderr, "ALSA read failed (unrecoverable): %s\n", ALSA_snd_strerror(status)); return -1; } continue; } /*printf("ALSA: captured %d bytes\n", status * frame_size);*/ sample_buf += status * frame_size; frames_left -= status; } this->hidden->swizzle_func(this, buffer, total_frames - frames_left); return (total_frames - frames_left) * frame_size; } static void ALSA_FlushCapture(_THIS) { ALSA_snd_pcm_reset(this->hidden->pcm_handle); } static void ALSA_CloseDevice(_THIS) { if (this->hidden->pcm_handle) { /* 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; SDL_Delay(delay); ALSA_snd_pcm_close(this->hidden->pcm_handle); } SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); } static int ALSA_set_buffer_size(_THIS, snd_pcm_hw_params_t *params) { int status; snd_pcm_hw_params_t *hwparams; snd_pcm_uframes_t persize; unsigned int periods; /* Copy the hardware parameters for this setup */ snd_pcm_hw_params_alloca(&hwparams); ALSA_snd_pcm_hw_params_copy(hwparams, params); /* Attempt to match 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); } /* Need to at least double buffer */ periods = 2; status = ALSA_snd_pcm_hw_params_set_periods_min( this->hidden->pcm_handle, hwparams, &periods, NULL); if ( status < 0 ) { return(-1); } status = ALSA_snd_pcm_hw_params_set_periods_first( this->hidden->pcm_handle, hwparams, &periods, NULL); if ( status < 0 ) { return(-1); } /* "set" the hardware with the desired parameters */ status = ALSA_snd_pcm_hw_params(this->hidden->pcm_handle, hwparams); if ( status < 0 ) { return(-1); } this->spec.samples = persize; /* This is useful for debugging */ if ( SDL_getenv("SDL_AUDIO_ALSA_DEBUG") ) { snd_pcm_uframes_t bufsize; ALSA_snd_pcm_hw_params_get_buffer_size(hwparams, &bufsize); fprintf(stderr, "ALSA: period size = %ld, periods = %u, buffer size = %lu\n", persize, periods, bufsize); } return(0); } static int ALSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { int status = 0; snd_pcm_t *pcm_handle = NULL; snd_pcm_hw_params_t *hwparams = NULL; snd_pcm_sw_params_t *swparams = NULL; snd_pcm_format_t format = 0; SDL_AudioFormat test_format = 0; unsigned int rate = 0; unsigned int channels = 0; #ifdef SND_CHMAP_API_VERSION snd_pcm_chmap_t *chmap; char chmap_str[64]; #endif /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); /* Open the audio device */ /* Name of device should depend on # channels in spec */ status = ALSA_snd_pcm_open(&pcm_handle, get_audio_device(handle, this->spec.channels), iscapture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); if (status < 0) { return SDL_SetError("ALSA: Couldn't open audio device: %s", ALSA_snd_strerror(status)); } this->hidden->pcm_handle = pcm_handle; /* Figure out what the hardware is capable of */ snd_pcm_hw_params_alloca(&hwparams); status = ALSA_snd_pcm_hw_params_any(pcm_handle, hwparams); if (status < 0) { return SDL_SetError("ALSA: Couldn't get hardware config: %s", ALSA_snd_strerror(status)); } /* SDL only uses interleaved sample output */ status = ALSA_snd_pcm_hw_params_set_access(pcm_handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED); if (status < 0) { return SDL_SetError("ALSA: Couldn't set interleaved access: %s", ALSA_snd_strerror(status)); } /* Try for a closest match on audio format */ status = -1; for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format && (status < 0);) { status = 0; /* if we can't support a format, it'll become -1. */ switch (test_format) { case AUDIO_U8: format = SND_PCM_FORMAT_U8; break; case AUDIO_S8: format = SND_PCM_FORMAT_S8; break; case AUDIO_S16LSB: format = SND_PCM_FORMAT_S16_LE; break; case AUDIO_S16MSB: format = SND_PCM_FORMAT_S16_BE; break; case AUDIO_U16LSB: format = SND_PCM_FORMAT_U16_LE; break; case AUDIO_U16MSB: format = SND_PCM_FORMAT_U16_BE; break; case AUDIO_S32LSB: format = SND_PCM_FORMAT_S32_LE; break; case AUDIO_S32MSB: format = SND_PCM_FORMAT_S32_BE; break; case AUDIO_F32LSB: format = SND_PCM_FORMAT_FLOAT_LE; break; case AUDIO_F32MSB: format = SND_PCM_FORMAT_FLOAT_BE; break; default: status = -1; break; } if (status >= 0) { status = ALSA_snd_pcm_hw_params_set_format(pcm_handle, hwparams, format); } if (status < 0) { test_format = SDL_NextAudioFormat(); } } if (status < 0) { return SDL_SetError("ALSA: Couldn't find any hardware audio formats"); } this->spec.format = test_format; /* Validate number of channels and determine if swizzling is necessary * Assume original swizzling, until proven otherwise. */ this->hidden->swizzle_func = swizzle_alsa_channels; #ifdef SND_CHMAP_API_VERSION chmap = ALSA_snd_pcm_get_chmap(pcm_handle); if (chmap) { ALSA_snd_pcm_chmap_print(chmap, sizeof(chmap_str), chmap_str); if (SDL_strcmp("FL FR FC LFE RL RR", chmap_str) == 0 || SDL_strcmp("FL FR FC LFE SL SR", chmap_str) == 0) { this->hidden->swizzle_func = no_swizzle; } free(chmap); } #endif /* SND_CHMAP_API_VERSION */ /* Set the number of channels */ status = ALSA_snd_pcm_hw_params_set_channels(pcm_handle, hwparams, this->spec.channels); channels = this->spec.channels; if (status < 0) { status = ALSA_snd_pcm_hw_params_get_channels(hwparams, &channels); if (status < 0) { return SDL_SetError("ALSA: Couldn't set audio channels"); } this->spec.channels = channels; } /* Set the audio rate */ rate = this->spec.freq; status = ALSA_snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, &rate, NULL); if (status < 0) { return SDL_SetError("ALSA: Couldn't set audio frequency: %s", ALSA_snd_strerror(status)); } 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)); } /* Set the software parameters */ snd_pcm_sw_params_alloca(&swparams); status = ALSA_snd_pcm_sw_params_current(pcm_handle, swparams); if (status < 0) { return SDL_SetError("ALSA: Couldn't get software config: %s", ALSA_snd_strerror(status)); } status = ALSA_snd_pcm_sw_params_set_avail_min(pcm_handle, swparams, this->spec.samples); if (status < 0) { return SDL_SetError("Couldn't set minimum available samples: %s", ALSA_snd_strerror(status)); } status = ALSA_snd_pcm_sw_params_set_start_threshold(pcm_handle, swparams, 1); if (status < 0) { return SDL_SetError("ALSA: Couldn't set start threshold: %s", ALSA_snd_strerror(status)); } status = ALSA_snd_pcm_sw_params(pcm_handle, swparams); if (status < 0) { return SDL_SetError("Couldn't set software audio parameters: %s", ALSA_snd_strerror(status)); } /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&this->spec); /* Allocate mixing buffer */ if (!iscapture) { this->hidden->mixlen = this->spec.size; this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } 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; } typedef struct ALSA_Device { char *name; SDL_bool iscapture; struct ALSA_Device *next; } ALSA_Device; static void add_device(const int iscapture, const char *name, void *hint, ALSA_Device **pSeen) { ALSA_Device *dev = SDL_malloc(sizeof (ALSA_Device)); char *desc; char *handle = NULL; char *ptr; if (!dev) { return; } /* Not all alsa devices are enumerable via snd_device_name_get_hint (i.e. bluetooth devices). Therefore if hint is passed in to this function as NULL, assume name contains desc. Make sure not to free the storage associated with desc in this case */ if (hint) { desc = ALSA_snd_device_name_get_hint(hint, "DESC"); if (!desc) { SDL_free(dev); return; } } else { desc = (char *) name; } SDL_assert(name != NULL); /* some strings have newlines, like "HDA NVidia, HDMI 0\nHDMI Audio Output". just chop the extra lines off, this seems to get a reasonable device name without extra details. */ if ((ptr = strchr(desc, '\n')) != NULL) { *ptr = '\0'; } /*printf("ALSA: adding %s device '%s' (%s)\n", iscapture ? "capture" : "output", name, desc);*/ handle = SDL_strdup(name); if (!handle) { if (hint) { free(desc); } SDL_free(dev); return; } SDL_AddAudioDevice(iscapture, desc, handle); if (hint) free(desc); dev->name = handle; dev->iscapture = iscapture; dev->next = *pSeen; *pSeen = dev; } static SDL_atomic_t ALSA_hotplug_shutdown; static SDL_Thread *ALSA_hotplug_thread; static int SDLCALL ALSA_HotplugThread(void *arg) { SDL_sem *first_run_semaphore = (SDL_sem *) arg; ALSA_Device *devices = NULL; ALSA_Device *next; ALSA_Device *dev; Uint32 ticks; SDL_SetThreadPriority(SDL_THREAD_PRIORITY_LOW); while (!SDL_AtomicGet(&ALSA_hotplug_shutdown)) { void **hints = NULL; ALSA_Device *unseen; ALSA_Device *seen; ALSA_Device *prev; if (ALSA_snd_device_name_hint(-1, "pcm", &hints) == 0) { int i, j; const char *match = NULL; int bestmatch = 0xFFFF; size_t match_len = 0; int defaultdev = -1; static const char * const prefixes[] = { "hw:", "sysdefault:", "default:", NULL }; unseen = devices; seen = NULL; /* Apparently there are several different ways that ALSA lists actual hardware. It could be prefixed with "hw:" or "default:" or "sysdefault:" and maybe others. Go through the list and see if we can find a preferred prefix for the system. */ for (i = 0; hints[i]; i++) { char *name = ALSA_snd_device_name_get_hint(hints[i], "NAME"); if (!name) { continue; } /* full name, not a prefix */ if ((defaultdev == -1) && (SDL_strcmp(name, "default") == 0)) { defaultdev = i; } for (j = 0; prefixes[j]; j++) { const char *prefix = prefixes[j]; const size_t prefixlen = SDL_strlen(prefix); if (SDL_strncmp(name, prefix, prefixlen) == 0) { if (j < bestmatch) { bestmatch = j; match = prefix; match_len = prefixlen; } } } free(name); } /* look through the list of device names to find matches */ for (i = 0; hints[i]; i++) { char *name; /* if we didn't find a device name prefix we like at all... */ if ((!match) && (defaultdev != i)) { continue; /* ...skip anything that isn't the default device. */ } name = ALSA_snd_device_name_get_hint(hints[i], "NAME"); if (!name) { continue; } /* only want physical hardware interfaces */ if (!match || (SDL_strncmp(name, match, match_len) == 0)) { char *ioid = ALSA_snd_device_name_get_hint(hints[i], "IOID"); const SDL_bool isoutput = (ioid == NULL) || (SDL_strcmp(ioid, "Output") == 0); const SDL_bool isinput = (ioid == NULL) || (SDL_strcmp(ioid, "Input") == 0); SDL_bool have_output = SDL_FALSE; SDL_bool have_input = SDL_FALSE; free(ioid); if (!isoutput && !isinput) { free(name); continue; } prev = NULL; for (dev = unseen; dev; dev = next) { next = dev->next; if ( (SDL_strcmp(dev->name, name) == 0) && (((isinput) && dev->iscapture) || ((isoutput) && !dev->iscapture)) ) { if (prev) { prev->next = next; } else { unseen = next; } dev->next = seen; seen = dev; if (isinput) have_input = SDL_TRUE; if (isoutput) have_output = SDL_TRUE; } else { prev = dev; } } if (isinput && !have_input) { add_device(SDL_TRUE, name, hints[i], &seen); } if (isoutput && !have_output) { add_device(SDL_FALSE, name, hints[i], &seen); } } free(name); } ALSA_snd_device_name_free_hint(hints); devices = seen; /* now we have a known-good list of attached devices. */ /* report anything still in unseen as removed. */ for (dev = unseen; dev; dev = next) { /*printf("ALSA: removing usb %s device '%s'\n", dev->iscapture ? "capture" : "output", dev->name);*/ next = dev->next; SDL_RemoveAudioDevice(dev->iscapture, dev->name); SDL_free(dev->name); SDL_free(dev); } } /* On first run, tell ALSA_DetectDevices() that we have a complete device list so it can return. */ if (first_run_semaphore) { SDL_SemPost(first_run_semaphore); first_run_semaphore = NULL; /* let other thread clean it up. */ } /* Block awhile before checking again, unless we're told to stop. */ ticks = SDL_GetTicks() + 5000; while (!SDL_AtomicGet(&ALSA_hotplug_shutdown) && !SDL_TICKS_PASSED(SDL_GetTicks(), ticks)) { SDL_Delay(100); } } /* Shutting down! Clean up any data we've gathered. */ for (dev = devices; dev; dev = next) { /*printf("ALSA: at shutdown, removing %s device '%s'\n", dev->iscapture ? "capture" : "output", dev->name);*/ next = dev->next; SDL_free(dev->name); SDL_free(dev); } return 0; } static void ALSA_DetectDevices(void) { /* Start the device detection thread here, wait for an initial iteration to complete. */ SDL_sem *semaphore = SDL_CreateSemaphore(0); if (!semaphore) { return; /* oh well. */ } SDL_AtomicSet(&ALSA_hotplug_shutdown, 0); ALSA_hotplug_thread = SDL_CreateThread(ALSA_HotplugThread, "SDLHotplugALSA", semaphore); if (ALSA_hotplug_thread) { SDL_SemWait(semaphore); /* wait for the first iteration to finish. */ } SDL_DestroySemaphore(semaphore); } static void ALSA_Deinitialize(void) { if (ALSA_hotplug_thread != NULL) { SDL_AtomicSet(&ALSA_hotplug_shutdown, 1); SDL_WaitThread(ALSA_hotplug_thread, NULL); ALSA_hotplug_thread = NULL; } UnloadALSALibrary(); } static int ALSA_Init(SDL_AudioDriverImpl * impl) { if (LoadALSALibrary() < 0) { return 0; } /* Set the function pointers */ impl->DetectDevices = ALSA_DetectDevices; impl->OpenDevice = ALSA_OpenDevice; impl->WaitDevice = ALSA_WaitDevice; impl->GetDeviceBuf = ALSA_GetDeviceBuf; impl->PlayDevice = ALSA_PlayDevice; impl->CloseDevice = ALSA_CloseDevice; impl->Deinitialize = ALSA_Deinitialize; impl->CaptureFromDevice = ALSA_CaptureFromDevice; impl->FlushCapture = ALSA_FlushCapture; impl->HasCaptureSupport = SDL_TRUE; return 1; /* this audio target is available. */ } AudioBootStrap ALSA_bootstrap = { "alsa", "ALSA PCM audio", ALSA_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_ALSA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/alsa/SDL_alsa_audio.c
C
apache-2.0
32,607
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_ALSA_audio_h_ #define SDL_ALSA_audio_h_ #include <alsa/asoundlib.h> #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The audio device handle */ snd_pcm_t *pcm_handle; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; /* swizzle function */ void (*swizzle_func)(_THIS, void *buffer, Uint32 bufferlen); }; #endif /* SDL_ALSA_audio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/alsa/SDL_alsa_audio.h
C
apache-2.0
1,494
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_ANDROID /* Output audio to Android */ #include "SDL_assert.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_androidaudio.h" #include "../../core/android/SDL_android.h" #include <android/log.h> static SDL_AudioDevice* audioDevice = NULL; static SDL_AudioDevice* captureDevice = NULL; static int ANDROIDAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { SDL_AudioFormat test_format; SDL_assert((captureDevice == NULL) || !iscapture); SDL_assert((audioDevice == NULL) || iscapture); if (iscapture) { captureDevice = this; } else { audioDevice = this; } this->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, (sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } 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)) { this->spec.format = test_format; break; } test_format = SDL_NextAudioFormat(); } if (test_format == 0) { /* Didn't find a compatible format :( */ return SDL_SetError("No compatible audio format!"); } if (Android_JNI_OpenAudioDevice(iscapture, &this->spec) < 0) { return -1; } SDL_CalculateAudioSpec(&this->spec); return 0; } static void ANDROIDAUDIO_PlayDevice(_THIS) { Android_JNI_WriteAudioBuffer(); } static Uint8 * ANDROIDAUDIO_GetDeviceBuf(_THIS) { return Android_JNI_GetAudioBuffer(); } static int ANDROIDAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen) { return Android_JNI_CaptureAudioBuffer(buffer, buflen); } static void ANDROIDAUDIO_FlushCapture(_THIS) { Android_JNI_FlushCapturedAudio(); } static void ANDROIDAUDIO_CloseDevice(_THIS) { /* At this point SDL_CloseAudioDevice via close_audio_device took care of terminating the audio thread so it's safe to terminate the Java side buffer and AudioTrack */ Android_JNI_CloseAudioDevice(this->iscapture); if (this->iscapture) { SDL_assert(captureDevice == this); captureDevice = NULL; } else { SDL_assert(audioDevice == this); audioDevice = NULL; } SDL_free(this->hidden); } static int ANDROIDAUDIO_Init(SDL_AudioDriverImpl * impl) { /* Set the function pointers */ impl->OpenDevice = ANDROIDAUDIO_OpenDevice; impl->PlayDevice = ANDROIDAUDIO_PlayDevice; impl->GetDeviceBuf = ANDROIDAUDIO_GetDeviceBuf; impl->CloseDevice = ANDROIDAUDIO_CloseDevice; impl->CaptureFromDevice = ANDROIDAUDIO_CaptureFromDevice; impl->FlushCapture = ANDROIDAUDIO_FlushCapture; /* and the capabilities */ impl->HasCaptureSupport = SDL_TRUE; impl->OnlyHasDefaultOutputDevice = 1; impl->OnlyHasDefaultCaptureDevice = 1; return 1; /* this audio target is available. */ } AudioBootStrap ANDROIDAUDIO_bootstrap = { "android", "SDL Android audio driver", ANDROIDAUDIO_Init, 0 }; /* Pause (block) all non already paused audio devices by taking their mixer lock */ void ANDROIDAUDIO_PauseDevices(void) { /* TODO: Handle multiple devices? */ struct SDL_PrivateAudioData *private; if(audioDevice != NULL && audioDevice->hidden != NULL) { private = (struct SDL_PrivateAudioData *) audioDevice->hidden; if (SDL_AtomicGet(&audioDevice->paused)) { /* The device is already paused, leave it alone */ private->resume = SDL_FALSE; } else { SDL_LockMutex(audioDevice->mixer_lock); SDL_AtomicSet(&audioDevice->paused, 1); private->resume = SDL_TRUE; } } if(captureDevice != NULL && captureDevice->hidden != NULL) { private = (struct SDL_PrivateAudioData *) captureDevice->hidden; if (SDL_AtomicGet(&captureDevice->paused)) { /* The device is already paused, leave it alone */ private->resume = SDL_FALSE; } else { SDL_LockMutex(captureDevice->mixer_lock); SDL_AtomicSet(&captureDevice->paused, 1); private->resume = SDL_TRUE; } } } /* Resume (unblock) all non already paused audio devices by releasing their mixer lock */ void ANDROIDAUDIO_ResumeDevices(void) { /* TODO: Handle multiple devices? */ struct SDL_PrivateAudioData *private; if(audioDevice != NULL && audioDevice->hidden != NULL) { private = (struct SDL_PrivateAudioData *) audioDevice->hidden; if (private->resume) { SDL_AtomicSet(&audioDevice->paused, 0); private->resume = SDL_FALSE; SDL_UnlockMutex(audioDevice->mixer_lock); } } if(captureDevice != NULL && captureDevice->hidden != NULL) { private = (struct SDL_PrivateAudioData *) captureDevice->hidden; if (private->resume) { SDL_AtomicSet(&captureDevice->paused, 0); private->resume = SDL_FALSE; SDL_UnlockMutex(captureDevice->mixer_lock); } } } #else void ANDROIDAUDIO_ResumeDevices(void) {} void ANDROIDAUDIO_PauseDevices(void) {} #endif /* SDL_AUDIO_DRIVER_ANDROID */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/android/SDL_androidaudio.c
C
apache-2.0
6,293
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_androidaudio_h_ #define SDL_androidaudio_h_ #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* Resume device if it was paused automatically */ int resume; }; void ANDROIDAUDIO_ResumeDevices(void); void ANDROIDAUDIO_PauseDevices(void); #endif /* SDL_androidaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/android/SDL_androidaudio.h
C
apache-2.0
1,402
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_ARTS /* Allow access to a raw mixing buffer */ #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #include <unistd.h> #include <errno.h> #include "SDL_timer.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_artsaudio.h" #ifdef SDL_AUDIO_DRIVER_ARTS_DYNAMIC #include "SDL_name.h" #include "SDL_loadso.h" #else #define SDL_NAME(X) X #endif #ifdef SDL_AUDIO_DRIVER_ARTS_DYNAMIC static const char *arts_library = SDL_AUDIO_DRIVER_ARTS_DYNAMIC; static void *arts_handle = NULL; /* !!! FIXME: I hate this SDL_NAME clutter...it makes everything so messy! */ static int (*SDL_NAME(arts_init)) (void); static void (*SDL_NAME(arts_free)) (void); static arts_stream_t(*SDL_NAME(arts_play_stream)) (int rate, int bits, int channels, const char *name); static int (*SDL_NAME(arts_stream_set)) (arts_stream_t s, arts_parameter_t param, int value); static int (*SDL_NAME(arts_stream_get)) (arts_stream_t s, arts_parameter_t param); static int (*SDL_NAME(arts_write)) (arts_stream_t s, const void *buffer, int count); static void (*SDL_NAME(arts_close_stream)) (arts_stream_t s); static int (*SDL_NAME(arts_suspend))(void); static int (*SDL_NAME(arts_suspended)) (void); static const char *(*SDL_NAME(arts_error_text)) (int errorcode); #define SDL_ARTS_SYM(x) { #x, (void **) (char *) &SDL_NAME(x) } static struct { const char *name; void **func; } arts_functions[] = { /* *INDENT-OFF* */ SDL_ARTS_SYM(arts_init), SDL_ARTS_SYM(arts_free), SDL_ARTS_SYM(arts_play_stream), SDL_ARTS_SYM(arts_stream_set), SDL_ARTS_SYM(arts_stream_get), SDL_ARTS_SYM(arts_write), SDL_ARTS_SYM(arts_close_stream), SDL_ARTS_SYM(arts_suspend), SDL_ARTS_SYM(arts_suspended), SDL_ARTS_SYM(arts_error_text), /* *INDENT-ON* */ }; #undef SDL_ARTS_SYM static void UnloadARTSLibrary() { if (arts_handle != NULL) { SDL_UnloadObject(arts_handle); arts_handle = NULL; } } static int LoadARTSLibrary(void) { int i, retval = -1; if (arts_handle == NULL) { arts_handle = SDL_LoadObject(arts_library); if (arts_handle != NULL) { retval = 0; for (i = 0; i < SDL_arraysize(arts_functions); ++i) { *arts_functions[i].func = SDL_LoadFunction(arts_handle, arts_functions[i].name); if (!*arts_functions[i].func) { retval = -1; UnloadARTSLibrary(); break; } } } } return retval; } #else static void UnloadARTSLibrary() { return; } static int LoadARTSLibrary(void) { return 0; } #endif /* SDL_AUDIO_DRIVER_ARTS_DYNAMIC */ /* This function waits until it is possible to write a full sound buffer */ static void ARTS_WaitDevice(_THIS) { Sint32 ticks; /* Check to see if the thread-parent process is still alive */ { static int cnt = 0; /* Note that this only works with thread implementations that use a different process id for each thread. */ /* Check every 10 loops */ if (this->hidden->parent && (((++cnt) % 10) == 0)) { if (kill(this->hidden->parent, 0) < 0 && errno == ESRCH) { SDL_OpenedAudioDeviceDisconnected(this); } } } /* Use timer for general audio synchronization */ ticks = ((Sint32) (this->hidden->next_frame - SDL_GetTicks())) - FUDGE_TICKS; if (ticks > 0) { SDL_Delay(ticks); } } static void ARTS_PlayDevice(_THIS) { /* Write the audio data */ int written = SDL_NAME(arts_write) (this->hidden->stream, this->hidden->mixbuf, this->hidden->mixlen); /* If timer synchronization is enabled, set the next write frame */ if (this->hidden->frame_ticks) { this->hidden->next_frame += this->hidden->frame_ticks; } /* If we couldn't write, assume fatal error for now */ if (written < 0) { SDL_OpenedAudioDeviceDisconnected(this); } #ifdef DEBUG_AUDIO fprintf(stderr, "Wrote %d bytes of audio data\n", written); #endif } static Uint8 * ARTS_GetDeviceBuf(_THIS) { return (this->hidden->mixbuf); } static void ARTS_CloseDevice(_THIS) { if (this->hidden->stream) { SDL_NAME(arts_close_stream) (this->hidden->stream); } SDL_NAME(arts_free) (); SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); } static int ARTS_Suspend(void) { const Uint32 abortms = SDL_GetTicks() + 3000; /* give up after 3 secs */ while ( (!SDL_NAME(arts_suspended)()) && !SDL_TICKS_PASSED(SDL_GetTicks(), abortms) ) { if ( SDL_NAME(arts_suspend)() ) { break; } } return SDL_NAME(arts_suspended)(); } static int ARTS_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { int rc = 0; int bits = 0, frag_spec = 0; SDL_AudioFormat test_format = 0, format = 0; /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); /* Try for a closest match on audio format */ for (test_format = SDL_FirstAudioFormat(this->spec.format); !format && test_format;) { #ifdef DEBUG_AUDIO fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif switch (test_format) { case AUDIO_U8: bits = 8; format = 1; break; case AUDIO_S16LSB: bits = 16; format = 1; break; default: format = 0; break; } if (!format) { test_format = SDL_NextAudioFormat(); } } if (format == 0) { return SDL_SetError("Couldn't find any hardware audio formats"); } this->spec.format = test_format; if ((rc = SDL_NAME(arts_init) ()) != 0) { return SDL_SetError("Unable to initialize ARTS: %s", SDL_NAME(arts_error_text) (rc)); } if (!ARTS_Suspend()) { return SDL_SetError("ARTS can not open audio device"); } this->hidden->stream = SDL_NAME(arts_play_stream) (this->spec.freq, bits, this->spec.channels, "SDL"); /* Play nothing so we have at least one write (server bug workaround). */ SDL_NAME(arts_write) (this->hidden->stream, "", 0); /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&this->spec); /* Determine the power of two of the fragment size */ for (frag_spec = 0; (0x01 << frag_spec) < this->spec.size; ++frag_spec); if ((0x01 << frag_spec) != this->spec.size) { return SDL_SetError("Fragment size must be a power of two"); } frag_spec |= 0x00020000; /* two fragments, for low latency */ #ifdef ARTS_P_PACKET_SETTINGS SDL_NAME(arts_stream_set) (this->hidden->stream, ARTS_P_PACKET_SETTINGS, frag_spec); #else SDL_NAME(arts_stream_set) (this->hidden->stream, ARTS_P_PACKET_SIZE, frag_spec & 0xffff); SDL_NAME(arts_stream_set) (this->hidden->stream, ARTS_P_PACKET_COUNT, frag_spec >> 16); #endif this->spec.size = SDL_NAME(arts_stream_get) (this->hidden->stream, ARTS_P_PACKET_SIZE); /* Allocate mixing buffer */ this->hidden->mixlen = this->spec.size; this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); /* Get the parent process id (we're the parent of the audio thread) */ this->hidden->parent = getpid(); /* We're ready to rock and roll. :-) */ return 0; } static void ARTS_Deinitialize(void) { UnloadARTSLibrary(); } static int ARTS_Init(SDL_AudioDriverImpl * impl) { if (LoadARTSLibrary() < 0) { return 0; } else { if (SDL_NAME(arts_init) () != 0) { UnloadARTSLibrary(); SDL_SetError("ARTS: arts_init failed (no audio server?)"); return 0; } /* Play a stream so aRts doesn't crash */ if (ARTS_Suspend()) { arts_stream_t stream; stream = SDL_NAME(arts_play_stream) (44100, 16, 2, "SDL"); SDL_NAME(arts_write) (stream, "", 0); SDL_NAME(arts_close_stream) (stream); } SDL_NAME(arts_free) (); } /* Set the function pointers */ impl->OpenDevice = ARTS_OpenDevice; impl->PlayDevice = ARTS_PlayDevice; impl->WaitDevice = ARTS_WaitDevice; impl->GetDeviceBuf = ARTS_GetDeviceBuf; impl->CloseDevice = ARTS_CloseDevice; impl->Deinitialize = ARTS_Deinitialize; impl->OnlyHasDefaultOutputDevice = 1; return 1; /* this audio target is available. */ } AudioBootStrap ARTS_bootstrap = { "arts", "Analog RealTime Synthesizer", ARTS_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_ARTS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/arts/SDL_artsaudio.c
C
apache-2.0
10,609
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_artsaudio_h_ #define SDL_artsaudio_h_ #include <artsc.h> #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The stream descriptor for the audio device */ arts_stream_t stream; /* The parent process id, to detect when application quits */ pid_t parent; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; /* Support for audio timing using a timer, in addition to SDL_IOReady() */ float frame_ticks; float next_frame; }; #define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ #endif /* SDL_artsaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/arts/SDL_artsaudio.h
C
apache-2.0
1,690
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_coreaudio_h_ #define SDL_coreaudio_h_ #include "../SDL_sysaudio.h" #if !defined(__IPHONEOS__) #define MACOSX_COREAUDIO 1 #endif #if MACOSX_COREAUDIO #include <CoreAudio/CoreAudio.h> #include <CoreServices/CoreServices.h> #else #import <AVFoundation/AVFoundation.h> #import <UIKit/UIApplication.h> #endif #include <AudioToolbox/AudioToolbox.h> #include <AudioUnit/AudioUnit.h> /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { SDL_Thread *thread; AudioQueueRef audioQueue; int numAudioBuffers; AudioQueueBufferRef *audioBuffer; void *buffer; UInt32 bufferOffset; UInt32 bufferSize; AudioStreamBasicDescription strdesc; SDL_sem *ready_semaphore; char *thread_error; SDL_atomic_t shutdown; #if MACOSX_COREAUDIO AudioDeviceID deviceID; SDL_atomic_t device_change_flag; #else SDL_bool interrupted; CFTypeRef interruption_listener; #endif }; #endif /* SDL_coreaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/coreaudio/SDL_coreaudio.h
Objective-C
apache-2.0
2,023
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_COREAUDIO /* !!! FIXME: clean out some of the macro salsa in here. */ #include "SDL_audio.h" #include "SDL_hints.h" #include "../SDL_audio_c.h" #include "../SDL_sysaudio.h" #include "SDL_coreaudio.h" #include "SDL_assert.h" #include "../../thread/SDL_systhread.h" #define DEBUG_COREAUDIO 0 #if DEBUG_COREAUDIO #define CHECK_RESULT(msg) \ if (result != noErr) { \ printf("COREAUDIO: Got error %d from '%s'!\n", (int) result, msg); \ SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \ return 0; \ } #else #define CHECK_RESULT(msg) \ if (result != noErr) { \ SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \ return 0; \ } #endif #if MACOSX_COREAUDIO static const AudioObjectPropertyAddress devlist_address = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; typedef void (*addDevFn)(const char *name, const int iscapture, AudioDeviceID devId, void *data); typedef struct AudioDeviceList { AudioDeviceID devid; SDL_bool alive; struct AudioDeviceList *next; } AudioDeviceList; static AudioDeviceList *output_devs = NULL; static AudioDeviceList *capture_devs = NULL; static SDL_bool add_to_internal_dev_list(const int iscapture, AudioDeviceID devId) { AudioDeviceList *item = (AudioDeviceList *) SDL_malloc(sizeof (AudioDeviceList)); if (item == NULL) { return SDL_FALSE; } item->devid = devId; item->alive = SDL_TRUE; item->next = iscapture ? capture_devs : output_devs; if (iscapture) { capture_devs = item; } else { output_devs = item; } return SDL_TRUE; } static void addToDevList(const char *name, const int iscapture, AudioDeviceID devId, void *data) { if (add_to_internal_dev_list(iscapture, devId)) { SDL_AddAudioDevice(iscapture, name, (void *) ((size_t) devId)); } } static void build_device_list(int iscapture, addDevFn addfn, void *addfndata) { OSStatus result = noErr; UInt32 size = 0; AudioDeviceID *devs = NULL; UInt32 i = 0; UInt32 max = 0; result = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &devlist_address, 0, NULL, &size); if (result != kAudioHardwareNoError) return; devs = (AudioDeviceID *) alloca(size); if (devs == NULL) return; result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &devlist_address, 0, NULL, &size, devs); if (result != kAudioHardwareNoError) return; max = size / sizeof (AudioDeviceID); for (i = 0; i < max; i++) { CFStringRef cfstr = NULL; char *ptr = NULL; AudioDeviceID dev = devs[i]; AudioBufferList *buflist = NULL; int usable = 0; CFIndex len = 0; const AudioObjectPropertyAddress addr = { kAudioDevicePropertyStreamConfiguration, iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster }; const AudioObjectPropertyAddress nameaddr = { kAudioObjectPropertyName, iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster }; result = AudioObjectGetPropertyDataSize(dev, &addr, 0, NULL, &size); if (result != noErr) continue; buflist = (AudioBufferList *) SDL_malloc(size); if (buflist == NULL) continue; result = AudioObjectGetPropertyData(dev, &addr, 0, NULL, &size, buflist); if (result == noErr) { UInt32 j; for (j = 0; j < buflist->mNumberBuffers; j++) { if (buflist->mBuffers[j].mNumberChannels > 0) { usable = 1; break; } } } SDL_free(buflist); if (!usable) continue; size = sizeof (CFStringRef); result = AudioObjectGetPropertyData(dev, &nameaddr, 0, NULL, &size, &cfstr); if (result != kAudioHardwareNoError) continue; len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr), kCFStringEncodingUTF8); ptr = (char *) SDL_malloc(len + 1); usable = ((ptr != NULL) && (CFStringGetCString (cfstr, ptr, len + 1, kCFStringEncodingUTF8))); CFRelease(cfstr); if (usable) { len = strlen(ptr); /* Some devices have whitespace at the end...trim it. */ while ((len > 0) && (ptr[len - 1] == ' ')) { len--; } usable = (len > 0); } if (usable) { ptr[len] = '\0'; #if DEBUG_COREAUDIO printf("COREAUDIO: Found %s device #%d: '%s' (devid %d)\n", ((iscapture) ? "capture" : "output"), (int) i, ptr, (int) dev); #endif addfn(ptr, iscapture, dev, addfndata); } SDL_free(ptr); /* addfn() would have copied the string. */ } } static void free_audio_device_list(AudioDeviceList **list) { AudioDeviceList *item = *list; while (item) { AudioDeviceList *next = item->next; SDL_free(item); item = next; } *list = NULL; } static void COREAUDIO_DetectDevices(void) { build_device_list(SDL_TRUE, addToDevList, NULL); build_device_list(SDL_FALSE, addToDevList, NULL); } static void build_device_change_list(const char *name, const int iscapture, AudioDeviceID devId, void *data) { AudioDeviceList **list = (AudioDeviceList **) data; AudioDeviceList *item; for (item = *list; item != NULL; item = item->next) { if (item->devid == devId) { item->alive = SDL_TRUE; return; } } add_to_internal_dev_list(iscapture, devId); /* new device, add it. */ SDL_AddAudioDevice(iscapture, name, (void *) ((size_t) devId)); } static void reprocess_device_list(const int iscapture, AudioDeviceList **list) { AudioDeviceList *item; AudioDeviceList *prev = NULL; for (item = *list; item != NULL; item = item->next) { item->alive = SDL_FALSE; } build_device_list(iscapture, build_device_change_list, list); /* free items in the list that aren't still alive. */ item = *list; while (item != NULL) { AudioDeviceList *next = item->next; if (item->alive) { prev = item; } else { SDL_RemoveAudioDevice(iscapture, (void *) ((size_t) item->devid)); if (prev) { prev->next = item->next; } else { *list = item->next; } SDL_free(item); } item = next; } } /* this is called when the system's list of available audio devices changes. */ static OSStatus device_list_changed(AudioObjectID systemObj, UInt32 num_addr, const AudioObjectPropertyAddress *addrs, void *data) { reprocess_device_list(SDL_TRUE, &capture_devs); reprocess_device_list(SDL_FALSE, &output_devs); return 0; } #endif static int open_playback_devices; static int open_capture_devices; static int num_open_devices; static SDL_AudioDevice **open_devices; #if !MACOSX_COREAUDIO static BOOL session_active = NO; static void pause_audio_devices() { int i; if (!open_devices) { return; } for (i = 0; i < num_open_devices; ++i) { SDL_AudioDevice *device = open_devices[i]; if (device->hidden->audioQueue && !device->hidden->interrupted) { AudioQueuePause(device->hidden->audioQueue); } } } static void resume_audio_devices() { int i; if (!open_devices) { return; } for (i = 0; i < num_open_devices; ++i) { SDL_AudioDevice *device = open_devices[i]; if (device->hidden->audioQueue && !device->hidden->interrupted) { AudioQueueStart(device->hidden->audioQueue, NULL); } } } static void interruption_begin(_THIS) { if (this != NULL && this->hidden->audioQueue != NULL) { this->hidden->interrupted = SDL_TRUE; AudioQueuePause(this->hidden->audioQueue); } } static void interruption_end(_THIS) { if (this != NULL && this->hidden != NULL && this->hidden->audioQueue != NULL && this->hidden->interrupted && AudioQueueStart(this->hidden->audioQueue, NULL) == AVAudioSessionErrorCodeNone) { this->hidden->interrupted = SDL_FALSE; } } @interface SDLInterruptionListener : NSObject @property (nonatomic, assign) SDL_AudioDevice *device; @end @implementation SDLInterruptionListener - (void)audioSessionInterruption:(NSNotification *)note { @synchronized (self) { NSNumber *type = note.userInfo[AVAudioSessionInterruptionTypeKey]; if (type.unsignedIntegerValue == AVAudioSessionInterruptionTypeBegan) { interruption_begin(self.device); } else { interruption_end(self.device); } } } - (void)applicationBecameActive:(NSNotification *)note { @synchronized (self) { interruption_end(self.device); } } @end static BOOL update_audio_session(_THIS, SDL_bool open, SDL_bool allow_playandrecord) { @autoreleasepool { AVAudioSession *session = [AVAudioSession sharedInstance]; NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; NSString *category = AVAudioSessionCategoryPlayback; NSString *mode = AVAudioSessionModeDefault; NSUInteger options = AVAudioSessionCategoryOptionMixWithOthers; NSError *err = nil; const char *hint; hint = SDL_GetHint(SDL_HINT_AUDIO_CATEGORY); if (hint) { if (SDL_strcasecmp(hint, "AVAudioSessionCategoryAmbient") == 0) { category = AVAudioSessionCategoryAmbient; } else if (SDL_strcasecmp(hint, "AVAudioSessionCategorySoloAmbient") == 0) { category = AVAudioSessionCategorySoloAmbient; options &= ~AVAudioSessionCategoryOptionMixWithOthers; } else if (SDL_strcasecmp(hint, "AVAudioSessionCategoryPlayback") == 0 || SDL_strcasecmp(hint, "playback") == 0) { category = AVAudioSessionCategoryPlayback; options &= ~AVAudioSessionCategoryOptionMixWithOthers; } else if (SDL_strcasecmp(hint, "AVAudioSessionCategoryPlayAndRecord") == 0 || SDL_strcasecmp(hint, "playandrecord") == 0) { if (allow_playandrecord) { category = AVAudioSessionCategoryPlayAndRecord; } } } else if (open_playback_devices && open_capture_devices) { category = AVAudioSessionCategoryPlayAndRecord; } else if (open_capture_devices) { category = AVAudioSessionCategoryRecord; } #if !TARGET_OS_TV if (category == AVAudioSessionCategoryPlayAndRecord) { options |= AVAudioSessionCategoryOptionDefaultToSpeaker; } #endif if (category == AVAudioSessionCategoryRecord || category == AVAudioSessionCategoryPlayAndRecord) { /* AVAudioSessionCategoryOptionAllowBluetooth isn't available in the SDK for Apple TV but is still needed in order to output to Bluetooth devices. */ options |= 0x4; /* AVAudioSessionCategoryOptionAllowBluetooth; */ } if (category == AVAudioSessionCategoryPlayAndRecord) { options |= AVAudioSessionCategoryOptionAllowBluetoothA2DP | AVAudioSessionCategoryOptionAllowAirPlay; } if (category == AVAudioSessionCategoryPlayback || category == AVAudioSessionCategoryPlayAndRecord) { options |= AVAudioSessionCategoryOptionDuckOthers; } if ([session respondsToSelector:@selector(setCategory:mode:options:error:)]) { if (![session.category isEqualToString:category] || session.categoryOptions != options) { /* Stop the current session so we don't interrupt other application audio */ pause_audio_devices(); [session setActive:NO error:nil]; session_active = NO; if (![session setCategory:category mode:mode options:options error:&err]) { NSString *desc = err.description; SDL_SetError("Could not set Audio Session category: %s", desc.UTF8String); return NO; } } } else { if (![session.category isEqualToString:category]) { /* Stop the current session so we don't interrupt other application audio */ pause_audio_devices(); [session setActive:NO error:nil]; session_active = NO; if (![session setCategory:category error:&err]) { NSString *desc = err.description; SDL_SetError("Could not set Audio Session category: %s", desc.UTF8String); return NO; } } } if ((open_playback_devices || open_capture_devices) && !session_active) { if (![session setActive:YES error:&err]) { if ([err code] == AVAudioSessionErrorCodeResourceNotAvailable && category == AVAudioSessionCategoryPlayAndRecord) { return update_audio_session(this, open, SDL_FALSE); } NSString *desc = err.description; SDL_SetError("Could not activate Audio Session: %s", desc.UTF8String); return NO; } session_active = YES; resume_audio_devices(); } else if (!open_playback_devices && !open_capture_devices && session_active) { pause_audio_devices(); [session setActive:NO error:nil]; session_active = NO; } if (open) { SDLInterruptionListener *listener = [SDLInterruptionListener new]; listener.device = this; [center addObserver:listener selector:@selector(audioSessionInterruption:) name:AVAudioSessionInterruptionNotification object:session]; /* An interruption end notification is not guaranteed to be sent if we were previously interrupted... resuming if needed when the app becomes active seems to be the way to go. */ // Note: object: below needs to be nil, as otherwise it filters by the object, and session doesn't send foreground / active notifications. johna [center addObserver:listener selector:@selector(applicationBecameActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; [center addObserver:listener selector:@selector(applicationBecameActive:) name:UIApplicationWillEnterForegroundNotification object:nil]; this->hidden->interruption_listener = CFBridgingRetain(listener); } else { SDLInterruptionListener *listener = nil; listener = (SDLInterruptionListener *) CFBridgingRelease(this->hidden->interruption_listener); [center removeObserver:listener]; @synchronized (listener) { listener.device = NULL; } } } return YES; } #endif /* The AudioQueue callback */ static void outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) { SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData; if (SDL_AtomicGet(&this->hidden->shutdown)) { return; /* don't do anything. */ } 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 if (this->stream) { UInt32 remaining = inBuffer->mAudioDataBytesCapacity; Uint8 *ptr = (Uint8 *) inBuffer->mAudioData; while (remaining > 0) { if (SDL_AudioStreamAvailable(this->stream) == 0) { /* 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; SDL_AudioStreamPut(this->stream, this->hidden->buffer, this->hidden->bufferSize); } if (SDL_AudioStreamAvailable(this->stream) > 0) { int got; UInt32 len = SDL_AudioStreamAvailable(this->stream); if (len > remaining) len = remaining; got = SDL_AudioStreamGet(this->stream, ptr, len); SDL_assert((got < 0) || (got == len)); if (got != len) { SDL_memset(ptr, this->spec.silence, len); } ptr = ptr + len; remaining -= len; } } } 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 inputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp *inStartTime, UInt32 inNumberPacketDescriptions, const AudioStreamPacketDescription *inPacketDescs) { SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData; if (SDL_AtomicGet(&this->shutdown)) { return; /* don't do anything. */ } /* 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; } 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; } } } AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL); } #if MACOSX_COREAUDIO static const AudioObjectPropertyAddress alive_address = { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; static OSStatus device_unplugged(AudioObjectID devid, UInt32 num_addr, const AudioObjectPropertyAddress *addrs, void *data) { SDL_AudioDevice *this = (SDL_AudioDevice *) data; SDL_bool dead = SDL_FALSE; UInt32 isAlive = 1; UInt32 size = sizeof (isAlive); OSStatus error; if (!SDL_AtomicGet(&this->enabled)) { return 0; /* already known to be dead. */ } error = AudioObjectGetPropertyData(this->hidden->deviceID, &alive_address, 0, NULL, &size, &isAlive); if (error == kAudioHardwareBadDeviceError) { dead = SDL_TRUE; /* device was unplugged. */ } else if ((error == kAudioHardwareNoError) && (!isAlive)) { dead = SDL_TRUE; /* device died in some other way. */ } if (dead) { SDL_OpenedAudioDeviceDisconnected(this); } return 0; } /* macOS calls this when the default device changed (if we have a default device open). */ static OSStatus default_device_changed(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses, void *inUserData) { SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData; #if DEBUG_COREAUDIO printf("COREAUDIO: default device changed for SDL audio device %p!\n", this); #endif SDL_AtomicSet(&this->hidden->device_change_flag, 1); /* let the audioqueue thread pick up on this when safe to do so. */ return noErr; } #endif static void COREAUDIO_CloseDevice(_THIS) { const SDL_bool iscapture = this->iscapture; int i; /* !!! FIXME: what does iOS do when a bluetooth audio device vanishes? Headphones unplugged? */ /* !!! FIXME: (we only do a "default" device on iOS right now...can we do more?) */ #if MACOSX_COREAUDIO if (this->handle != NULL) { /* we don't register this listener for default devices. */ AudioObjectRemovePropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this); } #endif if (iscapture) { open_capture_devices--; } else { open_playback_devices--; } #if !MACOSX_COREAUDIO update_audio_session(this, SDL_FALSE, SDL_TRUE); #endif for (i = 0; i < num_open_devices; ++i) { if (open_devices[i] == this) { --num_open_devices; if (i < num_open_devices) { SDL_memmove(&open_devices[i], &open_devices[i+1], sizeof(open_devices[i])*(num_open_devices - i)); } break; } } if (num_open_devices == 0) { SDL_free(open_devices); open_devices = NULL; } /* 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->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); } #if MACOSX_COREAUDIO static int prepare_device(_THIS, void *handle, int iscapture) { AudioDeviceID devid = (AudioDeviceID) ((size_t) handle); OSStatus result = noErr; UInt32 size = 0; UInt32 alive = 0; pid_t pid = 0; AudioObjectPropertyAddress addr = { 0, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; if (handle == NULL) { size = sizeof (AudioDeviceID); addr.mSelector = ((iscapture) ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice); result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, NULL, &size, &devid); CHECK_RESULT("AudioHardwareGetProperty (default device)"); } addr.mSelector = kAudioDevicePropertyDeviceIsAlive; addr.mScope = iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; size = sizeof (alive); result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &alive); CHECK_RESULT ("AudioDeviceGetProperty (kAudioDevicePropertyDeviceIsAlive)"); if (!alive) { SDL_SetError("CoreAudio: requested device exists, but isn't alive."); return 0; } addr.mSelector = kAudioDevicePropertyHogMode; size = sizeof (pid); result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &pid); /* some devices don't support this property, so errors are fine here. */ if ((result == noErr) && (pid != -1)) { SDL_SetError("CoreAudio: requested device is being hogged."); return 0; } this->hidden->deviceID = devid; return 1; } static int assign_device_to_audioqueue(_THIS) { const AudioObjectPropertyAddress prop = { kAudioDevicePropertyDeviceUID, this->iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMaster }; OSStatus result; CFStringRef devuid; UInt32 devuidsize = sizeof (devuid); result = AudioObjectGetPropertyData(this->hidden->deviceID, &prop, 0, NULL, &devuidsize, &devuid); CHECK_RESULT("AudioObjectGetPropertyData (kAudioDevicePropertyDeviceUID)"); result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_CurrentDevice, &devuid, devuidsize); CHECK_RESULT("AudioQueueSetProperty (kAudioQueueProperty_CurrentDevice)"); return 1; } #endif static int prepare_audioqueue(_THIS) { const AudioStreamBasicDescription *strdesc = &this->hidden->strdesc; const int iscapture = this->iscapture; OSStatus result; int i; SDL_assert(CFRunLoopGetCurrent() != NULL); if (iscapture) { result = AudioQueueNewInput(strdesc, inputCallback, this, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 0, &this->hidden->audioQueue); CHECK_RESULT("AudioQueueNewInput"); } else { result = AudioQueueNewOutput(strdesc, outputCallback, this, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 0, &this->hidden->audioQueue); CHECK_RESULT("AudioQueueNewOutput"); } #if MACOSX_COREAUDIO if (!assign_device_to_audioqueue(this)) { return 0; } /* only listen for unplugging on specific devices, not the default device, as that should switch to a different device (or hang out silently if there _is_ no other device). */ if (this->handle != NULL) { /* !!! FIXME: what does iOS do when a bluetooth audio device vanishes? Headphones unplugged? */ /* !!! FIXME: (we only do a "default" device on iOS right now...can we do more?) */ /* Fire a callback if the device stops being "alive" (disconnected, etc). */ /* If this fails, oh well, we won't notice a device had an extraordinary event take place. */ AudioObjectAddPropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this); } #endif /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&this->spec); /* Set the channel layout for the audio queue */ AudioChannelLayout layout; SDL_zero(layout); switch (this->spec.channels) { case 1: layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono; break; case 2: layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo; break; case 3: layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4; break; case 4: layout.mChannelLayoutTag = kAudioChannelLayoutTag_Quadraphonic; break; case 5: layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_5_0_A; break; case 6: layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_5_1_A; break; case 7: /* FIXME: Need to move channel[4] (BC) to channel[6] */ layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A; break; case 8: layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A; break; } if (layout.mChannelLayoutTag != 0) { result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_ChannelLayout, &layout, sizeof(layout)); CHECK_RESULT("AudioQueueSetProperty(kAudioQueueProperty_ChannelLayout)"); } /* 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__) if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) { /* Older iOS hardware, use 40 ms as a minimum time */ MINIMUM_AUDIO_BUFFER_TIME_MS = 40.0; } #endif const double msecs = (this->spec.samples / ((double) this->spec.freq)) * 1000.0; int numAudioBuffers = 2; if (msecs < MINIMUM_AUDIO_BUFFER_TIME_MS) { /* use more buffers if we have a VERY small sample set. */ 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(); return 0; } #if DEBUG_COREAUDIO printf("COREAUDIO: numAudioBuffers == %d\n", numAudioBuffers); #endif for (i = 0; i < numAudioBuffers; i++) { result = AudioQueueAllocateBuffer(this->hidden->audioQueue, this->spec.size, &this->hidden->audioBuffer[i]); CHECK_RESULT("AudioQueueAllocateBuffer"); SDL_memset(this->hidden->audioBuffer[i]->mAudioData, this->spec.silence, this->hidden->audioBuffer[i]->mAudioDataBytesCapacity); this->hidden->audioBuffer[i]->mAudioDataByteSize = this->hidden->audioBuffer[i]->mAudioDataBytesCapacity; /* !!! FIXME: should we use AudioQueueEnqueueBufferWithParameters and specify all frames be "trimmed" so these are immediately ready to refill with SDL callback data? */ result = AudioQueueEnqueueBuffer(this->hidden->audioQueue, this->hidden->audioBuffer[i], 0, NULL); CHECK_RESULT("AudioQueueEnqueueBuffer"); } result = AudioQueueStart(this->hidden->audioQueue, NULL); CHECK_RESULT("AudioQueueStart"); /* We're running! */ return 1; } static int audioqueue_thread(void *arg) { SDL_AudioDevice *this = (SDL_AudioDevice *) arg; #if MACOSX_COREAUDIO const AudioObjectPropertyAddress default_device_address = { this->iscapture ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; if (this->handle == NULL) { /* opened the default device? Register to know if the user picks a new default. */ /* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */ AudioObjectAddPropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this); } #endif const int rc = prepare_audioqueue(this); if (!rc) { this->hidden->thread_error = SDL_strdup(SDL_GetError()); SDL_SemPost(this->hidden->ready_semaphore); return 0; } SDL_SetThreadPriority(SDL_THREAD_PRIORITY_HIGH); /* 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 MACOSX_COREAUDIO if ((this->handle == NULL) && SDL_AtomicGet(&this->hidden->device_change_flag)) { SDL_AtomicSet(&this->hidden->device_change_flag, 0); #if DEBUG_COREAUDIO printf("COREAUDIO: audioqueue_thread is trying to switch to new default device!\n"); #endif /* if any of this fails, there's not much to do but wait to see if the user gives up and quits (flagging the audioqueue for shutdown), or toggles to some other system output device (in which case we'll try again). */ const AudioDeviceID prev_devid = this->hidden->deviceID; if (prepare_device(this, this->handle, this->iscapture) && (prev_devid != this->hidden->deviceID)) { AudioQueueStop(this->hidden->audioQueue, 1); if (assign_device_to_audioqueue(this)) { int i; for (i = 0; i < this->hidden->numAudioBuffers; i++) { SDL_memset(this->hidden->audioBuffer[i]->mAudioData, this->spec.silence, this->hidden->audioBuffer[i]->mAudioDataBytesCapacity); /* !!! FIXME: should we use AudioQueueEnqueueBufferWithParameters and specify all frames be "trimmed" so these are immediately ready to refill with SDL callback data? */ AudioQueueEnqueueBuffer(this->hidden->audioQueue, this->hidden->audioBuffer[i], 0, NULL); } AudioQueueStart(this->hidden->audioQueue, NULL); } } } #endif } 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); } #if MACOSX_COREAUDIO if (this->handle == NULL) { /* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */ AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this); } #endif return 0; } static int COREAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { AudioStreamBasicDescription *strdesc; SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format); int valid_datatype = 0; SDL_AudioDevice **new_open_devices; /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); strdesc = &this->hidden->strdesc; if (iscapture) { open_capture_devices++; } else { open_playback_devices++; } new_open_devices = (SDL_AudioDevice **)SDL_realloc(open_devices, sizeof(open_devices[0]) * (num_open_devices + 1)); if (new_open_devices) { open_devices = new_open_devices; open_devices[num_open_devices++] = this; } #if !MACOSX_COREAUDIO if (!update_audio_session(this, SDL_TRUE, SDL_TRUE)) { return -1; } /* Stop CoreAudio from doing expensive audio rate conversion */ @autoreleasepool { AVAudioSession* session = [AVAudioSession sharedInstance]; [session setPreferredSampleRate:this->spec.freq error:nil]; this->spec.freq = (int)session.sampleRate; #if TARGET_OS_TV if (iscapture) { [session setPreferredInputNumberOfChannels:this->spec.channels error:nil]; this->spec.channels = session.preferredInputNumberOfChannels; } else { [session setPreferredOutputNumberOfChannels:this->spec.channels error:nil]; this->spec.channels = session.preferredOutputNumberOfChannels; } #else /* Calling setPreferredOutputNumberOfChannels seems to break audio output on iOS */ #endif /* TARGET_OS_TV */ } #endif /* Setup a AudioStreamBasicDescription with the requested format */ SDL_zerop(strdesc); strdesc->mFormatID = kAudioFormatLinearPCM; strdesc->mFormatFlags = kLinearPCMFormatFlagIsPacked; strdesc->mChannelsPerFrame = this->spec.channels; strdesc->mSampleRate = this->spec.freq; strdesc->mFramesPerPacket = 1; while ((!valid_datatype) && (test_format)) { this->spec.format = test_format; /* CoreAudio handles most of SDL's formats natively, but not U16, apparently. */ switch (test_format) { case AUDIO_U8: case AUDIO_S8: case AUDIO_S16LSB: case AUDIO_S16MSB: case AUDIO_S32LSB: case AUDIO_S32MSB: case AUDIO_F32LSB: case AUDIO_F32MSB: valid_datatype = 1; strdesc->mBitsPerChannel = SDL_AUDIO_BITSIZE(this->spec.format); if (SDL_AUDIO_ISBIGENDIAN(this->spec.format)) strdesc->mFormatFlags |= kLinearPCMFormatFlagIsBigEndian; if (SDL_AUDIO_ISFLOAT(this->spec.format)) strdesc->mFormatFlags |= kLinearPCMFormatFlagIsFloat; else if (SDL_AUDIO_ISSIGNED(this->spec.format)) strdesc->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger; break; default: test_format = SDL_NextAudioFormat(); break; } } if (!valid_datatype) { /* shouldn't happen, but just in case... */ return SDL_SetError("Unsupported audio format"); } strdesc->mBytesPerFrame = strdesc->mChannelsPerFrame * strdesc->mBitsPerChannel / 8; strdesc->mBytesPerPacket = strdesc->mBytesPerFrame * strdesc->mFramesPerPacket; #if MACOSX_COREAUDIO if (!prepare_device(this, handle, iscapture)) { return -1; } #endif /* 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. */ } 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 COREAUDIO_Deinitialize(void) { #if MACOSX_COREAUDIO AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &devlist_address, device_list_changed, NULL); free_audio_device_list(&capture_devs); free_audio_device_list(&output_devs); #endif } static int COREAUDIO_Init(SDL_AudioDriverImpl * impl) { /* Set the function pointers */ impl->OpenDevice = COREAUDIO_OpenDevice; impl->CloseDevice = COREAUDIO_CloseDevice; impl->Deinitialize = COREAUDIO_Deinitialize; #if MACOSX_COREAUDIO impl->DetectDevices = COREAUDIO_DetectDevices; AudioObjectAddPropertyListener(kAudioObjectSystemObject, &devlist_address, device_list_changed, NULL); #else impl->OnlyHasDefaultOutputDevice = 1; impl->OnlyHasDefaultCaptureDevice = 1; #endif impl->ProvidesOwnCallbackThread = 1; impl->HasCaptureSupport = 1; return 1; /* this audio target is available. */ } AudioBootStrap COREAUDIO_bootstrap = { "coreaudio", "CoreAudio", COREAUDIO_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_COREAUDIO */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/coreaudio/SDL_coreaudio.m
Objective-C
apache-2.0
41,404
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_DSOUND /* Allow access to a raw mixing buffer */ #include "SDL_assert.h" #include "SDL_timer.h" #include "SDL_loadso.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_directsound.h" #ifndef WAVE_FORMAT_IEEE_FLOAT #define WAVE_FORMAT_IEEE_FLOAT 0x0003 #endif /* DirectX function pointers for audio */ static void* DSoundDLL = NULL; typedef HRESULT (WINAPI *fnDirectSoundCreate8)(LPGUID,LPDIRECTSOUND*,LPUNKNOWN); typedef HRESULT (WINAPI *fnDirectSoundEnumerateW)(LPDSENUMCALLBACKW, LPVOID); typedef HRESULT (WINAPI *fnDirectSoundCaptureCreate8)(LPCGUID,LPDIRECTSOUNDCAPTURE8 *,LPUNKNOWN); typedef HRESULT (WINAPI *fnDirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW,LPVOID); static fnDirectSoundCreate8 pDirectSoundCreate8 = NULL; static fnDirectSoundEnumerateW pDirectSoundEnumerateW = NULL; static fnDirectSoundCaptureCreate8 pDirectSoundCaptureCreate8 = NULL; static fnDirectSoundCaptureEnumerateW pDirectSoundCaptureEnumerateW = NULL; static void DSOUND_Unload(void) { pDirectSoundCreate8 = NULL; pDirectSoundEnumerateW = NULL; pDirectSoundCaptureCreate8 = NULL; pDirectSoundCaptureEnumerateW = NULL; if (DSoundDLL != NULL) { SDL_UnloadObject(DSoundDLL); DSoundDLL = NULL; } } static int DSOUND_Load(void) { int loaded = 0; DSOUND_Unload(); DSoundDLL = SDL_LoadObject("DSOUND.DLL"); if (DSoundDLL == NULL) { SDL_SetError("DirectSound: failed to load DSOUND.DLL"); } else { /* Now make sure we have DirectX 8 or better... */ #define DSOUNDLOAD(f) { \ p##f = (fn##f) SDL_LoadFunction(DSoundDLL, #f); \ if (!p##f) loaded = 0; \ } loaded = 1; /* will reset if necessary. */ DSOUNDLOAD(DirectSoundCreate8); DSOUNDLOAD(DirectSoundEnumerateW); DSOUNDLOAD(DirectSoundCaptureCreate8); DSOUNDLOAD(DirectSoundCaptureEnumerateW); #undef DSOUNDLOAD if (!loaded) { SDL_SetError("DirectSound: System doesn't appear to have DX8."); } } if (!loaded) { DSOUND_Unload(); } return loaded; } static int SetDSerror(const char *function, int code) { static const char *error; static char errbuf[1024]; errbuf[0] = 0; switch (code) { case E_NOINTERFACE: error = "Unsupported interface -- Is DirectX 8.0 or later installed?"; break; case DSERR_ALLOCATED: error = "Audio device in use"; break; case DSERR_BADFORMAT: error = "Unsupported audio format"; break; case DSERR_BUFFERLOST: error = "Mixing buffer was lost"; break; case DSERR_CONTROLUNAVAIL: error = "Control requested is not available"; break; case DSERR_INVALIDCALL: error = "Invalid call for the current state"; break; case DSERR_INVALIDPARAM: error = "Invalid parameter"; break; case DSERR_NODRIVER: error = "No audio device found"; break; case DSERR_OUTOFMEMORY: error = "Out of memory"; break; case DSERR_PRIOLEVELNEEDED: error = "Caller doesn't have priority"; break; case DSERR_UNSUPPORTED: error = "Function not supported"; break; default: SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: Unknown DirectSound error: 0x%x", function, code); break; } if (!errbuf[0]) { SDL_snprintf(errbuf, SDL_arraysize(errbuf), "%s: %s", function, error); } return SDL_SetError("%s", errbuf); } static void DSOUND_FreeDeviceHandle(void *handle) { SDL_free(handle); } static BOOL CALLBACK FindAllDevs(LPGUID guid, LPCWSTR desc, LPCWSTR module, LPVOID data) { const int iscapture = (int) ((size_t) data); if (guid != NULL) { /* skip default device */ char *str = WIN_LookupAudioDeviceName(desc, guid); if (str != NULL) { LPGUID cpyguid = (LPGUID) SDL_malloc(sizeof (GUID)); SDL_memcpy(cpyguid, guid, sizeof (GUID)); SDL_AddAudioDevice(iscapture, str, cpyguid); SDL_free(str); /* addfn() makes a copy of this string. */ } } return TRUE; /* keep enumerating. */ } static void DSOUND_DetectDevices(void) { pDirectSoundCaptureEnumerateW(FindAllDevs, (void *) ((size_t) 1)); pDirectSoundEnumerateW(FindAllDevs, (void *) ((size_t) 0)); } static void DSOUND_WaitDevice(_THIS) { DWORD status = 0; DWORD cursor = 0; DWORD junk = 0; HRESULT result = DS_OK; /* Semi-busy wait, since we have no way of getting play notification on a primary mixing buffer located in hardware (DirectX 5.0) */ result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, &junk, &cursor); if (result != DS_OK) { if (result == DSERR_BUFFERLOST) { IDirectSoundBuffer_Restore(this->hidden->mixbuf); } #ifdef DEBUG_SOUND SetDSerror("DirectSound GetCurrentPosition", result); #endif return; } while ((cursor / this->spec.size) == this->hidden->lastchunk) { /* FIXME: find out how much time is left and sleep that long */ SDL_Delay(1); /* Try to restore a lost sound buffer */ IDirectSoundBuffer_GetStatus(this->hidden->mixbuf, &status); if ((status & DSBSTATUS_BUFFERLOST)) { IDirectSoundBuffer_Restore(this->hidden->mixbuf); IDirectSoundBuffer_GetStatus(this->hidden->mixbuf, &status); if ((status & DSBSTATUS_BUFFERLOST)) { break; } } if (!(status & DSBSTATUS_PLAYING)) { result = IDirectSoundBuffer_Play(this->hidden->mixbuf, 0, 0, DSBPLAY_LOOPING); if (result == DS_OK) { continue; } #ifdef DEBUG_SOUND SetDSerror("DirectSound Play", result); #endif return; } /* Find out where we are playing */ result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, &junk, &cursor); if (result != DS_OK) { SetDSerror("DirectSound GetCurrentPosition", result); return; } } } static void DSOUND_PlayDevice(_THIS) { /* Unlock the buffer, allowing it to play */ if (this->hidden->locked_buf) { IDirectSoundBuffer_Unlock(this->hidden->mixbuf, this->hidden->locked_buf, this->spec.size, NULL, 0); } } static Uint8 * DSOUND_GetDeviceBuf(_THIS) { DWORD cursor = 0; DWORD junk = 0; HRESULT result = DS_OK; DWORD rawlen = 0; /* Figure out which blocks to fill next */ this->hidden->locked_buf = NULL; result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, &junk, &cursor); if (result == DSERR_BUFFERLOST) { IDirectSoundBuffer_Restore(this->hidden->mixbuf); result = IDirectSoundBuffer_GetCurrentPosition(this->hidden->mixbuf, &junk, &cursor); } if (result != DS_OK) { SetDSerror("DirectSound GetCurrentPosition", result); return (NULL); } cursor /= this->spec.size; #ifdef DEBUG_SOUND /* Detect audio dropouts */ { DWORD spot = cursor; if (spot < this->hidden->lastchunk) { spot += this->hidden->num_buffers; } if (spot > this->hidden->lastchunk + 1) { fprintf(stderr, "Audio dropout, missed %d fragments\n", (spot - (this->hidden->lastchunk + 1))); } } #endif this->hidden->lastchunk = cursor; cursor = (cursor + 1) % this->hidden->num_buffers; cursor *= this->spec.size; /* Lock the audio buffer */ result = IDirectSoundBuffer_Lock(this->hidden->mixbuf, cursor, this->spec.size, (LPVOID *) & this->hidden->locked_buf, &rawlen, NULL, &junk, 0); if (result == DSERR_BUFFERLOST) { IDirectSoundBuffer_Restore(this->hidden->mixbuf); result = IDirectSoundBuffer_Lock(this->hidden->mixbuf, cursor, this->spec.size, (LPVOID *) & this-> hidden->locked_buf, &rawlen, NULL, &junk, 0); } if (result != DS_OK) { SetDSerror("DirectSound Lock", result); return (NULL); } return (this->hidden->locked_buf); } static int DSOUND_CaptureFromDevice(_THIS, void *buffer, int buflen) { struct SDL_PrivateAudioData *h = this->hidden; DWORD junk, cursor, ptr1len, ptr2len; VOID *ptr1, *ptr2; SDL_assert(buflen == this->spec.size); while (SDL_TRUE) { if (SDL_AtomicGet(&this->shutdown)) { /* in case the buffer froze... */ SDL_memset(buffer, this->spec.silence, buflen); return buflen; } if (IDirectSoundCaptureBuffer_GetCurrentPosition(h->capturebuf, &junk, &cursor) != DS_OK) { return -1; } if ((cursor / this->spec.size) == h->lastchunk) { SDL_Delay(1); /* FIXME: find out how much time is left and sleep that long */ } else { break; } } if (IDirectSoundCaptureBuffer_Lock(h->capturebuf, h->lastchunk * this->spec.size, this->spec.size, &ptr1, &ptr1len, &ptr2, &ptr2len, 0) != DS_OK) { return -1; } SDL_assert(ptr1len == this->spec.size); SDL_assert(ptr2 == NULL); SDL_assert(ptr2len == 0); SDL_memcpy(buffer, ptr1, ptr1len); if (IDirectSoundCaptureBuffer_Unlock(h->capturebuf, ptr1, ptr1len, ptr2, ptr2len) != DS_OK) { return -1; } h->lastchunk = (h->lastchunk + 1) % h->num_buffers; return ptr1len; } static void DSOUND_FlushCapture(_THIS) { struct SDL_PrivateAudioData *h = this->hidden; DWORD junk, cursor; if (IDirectSoundCaptureBuffer_GetCurrentPosition(h->capturebuf, &junk, &cursor) == DS_OK) { h->lastchunk = cursor / this->spec.size; } } static void DSOUND_CloseDevice(_THIS) { if (this->hidden->mixbuf != NULL) { IDirectSoundBuffer_Stop(this->hidden->mixbuf); IDirectSoundBuffer_Release(this->hidden->mixbuf); } if (this->hidden->sound != NULL) { IDirectSound_Release(this->hidden->sound); } if (this->hidden->capturebuf != NULL) { IDirectSoundCaptureBuffer_Stop(this->hidden->capturebuf); IDirectSoundCaptureBuffer_Release(this->hidden->capturebuf); } if (this->hidden->capture != NULL) { IDirectSoundCapture_Release(this->hidden->capture); } SDL_free(this->hidden); } /* This function tries to create a secondary audio buffer, and returns the number of audio chunks available in the created buffer. This is for playback devices, not capture. */ static int CreateSecondary(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt) { LPDIRECTSOUND sndObj = this->hidden->sound; LPDIRECTSOUNDBUFFER *sndbuf = &this->hidden->mixbuf; HRESULT result = DS_OK; DSBUFFERDESC format; LPVOID pvAudioPtr1, pvAudioPtr2; DWORD dwAudioBytes1, dwAudioBytes2; /* Try to create the secondary buffer */ SDL_zero(format); format.dwSize = sizeof(format); format.dwFlags = DSBCAPS_GETCURRENTPOSITION2; format.dwFlags |= DSBCAPS_GLOBALFOCUS; format.dwBufferBytes = bufsize; format.lpwfxFormat = wfmt; result = IDirectSound_CreateSoundBuffer(sndObj, &format, sndbuf, NULL); if (result != DS_OK) { return SetDSerror("DirectSound CreateSoundBuffer", result); } IDirectSoundBuffer_SetFormat(*sndbuf, wfmt); /* Silence the initial audio buffer */ result = IDirectSoundBuffer_Lock(*sndbuf, 0, format.dwBufferBytes, (LPVOID *) & pvAudioPtr1, &dwAudioBytes1, (LPVOID *) & pvAudioPtr2, &dwAudioBytes2, DSBLOCK_ENTIREBUFFER); if (result == DS_OK) { SDL_memset(pvAudioPtr1, this->spec.silence, dwAudioBytes1); IDirectSoundBuffer_Unlock(*sndbuf, (LPVOID) pvAudioPtr1, dwAudioBytes1, (LPVOID) pvAudioPtr2, dwAudioBytes2); } /* We're ready to go */ return 0; } /* This function tries to create a capture buffer, and returns the number of audio chunks available in the created buffer. This is for capture devices, not playback. */ static int CreateCaptureBuffer(_THIS, const DWORD bufsize, WAVEFORMATEX *wfmt) { LPDIRECTSOUNDCAPTURE capture = this->hidden->capture; LPDIRECTSOUNDCAPTUREBUFFER *capturebuf = &this->hidden->capturebuf; DSCBUFFERDESC format; HRESULT result; SDL_zero(format); format.dwSize = sizeof (format); format.dwFlags = DSCBCAPS_WAVEMAPPED; format.dwBufferBytes = bufsize; format.lpwfxFormat = wfmt; result = IDirectSoundCapture_CreateCaptureBuffer(capture, &format, capturebuf, NULL); if (result != DS_OK) { return SetDSerror("DirectSound CreateCaptureBuffer", result); } result = IDirectSoundCaptureBuffer_Start(*capturebuf, DSCBSTART_LOOPING); if (result != DS_OK) { IDirectSoundCaptureBuffer_Release(*capturebuf); return SetDSerror("DirectSound Start", result); } #if 0 /* presumably this starts at zero, but just in case... */ result = IDirectSoundCaptureBuffer_GetCurrentPosition(*capturebuf, &junk, &cursor); if (result != DS_OK) { IDirectSoundCaptureBuffer_Stop(*capturebuf); IDirectSoundCaptureBuffer_Release(*capturebuf); return SetDSerror("DirectSound GetCurrentPosition", result); } this->hidden->lastchunk = cursor / this->spec.size; #endif return 0; } static int DSOUND_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { const DWORD numchunks = 8; HRESULT result; SDL_bool valid_format = SDL_FALSE; SDL_bool tried_format = SDL_FALSE; SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format); LPGUID guid = (LPGUID) handle; DWORD bufsize; /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); /* Open the audio device */ if (iscapture) { result = pDirectSoundCaptureCreate8(guid, &this->hidden->capture, NULL); if (result != DS_OK) { return SetDSerror("DirectSoundCaptureCreate8", result); } } else { result = pDirectSoundCreate8(guid, &this->hidden->sound, NULL); if (result != DS_OK) { return SetDSerror("DirectSoundCreate8", result); } result = IDirectSound_SetCooperativeLevel(this->hidden->sound, GetDesktopWindow(), DSSCL_NORMAL); if (result != DS_OK) { return SetDSerror("DirectSound SetCooperativeLevel", result); } } while ((!valid_format) && (test_format)) { switch (test_format) { case AUDIO_U8: case AUDIO_S16: case AUDIO_S32: case AUDIO_F32: tried_format = SDL_TRUE; this->spec.format = test_format; /* Update the fragment size as size in bytes */ SDL_CalculateAudioSpec(&this->spec); bufsize = numchunks * this->spec.size; if ((bufsize < DSBSIZE_MIN) || (bufsize > DSBSIZE_MAX)) { SDL_SetError("Sound buffer size must be between %d and %d", (int) ((DSBSIZE_MIN < numchunks) ? 1 : DSBSIZE_MIN / numchunks), (int) (DSBSIZE_MAX / numchunks)); } else { int rc; WAVEFORMATEX wfmt; SDL_zero(wfmt); if (SDL_AUDIO_ISFLOAT(this->spec.format)) { wfmt.wFormatTag = WAVE_FORMAT_IEEE_FLOAT; } else { wfmt.wFormatTag = WAVE_FORMAT_PCM; } wfmt.wBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format); wfmt.nChannels = this->spec.channels; wfmt.nSamplesPerSec = this->spec.freq; wfmt.nBlockAlign = wfmt.nChannels * (wfmt.wBitsPerSample / 8); wfmt.nAvgBytesPerSec = wfmt.nSamplesPerSec * wfmt.nBlockAlign; rc = iscapture ? CreateCaptureBuffer(this, bufsize, &wfmt) : CreateSecondary(this, bufsize, &wfmt); if (rc == 0) { this->hidden->num_buffers = numchunks; valid_format = SDL_TRUE; } } break; } test_format = SDL_NextAudioFormat(); } if (!valid_format) { if (tried_format) { return -1; /* CreateSecondary() should have called SDL_SetError(). */ } return SDL_SetError("DirectSound: Unsupported audio format"); } /* Playback buffers will auto-start playing in DSOUND_WaitDevice() */ return 0; /* good to go. */ } static void DSOUND_Deinitialize(void) { DSOUND_Unload(); } static int DSOUND_Init(SDL_AudioDriverImpl * impl) { if (!DSOUND_Load()) { return 0; } /* Set the function pointers */ impl->DetectDevices = DSOUND_DetectDevices; impl->OpenDevice = DSOUND_OpenDevice; impl->PlayDevice = DSOUND_PlayDevice; impl->WaitDevice = DSOUND_WaitDevice; impl->GetDeviceBuf = DSOUND_GetDeviceBuf; impl->CaptureFromDevice = DSOUND_CaptureFromDevice; impl->FlushCapture = DSOUND_FlushCapture; impl->CloseDevice = DSOUND_CloseDevice; impl->FreeDeviceHandle = DSOUND_FreeDeviceHandle; impl->Deinitialize = DSOUND_Deinitialize; impl->HasCaptureSupport = SDL_TRUE; return 1; /* this audio target is available. */ } AudioBootStrap DSOUND_bootstrap = { "directsound", "DirectSound", DSOUND_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_DSOUND */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/directsound/SDL_directsound.c
C
apache-2.0
19,516
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_directsound_h_ #define SDL_directsound_h_ #include "../../core/windows/SDL_directx.h" #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this /* The DirectSound objects */ struct SDL_PrivateAudioData { LPDIRECTSOUND sound; LPDIRECTSOUNDBUFFER mixbuf; LPDIRECTSOUNDCAPTURE capture; LPDIRECTSOUNDCAPTUREBUFFER capturebuf; int num_buffers; DWORD lastchunk; Uint8 *locked_buf; }; #endif /* SDL_directsound_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/directsound/SDL_directsound.h
C
apache-2.0
1,524
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_DISK /* Output raw audio data to a file. */ #if HAVE_STDIO_H #include <stdio.h> #endif #include "SDL_rwops.h" #include "SDL_timer.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_diskaudio.h" /* !!! FIXME: these should be SDL hints, not environment variables. */ /* environment variables and defaults. */ #define DISKENVR_OUTFILE "SDL_DISKAUDIOFILE" #define DISKDEFAULT_OUTFILE "sdlaudio.raw" #define DISKENVR_INFILE "SDL_DISKAUDIOFILEIN" #define DISKDEFAULT_INFILE "sdlaudio-in.raw" #define DISKENVR_IODELAY "SDL_DISKAUDIODELAY" /* This function waits until it is possible to write a full sound buffer */ static void DISKAUDIO_WaitDevice(_THIS) { SDL_Delay(this->hidden->io_delay); } static void DISKAUDIO_PlayDevice(_THIS) { const size_t written = SDL_RWwrite(this->hidden->io, this->hidden->mixbuf, 1, this->spec.size); /* If we couldn't write, assume fatal error for now */ if (written != this->spec.size) { SDL_OpenedAudioDeviceDisconnected(this); } #ifdef DEBUG_AUDIO fprintf(stderr, "Wrote %d bytes of audio data\n", written); #endif } static Uint8 * DISKAUDIO_GetDeviceBuf(_THIS) { return (this->hidden->mixbuf); } static int DISKAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen) { struct SDL_PrivateAudioData *h = this->hidden; const int origbuflen = buflen; SDL_Delay(h->io_delay); if (h->io) { const size_t br = SDL_RWread(h->io, buffer, 1, buflen); buflen -= (int) br; buffer = ((Uint8 *) buffer) + br; if (buflen > 0) { /* EOF (or error, but whatever). */ SDL_RWclose(h->io); h->io = NULL; } } /* if we ran out of file, just write silence. */ SDL_memset(buffer, this->spec.silence, buflen); return origbuflen; } static void DISKAUDIO_FlushCapture(_THIS) { /* no op...we don't advance the file pointer or anything. */ } static void DISKAUDIO_CloseDevice(_THIS) { if (this->hidden->io != NULL) { SDL_RWclose(this->hidden->io); } SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); } static const char * get_filename(const int iscapture, const char *devname) { if (devname == NULL) { devname = SDL_getenv(iscapture ? DISKENVR_INFILE : DISKENVR_OUTFILE); if (devname == NULL) { devname = iscapture ? DISKDEFAULT_INFILE : DISKDEFAULT_OUTFILE; } } return devname; } static int DISKAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { /* handle != NULL means "user specified the placeholder name on the fake detected device list" */ const char *fname = get_filename(iscapture, handle ? NULL : devname); const char *envr = SDL_getenv(DISKENVR_IODELAY); this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc(sizeof(*this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); if (envr != NULL) { this->hidden->io_delay = SDL_atoi(envr); } else { this->hidden->io_delay = ((this->spec.samples * 1000) / this->spec.freq); } /* Open the audio device */ this->hidden->io = SDL_RWFromFile(fname, iscapture ? "rb" : "wb"); if (this->hidden->io == NULL) { return -1; } /* Allocate mixing buffer */ if (!iscapture) { this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->spec.size); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); } SDL_LogCritical(SDL_LOG_CATEGORY_AUDIO, "You are using the SDL disk i/o audio driver!\n"); SDL_LogCritical(SDL_LOG_CATEGORY_AUDIO, " %s file [%s].\n", iscapture ? "Reading from" : "Writing to", fname); /* We're ready to rock and roll. :-) */ return 0; } static void DISKAUDIO_DetectDevices(void) { SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, (void *) 0x1); SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, (void *) 0x2); } static int DISKAUDIO_Init(SDL_AudioDriverImpl * impl) { /* Set the function pointers */ impl->OpenDevice = DISKAUDIO_OpenDevice; impl->WaitDevice = DISKAUDIO_WaitDevice; impl->PlayDevice = DISKAUDIO_PlayDevice; impl->GetDeviceBuf = DISKAUDIO_GetDeviceBuf; impl->CaptureFromDevice = DISKAUDIO_CaptureFromDevice; impl->FlushCapture = DISKAUDIO_FlushCapture; impl->CloseDevice = DISKAUDIO_CloseDevice; impl->DetectDevices = DISKAUDIO_DetectDevices; impl->AllowsArbitraryDeviceNames = 1; impl->HasCaptureSupport = SDL_TRUE; return 1; /* this audio target is available. */ } AudioBootStrap DISKAUDIO_bootstrap = { "disk", "direct-to-disk audio", DISKAUDIO_Init, 1 }; #endif /* SDL_AUDIO_DRIVER_DISK */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/disk/SDL_diskaudio.c
C
apache-2.0
5,996
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_diskaudio_h_ #define SDL_diskaudio_h_ #include "SDL_rwops.h" #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The file descriptor for the audio device */ SDL_RWops *io; Uint32 io_delay; Uint8 *mixbuf; }; #endif /* SDL_diskaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/disk/SDL_diskaudio.h
C
apache-2.0
1,376
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_OSS /* Allow access to a raw mixing buffer */ #include <stdio.h> /* For perror() */ #include <string.h> /* For strerror() */ #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <sys/time.h> #include <sys/ioctl.h> #include <sys/stat.h> #if SDL_AUDIO_DRIVER_OSS_SOUNDCARD_H /* This is installed on some systems */ #include <soundcard.h> #else /* This is recommended by OSS */ #include <sys/soundcard.h> #endif #include "SDL_timer.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "../SDL_audiodev_c.h" #include "SDL_dspaudio.h" static void DSP_DetectDevices(void) { SDL_EnumUnixAudioDevices(0, NULL); } static void DSP_CloseDevice(_THIS) { if (this->hidden->audio_fd >= 0) { close(this->hidden->audio_fd); } SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); } static int DSP_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { const int flags = ((iscapture) ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT); int format; int value; int frag_spec; SDL_AudioFormat test_format; /* We don't care what the devname is...we'll try to open anything. */ /* ...but default to first name in the list... */ if (devname == NULL) { devname = SDL_GetAudioDeviceName(0, iscapture); if (devname == NULL) { return SDL_SetError("No such audio device"); } } /* Make sure fragment size stays a power of 2, or OSS fails. */ /* I don't know which of these are actually legal values, though... */ if (this->spec.channels > 8) this->spec.channels = 8; else if (this->spec.channels > 4) this->spec.channels = 4; else if (this->spec.channels > 2) this->spec.channels = 2; /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); /* Open the audio device */ this->hidden->audio_fd = open(devname, flags, 0); if (this->hidden->audio_fd < 0) { return SDL_SetError("Couldn't open %s: %s", devname, strerror(errno)); } /* Make the file descriptor use blocking i/o with fcntl() */ { long ctlflags; ctlflags = fcntl(this->hidden->audio_fd, F_GETFL); ctlflags &= ~O_NONBLOCK; if (fcntl(this->hidden->audio_fd, F_SETFL, ctlflags) < 0) { return SDL_SetError("Couldn't set audio blocking mode"); } } /* Get a list of supported hardware formats */ if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0) { perror("SNDCTL_DSP_GETFMTS"); return SDL_SetError("Couldn't get audio format list"); } /* Try for a closest match on audio format */ format = 0; for (test_format = SDL_FirstAudioFormat(this->spec.format); !format && test_format;) { #ifdef DEBUG_AUDIO fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif switch (test_format) { case AUDIO_U8: if (value & AFMT_U8) { format = AFMT_U8; } break; case AUDIO_S16LSB: if (value & AFMT_S16_LE) { format = AFMT_S16_LE; } break; case AUDIO_S16MSB: if (value & AFMT_S16_BE) { format = AFMT_S16_BE; } break; #if 0 /* * These formats are not used by any real life systems so they are not * needed here. */ case AUDIO_S8: if (value & AFMT_S8) { format = AFMT_S8; } break; case AUDIO_U16LSB: if (value & AFMT_U16_LE) { format = AFMT_U16_LE; } break; case AUDIO_U16MSB: if (value & AFMT_U16_BE) { format = AFMT_U16_BE; } break; #endif default: format = 0; break; } if (!format) { test_format = SDL_NextAudioFormat(); } } if (format == 0) { return SDL_SetError("Couldn't find any hardware audio formats"); } this->spec.format = test_format; /* Set the audio format */ value = format; if ((ioctl(this->hidden->audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || (value != format)) { perror("SNDCTL_DSP_SETFMT"); return SDL_SetError("Couldn't set audio format"); } /* Set the number of channels of output */ value = this->spec.channels; if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_CHANNELS, &value) < 0) { perror("SNDCTL_DSP_CHANNELS"); return SDL_SetError("Cannot set the number of channels"); } this->spec.channels = value; /* Set the DSP frequency */ value = this->spec.freq; if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_SPEED, &value) < 0) { perror("SNDCTL_DSP_SPEED"); return SDL_SetError("Couldn't set audio frequency"); } this->spec.freq = value; /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&this->spec); /* Determine the power of two of the fragment size */ for (frag_spec = 0; (0x01U << frag_spec) < this->spec.size; ++frag_spec); if ((0x01U << frag_spec) != this->spec.size) { return SDL_SetError("Fragment size must be a power of two"); } frag_spec |= 0x00020000; /* two fragments, for low latency */ /* Set the audio buffering parameters */ #ifdef DEBUG_AUDIO fprintf(stderr, "Requesting %d fragments of size %d\n", (frag_spec >> 16), 1 << (frag_spec & 0xFFFF)); #endif if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0) { perror("SNDCTL_DSP_SETFRAGMENT"); } #ifdef DEBUG_AUDIO { audio_buf_info info; ioctl(this->hidden->audio_fd, SNDCTL_DSP_GETOSPACE, &info); fprintf(stderr, "fragments = %d\n", info.fragments); fprintf(stderr, "fragstotal = %d\n", info.fragstotal); fprintf(stderr, "fragsize = %d\n", info.fragsize); fprintf(stderr, "bytes = %d\n", info.bytes); } #endif /* Allocate mixing buffer */ if (!iscapture) { this->hidden->mixlen = this->spec.size; this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); } /* We're ready to rock and roll. :-) */ return 0; } static void DSP_PlayDevice(_THIS) { struct SDL_PrivateAudioData *h = this->hidden; if (write(h->audio_fd, h->mixbuf, h->mixlen) == -1) { perror("Audio write"); SDL_OpenedAudioDeviceDisconnected(this); } #ifdef DEBUG_AUDIO fprintf(stderr, "Wrote %d bytes of audio data\n", h->mixlen); #endif } static Uint8 * DSP_GetDeviceBuf(_THIS) { return (this->hidden->mixbuf); } static int DSP_CaptureFromDevice(_THIS, void *buffer, int buflen) { return (int) read(this->hidden->audio_fd, buffer, buflen); } static void DSP_FlushCapture(_THIS) { struct SDL_PrivateAudioData *h = this->hidden; audio_buf_info info; if (ioctl(h->audio_fd, SNDCTL_DSP_GETISPACE, &info) == 0) { while (info.bytes > 0) { char buf[512]; const size_t len = SDL_min(sizeof (buf), info.bytes); const ssize_t br = read(h->audio_fd, buf, len); if (br <= 0) { break; } info.bytes -= br; } } } static int DSP_Init(SDL_AudioDriverImpl * impl) { /* Set the function pointers */ impl->DetectDevices = DSP_DetectDevices; impl->OpenDevice = DSP_OpenDevice; impl->PlayDevice = DSP_PlayDevice; impl->GetDeviceBuf = DSP_GetDeviceBuf; impl->CloseDevice = DSP_CloseDevice; impl->CaptureFromDevice = DSP_CaptureFromDevice; impl->FlushCapture = DSP_FlushCapture; impl->AllowsArbitraryDeviceNames = 1; impl->HasCaptureSupport = SDL_TRUE; return 1; /* this audio target is available. */ } AudioBootStrap DSP_bootstrap = { "dsp", "OSS /dev/dsp standard audio", DSP_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_OSS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/dsp/SDL_dspaudio.c
C
apache-2.0
9,394
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_dspaudio_h_ #define SDL_dspaudio_h_ #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The file descriptor for the audio device */ int audio_fd; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; }; #define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ #endif /* SDL_dspaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/dsp/SDL_dspaudio.h
C
apache-2.0
1,446
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" /* Output audio to nowhere... */ #include "SDL_timer.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_dummyaudio.h" static int DUMMYAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { return 0; /* always succeeds. */ } static int DUMMYAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen) { /* Delay to make this sort of simulate real audio input. */ SDL_Delay((this->spec.samples * 1000) / this->spec.freq); /* always return a full buffer of silence. */ SDL_memset(buffer, this->spec.silence, buflen); return buflen; } static int DUMMYAUDIO_Init(SDL_AudioDriverImpl * impl) { /* Set the function pointers */ impl->OpenDevice = DUMMYAUDIO_OpenDevice; impl->CaptureFromDevice = DUMMYAUDIO_CaptureFromDevice; impl->OnlyHasDefaultOutputDevice = 1; impl->OnlyHasDefaultCaptureDevice = 1; impl->HasCaptureSupport = SDL_TRUE; return 1; /* this audio target is available. */ } AudioBootStrap DUMMYAUDIO_bootstrap = { "dummy", "SDL dummy audio driver", DUMMYAUDIO_Init, 1 }; /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/dummy/SDL_dummyaudio.c
C
apache-2.0
2,105
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_dummyaudio_h_ #define SDL_dummyaudio_h_ #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The file descriptor for the audio device */ Uint8 *mixbuf; Uint32 mixlen; Uint32 write_delay; Uint32 initial_calls; }; #endif /* SDL_dummyaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/dummy/SDL_dummyaudio.h
C
apache-2.0
1,385
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_EMSCRIPTEN #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_emscriptenaudio.h" #include "SDL_assert.h" #include <emscripten/emscripten.h> static void FeedAudioDevice(_THIS, const void *buf, const int buflen) { const int framelen = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels; EM_ASM_ARGS({ var SDL2 = Module['SDL2']; var numChannels = SDL2.audio.currentOutputBuffer['numberOfChannels']; for (var c = 0; c < numChannels; ++c) { var channelData = SDL2.audio.currentOutputBuffer['getChannelData'](c); if (channelData.length != $1) { throw 'Web Audio output buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!'; } for (var j = 0; j < $1; ++j) { channelData[j] = HEAPF32[$0 + ((j*numChannels + c) << 2) >> 2]; /* !!! FIXME: why are these shifts here? */ } } }, buf, buflen / framelen); } static void HandleAudioProcess(_THIS) { SDL_AudioCallback callback = this->callbackspec.callback; const int stream_len = this->callbackspec.size; /* Only do something if audio is enabled */ if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) { if (this->stream) { SDL_AudioStreamClear(this->stream); } return; } if (this->stream == NULL) { /* no conversion necessary. */ SDL_assert(this->spec.size == stream_len); callback(this->callbackspec.userdata, this->work_buffer, stream_len); } else { /* streaming/converting */ int got; while (SDL_AudioStreamAvailable(this->stream) < ((int) this->spec.size)) { callback(this->callbackspec.userdata, this->work_buffer, stream_len); if (SDL_AudioStreamPut(this->stream, this->work_buffer, stream_len) == -1) { SDL_AudioStreamClear(this->stream); SDL_AtomicSet(&this->enabled, 0); break; } } got = SDL_AudioStreamGet(this->stream, this->work_buffer, this->spec.size); SDL_assert((got < 0) || (got == this->spec.size)); if (got != this->spec.size) { SDL_memset(this->work_buffer, this->spec.silence, this->spec.size); } } FeedAudioDevice(this, this->work_buffer, this->spec.size); } static void HandleCaptureProcess(_THIS) { SDL_AudioCallback callback = this->callbackspec.callback; const int stream_len = this->callbackspec.size; /* Only do something if audio is enabled */ if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) { SDL_AudioStreamClear(this->stream); return; } EM_ASM_ARGS({ var SDL2 = Module['SDL2']; var numChannels = SDL2.capture.currentCaptureBuffer.numberOfChannels; for (var c = 0; c < numChannels; ++c) { var channelData = SDL2.capture.currentCaptureBuffer.getChannelData(c); if (channelData.length != $1) { throw 'Web Audio capture buffer length mismatch! Destination size: ' + channelData.length + ' samples vs expected ' + $1 + ' samples!'; } if (numChannels == 1) { /* fastpath this a little for the common (mono) case. */ for (var j = 0; j < $1; ++j) { setValue($0 + (j * 4), channelData[j], 'float'); } } else { for (var j = 0; j < $1; ++j) { setValue($0 + (((j * numChannels) + c) * 4), channelData[j], 'float'); } } } }, this->work_buffer, (this->spec.size / sizeof (float)) / this->spec.channels); /* okay, we've got an interleaved float32 array in C now. */ if (this->stream == NULL) { /* no conversion necessary. */ SDL_assert(this->spec.size == stream_len); callback(this->callbackspec.userdata, this->work_buffer, stream_len); } else { /* streaming/converting */ if (SDL_AudioStreamPut(this->stream, this->work_buffer, this->spec.size) == -1) { SDL_AtomicSet(&this->enabled, 0); } while (SDL_AudioStreamAvailable(this->stream) >= stream_len) { const int got = SDL_AudioStreamGet(this->stream, this->work_buffer, stream_len); SDL_assert((got < 0) || (got == stream_len)); if (got != stream_len) { SDL_memset(this->work_buffer, this->callbackspec.silence, stream_len); } callback(this->callbackspec.userdata, this->work_buffer, stream_len); /* Send it to the app. */ } } } static void EMSCRIPTENAUDIO_CloseDevice(_THIS) { EM_ASM_({ var SDL2 = Module['SDL2']; if ($0) { if (SDL2.capture.silenceTimer !== undefined) { clearTimeout(SDL2.capture.silenceTimer); } if (SDL2.capture.stream !== undefined) { var tracks = SDL2.capture.stream.getAudioTracks(); for (var i = 0; i < tracks.length; i++) { SDL2.capture.stream.removeTrack(tracks[i]); } SDL2.capture.stream = undefined; } if (SDL2.capture.scriptProcessorNode !== undefined) { SDL2.capture.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) {}; SDL2.capture.scriptProcessorNode.disconnect(); SDL2.capture.scriptProcessorNode = undefined; } if (SDL2.capture.mediaStreamNode !== undefined) { SDL2.capture.mediaStreamNode.disconnect(); SDL2.capture.mediaStreamNode = undefined; } if (SDL2.capture.silenceBuffer !== undefined) { SDL2.capture.silenceBuffer = undefined } SDL2.capture = undefined; } else { if (SDL2.audio.scriptProcessorNode != undefined) { SDL2.audio.scriptProcessorNode.disconnect(); SDL2.audio.scriptProcessorNode = undefined; } SDL2.audio = undefined; } if ((SDL2.audioContext !== undefined) && (SDL2.audio === undefined) && (SDL2.capture === undefined)) { SDL2.audioContext.close(); SDL2.audioContext = undefined; } }, this->iscapture); #if 0 /* !!! FIXME: currently not used. Can we move some stuff off the SDL2 namespace? --ryan. */ SDL_free(this->hidden); #endif } static int EMSCRIPTENAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { SDL_bool valid_format = SDL_FALSE; SDL_AudioFormat test_format; int result; /* based on parts of library_sdl.js */ /* create context */ result = EM_ASM_INT({ if(typeof(Module['SDL2']) === 'undefined') { Module['SDL2'] = {}; } var SDL2 = Module['SDL2']; if (!$0) { SDL2.audio = {}; } else { SDL2.capture = {}; } if (!SDL2.audioContext) { if (typeof(AudioContext) !== 'undefined') { SDL2.audioContext = new AudioContext(); } else if (typeof(webkitAudioContext) !== 'undefined') { SDL2.audioContext = new webkitAudioContext(); } } return SDL2.audioContext === undefined ? -1 : 0; }, iscapture); if (result < 0) { return SDL_SetError("Web Audio API is not available!"); } test_format = SDL_FirstAudioFormat(this->spec.format); while ((!valid_format) && (test_format)) { switch (test_format) { case AUDIO_F32: /* web audio only supports floats */ this->spec.format = test_format; valid_format = SDL_TRUE; break; } test_format = SDL_NextAudioFormat(); } if (!valid_format) { /* Didn't find a compatible format :( */ return SDL_SetError("No compatible audio format!"); } /* Initialize all variables that we clean on shutdown */ #if 0 /* !!! FIXME: currently not used. Can we move some stuff off the SDL2 namespace? --ryan. */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); #endif this->hidden = (struct SDL_PrivateAudioData *)0x1; /* limit to native freq */ this->spec.freq = EM_ASM_INT_V({ var SDL2 = Module['SDL2']; return SDL2.audioContext.sampleRate; }); SDL_CalculateAudioSpec(&this->spec); if (iscapture) { /* The idea is to take the capture media stream, hook it up to an audio graph where we can pass it through a ScriptProcessorNode to access the raw PCM samples and push them to the SDL app's callback. From there, we "process" the audio data into silence and forget about it. */ /* This should, strictly speaking, use MediaRecorder for capture, but this API is cleaner to use and better supported, and fires a callback whenever there's enough data to fire down into the app. The downside is that we are spending CPU time silencing a buffer that the audiocontext uselessly mixes into any output. On the upside, both of those things are not only run in native code in the browser, they're probably SIMD code, too. MediaRecorder feels like it's a pretty inefficient tapdance in similar ways, to be honest. */ EM_ASM_({ var SDL2 = Module['SDL2']; var have_microphone = function(stream) { //console.log('SDL audio capture: we have a microphone! Replacing silence callback.'); if (SDL2.capture.silenceTimer !== undefined) { clearTimeout(SDL2.capture.silenceTimer); SDL2.capture.silenceTimer = undefined; } SDL2.capture.mediaStreamNode = SDL2.audioContext.createMediaStreamSource(stream); SDL2.capture.scriptProcessorNode = SDL2.audioContext.createScriptProcessor($1, $0, 1); SDL2.capture.scriptProcessorNode.onaudioprocess = function(audioProcessingEvent) { if ((SDL2 === undefined) || (SDL2.capture === undefined)) { return; } audioProcessingEvent.outputBuffer.getChannelData(0).fill(0.0); SDL2.capture.currentCaptureBuffer = audioProcessingEvent.inputBuffer; dynCall('vi', $2, [$3]); }; SDL2.capture.mediaStreamNode.connect(SDL2.capture.scriptProcessorNode); SDL2.capture.scriptProcessorNode.connect(SDL2.audioContext.destination); SDL2.capture.stream = stream; }; var no_microphone = function(error) { //console.log('SDL audio capture: we DO NOT have a microphone! (' + error.name + ')...leaving silence callback running.'); }; /* we write silence to the audio callback until the microphone is available (user approves use, etc). */ SDL2.capture.silenceBuffer = SDL2.audioContext.createBuffer($0, $1, SDL2.audioContext.sampleRate); SDL2.capture.silenceBuffer.getChannelData(0).fill(0.0); var silence_callback = function() { SDL2.capture.currentCaptureBuffer = SDL2.capture.silenceBuffer; dynCall('vi', $2, [$3]); }; SDL2.capture.silenceTimer = setTimeout(silence_callback, ($1 / SDL2.audioContext.sampleRate) * 1000); if ((navigator.mediaDevices !== undefined) && (navigator.mediaDevices.getUserMedia !== undefined)) { navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(have_microphone).catch(no_microphone); } else if (navigator.webkitGetUserMedia !== undefined) { navigator.webkitGetUserMedia({ audio: true, video: false }, have_microphone, no_microphone); } }, this->spec.channels, this->spec.samples, HandleCaptureProcess, this); } else { /* setup a ScriptProcessorNode */ EM_ASM_ARGS({ var SDL2 = Module['SDL2']; SDL2.audio.scriptProcessorNode = SDL2.audioContext['createScriptProcessor']($1, 0, $0); SDL2.audio.scriptProcessorNode['onaudioprocess'] = function (e) { if ((SDL2 === undefined) || (SDL2.audio === undefined)) { return; } SDL2.audio.currentOutputBuffer = e['outputBuffer']; dynCall('vi', $2, [$3]); }; SDL2.audio.scriptProcessorNode['connect'](SDL2.audioContext['destination']); }, this->spec.channels, this->spec.samples, HandleAudioProcess, this); } return 0; } static int EMSCRIPTENAUDIO_Init(SDL_AudioDriverImpl * impl) { int available; int capture_available; /* Set the function pointers */ impl->OpenDevice = EMSCRIPTENAUDIO_OpenDevice; impl->CloseDevice = EMSCRIPTENAUDIO_CloseDevice; impl->OnlyHasDefaultOutputDevice = 1; /* no threads here */ impl->SkipMixerLock = 1; impl->ProvidesOwnCallbackThread = 1; /* check availability */ available = EM_ASM_INT_V({ if (typeof(AudioContext) !== 'undefined') { return 1; } else if (typeof(webkitAudioContext) !== 'undefined') { return 1; } return 0; }); if (!available) { SDL_SetError("No audio context available"); } capture_available = available && EM_ASM_INT_V({ if ((typeof(navigator.mediaDevices) !== 'undefined') && (typeof(navigator.mediaDevices.getUserMedia) !== 'undefined')) { return 1; } else if (typeof(navigator.webkitGetUserMedia) !== 'undefined') { return 1; } return 0; }); impl->HasCaptureSupport = capture_available ? SDL_TRUE : SDL_FALSE; impl->OnlyHasDefaultCaptureDevice = capture_available ? SDL_TRUE : SDL_FALSE; return available; } AudioBootStrap EMSCRIPTENAUDIO_bootstrap = { "emscripten", "SDL emscripten audio driver", EMSCRIPTENAUDIO_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_EMSCRIPTEN */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/emscripten/SDL_emscriptenaudio.c
C
apache-2.0
15,343
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_emscriptenaudio_h_ #define SDL_emscriptenaudio_h_ #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { int unused; }; #endif /* SDL_emscriptenaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/emscripten/SDL_emscriptenaudio.h
C
apache-2.0
1,278
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_ESD /* Allow access to an ESD network stream mixing buffer */ #include <sys/types.h> #include <unistd.h> #include <signal.h> #include <errno.h> #include <esd.h> #include "SDL_timer.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_esdaudio.h" #ifdef SDL_AUDIO_DRIVER_ESD_DYNAMIC #include "SDL_name.h" #include "SDL_loadso.h" #else #define SDL_NAME(X) X #endif #ifdef SDL_AUDIO_DRIVER_ESD_DYNAMIC static const char *esd_library = SDL_AUDIO_DRIVER_ESD_DYNAMIC; static void *esd_handle = NULL; static int (*SDL_NAME(esd_open_sound)) (const char *host); static int (*SDL_NAME(esd_close)) (int esd); static int (*SDL_NAME(esd_play_stream)) (esd_format_t format, int rate, const char *host, const char *name); #define SDL_ESD_SYM(x) { #x, (void **) (char *) &SDL_NAME(x) } static struct { const char *name; void **func; } const esd_functions[] = { SDL_ESD_SYM(esd_open_sound), SDL_ESD_SYM(esd_close), SDL_ESD_SYM(esd_play_stream), }; #undef SDL_ESD_SYM static void UnloadESDLibrary() { if (esd_handle != NULL) { SDL_UnloadObject(esd_handle); esd_handle = NULL; } } static int LoadESDLibrary(void) { int i, retval = -1; if (esd_handle == NULL) { esd_handle = SDL_LoadObject(esd_library); if (esd_handle) { retval = 0; for (i = 0; i < SDL_arraysize(esd_functions); ++i) { *esd_functions[i].func = SDL_LoadFunction(esd_handle, esd_functions[i].name); if (!*esd_functions[i].func) { retval = -1; UnloadESDLibrary(); break; } } } } return retval; } #else static void UnloadESDLibrary() { return; } static int LoadESDLibrary(void) { return 0; } #endif /* SDL_AUDIO_DRIVER_ESD_DYNAMIC */ /* This function waits until it is possible to write a full sound buffer */ static void ESD_WaitDevice(_THIS) { Sint32 ticks; /* Check to see if the thread-parent process is still alive */ { static int cnt = 0; /* Note that this only works with thread implementations that use a different process id for each thread. */ /* Check every 10 loops */ if (this->hidden->parent && (((++cnt) % 10) == 0)) { if (kill(this->hidden->parent, 0) < 0 && errno == ESRCH) { SDL_OpenedAudioDeviceDisconnected(this); } } } /* Use timer for general audio synchronization */ ticks = ((Sint32) (this->hidden->next_frame - SDL_GetTicks())) - FUDGE_TICKS; if (ticks > 0) { SDL_Delay(ticks); } } static void ESD_PlayDevice(_THIS) { int written = 0; /* Write the audio data, checking for EAGAIN on broken audio drivers */ do { written = write(this->hidden->audio_fd, this->hidden->mixbuf, this->hidden->mixlen); if ((written < 0) && ((errno == 0) || (errno == EAGAIN))) { SDL_Delay(1); /* Let a little CPU time go by */ } } while ((written < 0) && ((errno == 0) || (errno == EAGAIN) || (errno == EINTR))); /* Set the next write frame */ this->hidden->next_frame += this->hidden->frame_ticks; /* If we couldn't write, assume fatal error for now */ if (written < 0) { SDL_OpenedAudioDeviceDisconnected(this); } } static Uint8 * ESD_GetDeviceBuf(_THIS) { return (this->hidden->mixbuf); } static void ESD_CloseDevice(_THIS) { if (this->hidden->audio_fd >= 0) { SDL_NAME(esd_close) (this->hidden->audio_fd); } SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); } /* Try to get the name of the program */ static char * get_progname(void) { char *progname = NULL; #ifdef __LINUX__ FILE *fp; static char temp[BUFSIZ]; SDL_snprintf(temp, SDL_arraysize(temp), "/proc/%d/cmdline", getpid()); fp = fopen(temp, "r"); if (fp != NULL) { if (fgets(temp, sizeof(temp) - 1, fp)) { progname = SDL_strrchr(temp, '/'); if (progname == NULL) { progname = temp; } else { progname = progname + 1; } } fclose(fp); } #endif return (progname); } static int ESD_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { esd_format_t format = (ESD_STREAM | ESD_PLAY); SDL_AudioFormat test_format = 0; int found = 0; /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); this->hidden->audio_fd = -1; /* Convert audio spec to the ESD audio format */ /* Try for a closest match on audio format */ for (test_format = SDL_FirstAudioFormat(this->spec.format); !found && test_format; test_format = SDL_NextAudioFormat()) { #ifdef DEBUG_AUDIO fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif found = 1; switch (test_format) { case AUDIO_U8: format |= ESD_BITS8; break; case AUDIO_S16SYS: format |= ESD_BITS16; break; default: found = 0; break; } } if (!found) { return SDL_SetError("Couldn't find any hardware audio formats"); } if (this->spec.channels == 1) { format |= ESD_MONO; } else { format |= ESD_STEREO; } #if 0 this->spec.samples = ESD_BUF_SIZE; /* Darn, no way to change this yet */ #endif /* Open a connection to the ESD audio server */ this->hidden->audio_fd = SDL_NAME(esd_play_stream) (format, this->spec.freq, NULL, get_progname()); if (this->hidden->audio_fd < 0) { return SDL_SetError("Couldn't open ESD connection"); } /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&this->spec); this->hidden->frame_ticks = (float) (this->spec.samples * 1000) / this->spec.freq; this->hidden->next_frame = SDL_GetTicks() + this->hidden->frame_ticks; /* Allocate mixing buffer */ this->hidden->mixlen = this->spec.size; this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); /* Get the parent process id (we're the parent of the audio thread) */ this->hidden->parent = getpid(); /* We're ready to rock and roll. :-) */ return 0; } static void ESD_Deinitialize(void) { UnloadESDLibrary(); } static int ESD_Init(SDL_AudioDriverImpl * impl) { if (LoadESDLibrary() < 0) { return 0; } else { int connection = 0; /* Don't start ESD if it's not running */ SDL_setenv("ESD_NO_SPAWN", "1", 0); connection = SDL_NAME(esd_open_sound) (NULL); if (connection < 0) { UnloadESDLibrary(); SDL_SetError("ESD: esd_open_sound failed (no audio server?)"); return 0; } SDL_NAME(esd_close) (connection); } /* Set the function pointers */ impl->OpenDevice = ESD_OpenDevice; impl->PlayDevice = ESD_PlayDevice; impl->WaitDevice = ESD_WaitDevice; impl->GetDeviceBuf = ESD_GetDeviceBuf; impl->CloseDevice = ESD_CloseDevice; impl->Deinitialize = ESD_Deinitialize; impl->OnlyHasDefaultOutputDevice = 1; return 1; /* this audio target is available. */ } AudioBootStrap ESD_bootstrap = { "esd", "Enlightened Sound Daemon", ESD_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_ESD */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/esd/SDL_esdaudio.c
C
apache-2.0
8,911
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_esdaudio_h_ #define SDL_esdaudio_h_ #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The file descriptor for the audio device */ int audio_fd; /* The parent process id, to detect when application quits */ pid_t parent; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; /* Support for audio timing using a timer */ float frame_ticks; float next_frame; }; #define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ #endif /* SDL_esdaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/esd/SDL_esdaudio.h
C
apache-2.0
1,627
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_FUSIONSOUND /* !!! FIXME: why is this is SDL_FS_* instead of FUSIONSOUND_*? */ /* Allow access to a raw mixing buffer */ #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #include <unistd.h> #include "SDL_timer.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_fsaudio.h" #include <fusionsound/fusionsound_version.h> /* #define SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC "libfusionsound.so" */ #ifdef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC #include "SDL_name.h" #include "SDL_loadso.h" #else #define SDL_NAME(X) X #endif #if (FUSIONSOUND_MAJOR_VERSION == 1) && (FUSIONSOUND_MINOR_VERSION < 1) typedef DFBResult DirectResult; #endif /* Buffers to use - more than 2 gives a lot of latency */ #define FUSION_BUFFERS (2) #ifdef SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC static const char *fs_library = SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC; static void *fs_handle = NULL; static DirectResult (*SDL_NAME(FusionSoundInit)) (int *argc, char *(*argv[])); static DirectResult (*SDL_NAME(FusionSoundCreate)) (IFusionSound ** ret_interface); #define SDL_FS_SYM(x) { #x, (void **) (char *) &SDL_NAME(x) } static struct { const char *name; void **func; } fs_functions[] = { /* *INDENT-OFF* */ SDL_FS_SYM(FusionSoundInit), SDL_FS_SYM(FusionSoundCreate), /* *INDENT-ON* */ }; #undef SDL_FS_SYM static void UnloadFusionSoundLibrary() { if (fs_handle != NULL) { SDL_UnloadObject(fs_handle); fs_handle = NULL; } } static int LoadFusionSoundLibrary(void) { int i, retval = -1; if (fs_handle == NULL) { fs_handle = SDL_LoadObject(fs_library); if (fs_handle != NULL) { retval = 0; for (i = 0; i < SDL_arraysize(fs_functions); ++i) { *fs_functions[i].func = SDL_LoadFunction(fs_handle, fs_functions[i].name); if (!*fs_functions[i].func) { retval = -1; UnloadFusionSoundLibrary(); break; } } } } return retval; } #else static void UnloadFusionSoundLibrary() { return; } static int LoadFusionSoundLibrary(void) { return 0; } #endif /* SDL_AUDIO_DRIVER_FUSIONSOUND_DYNAMIC */ /* This function waits until it is possible to write a full sound buffer */ static void SDL_FS_WaitDevice(_THIS) { this->hidden->stream->Wait(this->hidden->stream, this->hidden->mixsamples); } static void SDL_FS_PlayDevice(_THIS) { DirectResult ret; ret = this->hidden->stream->Write(this->hidden->stream, this->hidden->mixbuf, this->hidden->mixsamples); /* If we couldn't write, assume fatal error for now */ if (ret) { SDL_OpenedAudioDeviceDisconnected(this); } #ifdef DEBUG_AUDIO fprintf(stderr, "Wrote %d bytes of audio data\n", this->hidden->mixlen); #endif } static Uint8 * SDL_FS_GetDeviceBuf(_THIS) { return (this->hidden->mixbuf); } static void SDL_FS_CloseDevice(_THIS) { if (this->hidden->stream) { this->hidden->stream->Release(this->hidden->stream); } if (this->hidden->fs) { this->hidden->fs->Release(this->hidden->fs); } SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); } static int SDL_FS_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { int bytes; SDL_AudioFormat test_format = 0, format = 0; FSSampleFormat fs_format; FSStreamDescription desc; DirectResult ret; /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); /* Try for a closest match on audio format */ for (test_format = SDL_FirstAudioFormat(this->spec.format); !format && test_format;) { #ifdef DEBUG_AUDIO fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif switch (test_format) { case AUDIO_U8: fs_format = FSSF_U8; bytes = 1; format = 1; break; case AUDIO_S16SYS: fs_format = FSSF_S16; bytes = 2; format = 1; break; case AUDIO_S32SYS: fs_format = FSSF_S32; bytes = 4; format = 1; break; case AUDIO_F32SYS: fs_format = FSSF_FLOAT; bytes = 4; format = 1; break; default: format = 0; break; } if (!format) { test_format = SDL_NextAudioFormat(); } } if (format == 0) { return SDL_SetError("Couldn't find any hardware audio formats"); } this->spec.format = test_format; /* Retrieve the main sound interface. */ ret = SDL_NAME(FusionSoundCreate) (&this->hidden->fs); if (ret) { return SDL_SetError("Unable to initialize FusionSound: %d", ret); } this->hidden->mixsamples = this->spec.size / bytes / this->spec.channels; /* Fill stream description. */ desc.flags = FSSDF_SAMPLERATE | FSSDF_BUFFERSIZE | FSSDF_CHANNELS | FSSDF_SAMPLEFORMAT | FSSDF_PREBUFFER; desc.samplerate = this->spec.freq; desc.buffersize = this->spec.size * FUSION_BUFFERS; desc.channels = this->spec.channels; desc.prebuffer = 10; desc.sampleformat = fs_format; ret = this->hidden->fs->CreateStream(this->hidden->fs, &desc, &this->hidden->stream); if (ret) { return SDL_SetError("Unable to create FusionSoundStream: %d", ret); } /* See what we got */ desc.flags = FSSDF_SAMPLERATE | FSSDF_BUFFERSIZE | FSSDF_CHANNELS | FSSDF_SAMPLEFORMAT; ret = this->hidden->stream->GetDescription(this->hidden->stream, &desc); this->spec.freq = desc.samplerate; this->spec.size = desc.buffersize / FUSION_BUFFERS * bytes * desc.channels; this->spec.channels = desc.channels; /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&this->spec); /* Allocate mixing buffer */ this->hidden->mixlen = this->spec.size; this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); /* We're ready to rock and roll. :-) */ return 0; } static void SDL_FS_Deinitialize(void) { UnloadFusionSoundLibrary(); } static int SDL_FS_Init(SDL_AudioDriverImpl * impl) { if (LoadFusionSoundLibrary() < 0) { return 0; } else { DirectResult ret; ret = SDL_NAME(FusionSoundInit) (NULL, NULL); if (ret) { UnloadFusionSoundLibrary(); SDL_SetError ("FusionSound: SDL_FS_init failed (FusionSoundInit: %d)", ret); return 0; } } /* Set the function pointers */ impl->OpenDevice = SDL_FS_OpenDevice; impl->PlayDevice = SDL_FS_PlayDevice; impl->WaitDevice = SDL_FS_WaitDevice; impl->GetDeviceBuf = SDL_FS_GetDeviceBuf; impl->CloseDevice = SDL_FS_CloseDevice; impl->Deinitialize = SDL_FS_Deinitialize; impl->OnlyHasDefaultOutputDevice = 1; return 1; /* this audio target is available. */ } AudioBootStrap FUSIONSOUND_bootstrap = { "fusionsound", "FusionSound", SDL_FS_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_FUSIONSOUND */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/fusionsound/SDL_fsaudio.c
C
apache-2.0
8,730
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_fsaudio_h_ #define SDL_fsaudio_h_ #include <fusionsound/fusionsound.h> #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* Interface */ IFusionSound *fs; /* The stream interface for the audio device */ IFusionSoundStream *stream; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; int mixsamples; }; #endif /* SDL_fsaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/fusionsound/SDL_fsaudio.h
C
apache-2.0
1,488
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_HAIKU /* Allow access to the audio stream on Haiku */ #include <SoundPlayer.h> #include <signal.h> #include "../../main/haiku/SDL_BeApp.h" extern "C" { #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "../SDL_sysaudio.h" #include "SDL_haikuaudio.h" #include "SDL_assert.h" } /* !!! FIXME: have the callback call the higher level to avoid code dupe. */ /* The Haiku callback for handling the audio buffer */ static void FillSound(void *device, void *stream, size_t len, const media_raw_audio_format & format) { SDL_AudioDevice *audio = (SDL_AudioDevice *) device; SDL_AudioCallback callback = audio->callbackspec.callback; /* Only do something if audio is enabled */ if (!SDL_AtomicGet(&audio->enabled) || SDL_AtomicGet(&audio->paused)) { if (audio->stream) { SDL_AudioStreamClear(audio->stream); } SDL_memset(stream, audio->spec.silence, len); return; } SDL_assert(audio->spec.size == len); if (audio->stream == NULL) { /* no conversion necessary. */ SDL_LockMutex(audio->mixer_lock); callback(audio->callbackspec.userdata, (Uint8 *) stream, len); SDL_UnlockMutex(audio->mixer_lock); } else { /* streaming/converting */ const int stream_len = audio->callbackspec.size; const int ilen = (int) len; while (SDL_AudioStreamAvailable(audio->stream) < ilen) { callback(audio->callbackspec.userdata, audio->work_buffer, stream_len); if (SDL_AudioStreamPut(audio->stream, audio->work_buffer, stream_len) == -1) { SDL_AudioStreamClear(audio->stream); SDL_AtomicSet(&audio->enabled, 0); break; } } const int got = SDL_AudioStreamGet(audio->stream, stream, ilen); SDL_assert((got < 0) || (got == ilen)); if (got != ilen) { SDL_memset(stream, audio->spec.silence, len); } } } static void HAIKUAUDIO_CloseDevice(_THIS) { if (_this->hidden->audio_obj) { _this->hidden->audio_obj->Stop(); delete _this->hidden->audio_obj; } delete _this->hidden; } static const int sig_list[] = { SIGHUP, SIGINT, SIGQUIT, SIGPIPE, SIGALRM, SIGTERM, SIGWINCH, 0 }; static inline void MaskSignals(sigset_t * omask) { sigset_t mask; int i; sigemptyset(&mask); for (i = 0; sig_list[i]; ++i) { sigaddset(&mask, sig_list[i]); } sigprocmask(SIG_BLOCK, &mask, omask); } static inline void UnmaskSignals(sigset_t * omask) { sigprocmask(SIG_SETMASK, omask, NULL); } static int HAIKUAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { int valid_datatype = 0; media_raw_audio_format format; SDL_AudioFormat test_format = SDL_FirstAudioFormat(_this->spec.format); /* Initialize all variables that we clean on shutdown */ _this->hidden = new SDL_PrivateAudioData; if (_this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(_this->hidden); /* Parse the audio format and fill the Be raw audio format */ SDL_zero(format); format.byte_order = B_MEDIA_LITTLE_ENDIAN; format.frame_rate = (float) _this->spec.freq; format.channel_count = _this->spec.channels; /* !!! FIXME: support > 2? */ while ((!valid_datatype) && (test_format)) { valid_datatype = 1; _this->spec.format = test_format; switch (test_format) { case AUDIO_S8: format.format = media_raw_audio_format::B_AUDIO_CHAR; break; case AUDIO_U8: format.format = media_raw_audio_format::B_AUDIO_UCHAR; break; case AUDIO_S16LSB: format.format = media_raw_audio_format::B_AUDIO_SHORT; break; case AUDIO_S16MSB: format.format = media_raw_audio_format::B_AUDIO_SHORT; format.byte_order = B_MEDIA_BIG_ENDIAN; break; case AUDIO_S32LSB: format.format = media_raw_audio_format::B_AUDIO_INT; break; case AUDIO_S32MSB: format.format = media_raw_audio_format::B_AUDIO_INT; format.byte_order = B_MEDIA_BIG_ENDIAN; break; case AUDIO_F32LSB: format.format = media_raw_audio_format::B_AUDIO_FLOAT; break; case AUDIO_F32MSB: format.format = media_raw_audio_format::B_AUDIO_FLOAT; format.byte_order = B_MEDIA_BIG_ENDIAN; break; default: valid_datatype = 0; test_format = SDL_NextAudioFormat(); break; } } if (!valid_datatype) { /* shouldn't happen, but just in case... */ return SDL_SetError("Unsupported audio format"); } /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&_this->spec); format.buffer_size = _this->spec.size; /* Subscribe to the audio stream (creates a new thread) */ sigset_t omask; MaskSignals(&omask); _this->hidden->audio_obj = new BSoundPlayer(&format, "SDL Audio", FillSound, NULL, _this); UnmaskSignals(&omask); if (_this->hidden->audio_obj->Start() == B_NO_ERROR) { _this->hidden->audio_obj->SetHasData(true); } else { return SDL_SetError("Unable to start Be audio"); } /* We're running! */ return 0; } static void HAIKUAUDIO_Deinitialize(void) { SDL_QuitBeApp(); } static int HAIKUAUDIO_Init(SDL_AudioDriverImpl * impl) { /* Initialize the Be Application, if it's not already started */ if (SDL_InitBeApp() < 0) { return 0; } /* Set the function pointers */ impl->OpenDevice = HAIKUAUDIO_OpenDevice; impl->CloseDevice = HAIKUAUDIO_CloseDevice; impl->Deinitialize = HAIKUAUDIO_Deinitialize; impl->ProvidesOwnCallbackThread = 1; impl->OnlyHasDefaultOutputDevice = 1; return 1; /* this audio target is available. */ } extern "C" { extern AudioBootStrap HAIKUAUDIO_bootstrap; } AudioBootStrap HAIKUAUDIO_bootstrap = { "haiku", "Haiku BSoundPlayer", HAIKUAUDIO_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_HAIKU */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/haiku/SDL_haikuaudio.cc
C++
apache-2.0
7,255
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_haikuaudio_h_ #define SDL_haikuaudio_h_ #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *_this struct SDL_PrivateAudioData { BSoundPlayer *audio_obj; }; #endif /* SDL_haikuaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/haiku/SDL_haikuaudio.h
C
apache-2.0
1,277
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_JACK #include "SDL_assert.h" #include "SDL_timer.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_jackaudio.h" #include "SDL_loadso.h" #include "../../thread/SDL_systhread.h" static jack_client_t * (*JACK_jack_client_open) (const char *, jack_options_t, jack_status_t *, ...); static int (*JACK_jack_client_close) (jack_client_t *); static void (*JACK_jack_on_shutdown) (jack_client_t *, JackShutdownCallback, void *); static int (*JACK_jack_activate) (jack_client_t *); static int (*JACK_jack_deactivate) (jack_client_t *); static void * (*JACK_jack_port_get_buffer) (jack_port_t *, jack_nframes_t); static int (*JACK_jack_port_unregister) (jack_client_t *, jack_port_t *); static void (*JACK_jack_free) (void *); static const char ** (*JACK_jack_get_ports) (jack_client_t *, const char *, const char *, unsigned long); static jack_nframes_t (*JACK_jack_get_sample_rate) (jack_client_t *); static jack_nframes_t (*JACK_jack_get_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 *); static int load_jack_syms(void); #ifdef SDL_AUDIO_DRIVER_JACK_DYNAMIC static const char *jack_library = SDL_AUDIO_DRIVER_JACK_DYNAMIC; static void *jack_handle = NULL; /* !!! FIXME: this is copy/pasted in several places now */ static int load_jack_sym(const char *fn, void **addr) { *addr = SDL_LoadFunction(jack_handle, fn); if (*addr == NULL) { /* Don't call SDL_SetError(): SDL_LoadFunction already did. */ return 0; } return 1; } /* cast funcs to char* first, to please GCC's strict aliasing rules. */ #define SDL_JACK_SYM(x) \ if (!load_jack_sym(#x, (void **) (char *) &JACK_##x)) return -1 static void UnloadJackLibrary(void) { if (jack_handle != NULL) { SDL_UnloadObject(jack_handle); jack_handle = NULL; } } static int LoadJackLibrary(void) { int retval = 0; if (jack_handle == NULL) { jack_handle = SDL_LoadObject(jack_library); if (jack_handle == NULL) { retval = -1; /* Don't call SDL_SetError(): SDL_LoadObject already did. */ } else { retval = load_jack_syms(); if (retval < 0) { UnloadJackLibrary(); } } } return retval; } #else #define SDL_JACK_SYM(x) JACK_##x = x static void UnloadJackLibrary(void) { } static int LoadJackLibrary(void) { load_jack_syms(); return 0; } #endif /* SDL_AUDIO_DRIVER_JACK_DYNAMIC */ static int load_jack_syms(void) { SDL_JACK_SYM(jack_client_open); SDL_JACK_SYM(jack_client_close); SDL_JACK_SYM(jack_on_shutdown); SDL_JACK_SYM(jack_activate); SDL_JACK_SYM(jack_deactivate); SDL_JACK_SYM(jack_port_get_buffer); SDL_JACK_SYM(jack_port_unregister); SDL_JACK_SYM(jack_free); SDL_JACK_SYM(jack_get_ports); 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; } static void jackShutdownCallback(void *arg) /* JACK went away; device is lost. */ { SDL_AudioDevice *this = (SDL_AudioDevice *) arg; SDL_OpenedAudioDeviceDisconnected(this); SDL_SemPost(this->hidden->iosem); /* unblock the SDL thread. */ } // !!! FIXME: implement and register these! //typedef int(* JackSampleRateCallback)(jack_nframes_t nframes, void *arg) //typedef int(* JackBufferSizeCallback)(jack_nframes_t nframes, void *arg) static int jackProcessPlaybackCallback(jack_nframes_t nframes, void *arg) { SDL_AudioDevice *this = (SDL_AudioDevice *) arg; jack_port_t **ports = this->hidden->sdlports; const int total_channels = this->spec.channels; const int total_frames = this->spec.samples; int channelsi; if (!SDL_AtomicGet(&this->enabled)) { /* silence the buffer to avoid repeats and corruption. */ SDL_memset(this->hidden->iobuffer, '\0', this->spec.size); } for (channelsi = 0; channelsi < total_channels; channelsi++) { float *dst = (float *) JACK_jack_port_get_buffer(ports[channelsi], nframes); if (dst) { const float *src = ((float *) this->hidden->iobuffer) + channelsi; int framesi; for (framesi = 0; framesi < total_frames; framesi++) { *(dst++) = *src; src += total_channels; } } } SDL_SemPost(this->hidden->iosem); /* tell SDL thread we're done; refill the buffer. */ return 0; /* success */ } /* This function waits until it is possible to write a full sound buffer */ static void JACK_WaitDevice(_THIS) { if (SDL_AtomicGet(&this->enabled)) { if (SDL_SemWait(this->hidden->iosem) == -1) { SDL_OpenedAudioDeviceDisconnected(this); } } } static Uint8 * JACK_GetDeviceBuf(_THIS) { return (Uint8 *) this->hidden->iobuffer; } static int jackProcessCaptureCallback(jack_nframes_t nframes, void *arg) { SDL_AudioDevice *this = (SDL_AudioDevice *) arg; if (SDL_AtomicGet(&this->enabled)) { jack_port_t **ports = this->hidden->sdlports; const int total_channels = this->spec.channels; const int total_frames = this->spec.samples; int channelsi; for (channelsi = 0; channelsi < total_channels; channelsi++) { const float *src = (const float *) JACK_jack_port_get_buffer(ports[channelsi], nframes); if (src) { float *dst = ((float *) this->hidden->iobuffer) + channelsi; int framesi; for (framesi = 0; framesi < total_frames; framesi++) { *dst = *(src++); dst += total_channels; } } } } SDL_SemPost(this->hidden->iosem); /* tell SDL thread we're done; new buffer is ready! */ return 0; /* success */ } static int JACK_CaptureFromDevice(_THIS, void *buffer, int buflen) { SDL_assert(buflen == this->spec.size); /* we always fill a full buffer. */ /* Wait for JACK to fill the iobuffer */ if (SDL_SemWait(this->hidden->iosem) == -1) { return -1; } SDL_memcpy(buffer, this->hidden->iobuffer, buflen); return buflen; } static void JACK_FlushCapture(_THIS) { SDL_SemWait(this->hidden->iosem); } static void JACK_CloseDevice(_THIS) { if (this->hidden->client) { JACK_jack_deactivate(this->hidden->client); if (this->hidden->sdlports) { const int channels = this->spec.channels; int i; for (i = 0; i < channels; i++) { JACK_jack_port_unregister(this->hidden->client, this->hidden->sdlports[i]); } SDL_free(this->hidden->sdlports); } JACK_jack_client_close(this->hidden->client); } if (this->hidden->iosem) { SDL_DestroySemaphore(this->hidden->iosem); } SDL_free(this->hidden->iobuffer); } static int JACK_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { /* Note that JACK uses "output" for capture devices (they output audio data to us) and "input" for playback (we input audio data to them). Likewise, SDL's playback port will be "output" (we write data out) and capture will be "input" (we read data in). */ const unsigned long sysportflags = iscapture ? JackPortIsOutput : JackPortIsInput; const unsigned long sdlportflags = iscapture ? JackPortIsInput : JackPortIsOutput; 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 */ this->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, sizeof (*this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } /* !!! FIXME: we _still_ need an API to specify an app name */ client = JACK_jack_client_open("SDL", JackNoStartServer, &status, NULL); this->hidden->client = client; if (client == NULL) { return SDL_SetError("Can't open JACK client"); } devports = JACK_jack_get_ports(client, NULL, NULL, JackPortIsPhysical | sysportflags); if (!devports || !devports[0]) { return SDL_SetError("No physical JACK ports available"); } while (devports[++ports]) { /* 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. */ this->spec.format = AUDIO_F32SYS; this->spec.freq = JACK_jack_get_sample_rate(client); this->spec.channels = channels; this->spec.samples = JACK_jack_get_buffer_size(client); SDL_CalculateAudioSpec(&this->spec); this->hidden->iosem = SDL_CreateSemaphore(0); if (!this->hidden->iosem) { return -1; /* error was set by SDL_CreateSemaphore */ } this->hidden->iobuffer = (float *) SDL_calloc(1, this->spec.size); if (!this->hidden->iobuffer) { return SDL_OutOfMemory(); } /* Build SDL's ports, which we will connect to the device ports. */ this->hidden->sdlports = (jack_port_t **) SDL_calloc(channels, sizeof (jack_port_t *)); if (this->hidden->sdlports == NULL) { return SDL_OutOfMemory(); } for (i = 0; i < channels; i++) { char portname[32]; SDL_snprintf(portname, sizeof (portname), "sdl_jack_%s_%d", sdlportstr, i); this->hidden->sdlports[i] = JACK_jack_port_register(client, portname, JACK_DEFAULT_AUDIO_TYPE, sdlportflags, 0); if (this->hidden->sdlports[i] == NULL) { return SDL_SetError("jack_port_register failed"); } } if (JACK_jack_set_process_callback(client, callback, this) != 0) { return SDL_SetError("JACK: Couldn't set process callback"); } JACK_jack_on_shutdown(client, jackShutdownCallback, this); if (JACK_jack_activate(client) != 0) { return SDL_SetError("Failed to activate JACK client"); } /* 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]]; 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. */ JACK_jack_free(devports); SDL_free(audio_ports); /* We're ready to rock and roll. :-) */ return 0; } static void JACK_Deinitialize(void) { UnloadJackLibrary(); } static int JACK_Init(SDL_AudioDriverImpl * impl) { if (LoadJackLibrary() < 0) { return 0; } else { /* Make sure a JACK server is running and available. */ jack_status_t status; jack_client_t *client = JACK_jack_client_open("SDL", JackNoStartServer, &status, NULL); if (client == NULL) { UnloadJackLibrary(); return 0; } JACK_jack_client_close(client); } /* Set the function pointers */ impl->OpenDevice = JACK_OpenDevice; impl->WaitDevice = JACK_WaitDevice; impl->GetDeviceBuf = JACK_GetDeviceBuf; impl->CloseDevice = JACK_CloseDevice; impl->Deinitialize = JACK_Deinitialize; impl->CaptureFromDevice = JACK_CaptureFromDevice; impl->FlushCapture = JACK_FlushCapture; impl->OnlyHasDefaultOutputDevice = SDL_TRUE; impl->OnlyHasDefaultCaptureDevice = SDL_TRUE; impl->HasCaptureSupport = SDL_TRUE; return 1; /* this audio target is available. */ } AudioBootStrap JACK_bootstrap = { "jack", "JACK Audio Connection Kit", JACK_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_JACK */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/jack/SDL_jackaudio.c
C
apache-2.0
14,329
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ #ifndef SDL_jackaudio_h_ #define SDL_jackaudio_h_ #include <jack/jack.h> #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { jack_client_t *client; SDL_sem *iosem; float *iobuffer; jack_port_t **sdlports; }; #endif /* SDL_jackaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/jack/SDL_jackaudio.h
C
apache-2.0
1,329
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_NACL #include "SDL_naclaudio.h" #include "SDL_audio.h" #include "SDL_mutex.h" #include "../SDL_audio_c.h" #include "../SDL_audiodev_c.h" #include "ppapi/c/pp_errors.h" #include "ppapi/c/pp_instance.h" #include "ppapi_simple/ps.h" #include "ppapi_simple/ps_interface.h" #include "ppapi_simple/ps_event.h" /* The tag name used by NACL audio */ #define NACLAUDIO_DRIVER_NAME "nacl" #define SAMPLE_FRAME_COUNT 4096 /* Audio driver functions */ static void nacl_audio_callback(void* samples, uint32_t buffer_size, PP_TimeDelta latency, void* data); /* FIXME: Make use of latency if needed */ static void nacl_audio_callback(void* stream, uint32_t buffer_size, PP_TimeDelta latency, void* data) { const int len = (int) buffer_size; SDL_AudioDevice* _this = (SDL_AudioDevice*) data; SDL_AudioCallback callback = _this->callbackspec.callback; SDL_LockMutex(private->mutex); /* !!! FIXME: is this mutex necessary? */ /* Only do something if audio is enabled */ if (!SDL_AtomicGet(&_this->enabled) || SDL_AtomicGet(&_this->paused)) { if (_this->stream) { SDL_AudioStreamClear(_this->stream); } SDL_memset(stream, _this->spec.silence, len); return; } SDL_assert(_this->spec.size == len); if (_this->stream == NULL) { /* no conversion necessary. */ SDL_LockMutex(_this->mixer_lock); callback(_this->callbackspec.userdata, stream, len); SDL_UnlockMutex(_this->mixer_lock); } else { /* streaming/converting */ const int stream_len = _this->callbackspec.size; while (SDL_AudioStreamAvailable(_this->stream) < len) { callback(_this->callbackspec.userdata, _this->work_buffer, stream_len); if (SDL_AudioStreamPut(_this->stream, _this->work_buffer, stream_len) == -1) { SDL_AudioStreamClear(_this->stream); SDL_AtomicSet(&_this->enabled, 0); break; } } const int got = SDL_AudioStreamGet(_this->stream, stream, len); SDL_assert((got < 0) || (got == len)); if (got != len) { SDL_memset(stream, _this->spec.silence, len); } } SDL_UnlockMutex(private->mutex); } static void NACLAUDIO_CloseDevice(SDL_AudioDevice *device) { const PPB_Core *core = PSInterfaceCore(); const PPB_Audio *ppb_audio = PSInterfaceAudio(); SDL_PrivateAudioData *hidden = (SDL_PrivateAudioData *) device->hidden; ppb_audio->StopPlayback(hidden->audio); SDL_DestroyMutex(hidden->mutex); core->ReleaseResource(hidden->audio); } static int NACLAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { PP_Instance instance = PSGetInstanceId(); const PPB_Audio *ppb_audio = PSInterfaceAudio(); const PPB_AudioConfig *ppb_audiocfg = PSInterfaceAudioConfig(); private = (SDL_PrivateAudioData *) SDL_calloc(1, (sizeof *private)); if (private == NULL) { return SDL_OutOfMemory(); } private->mutex = SDL_CreateMutex(); _this->spec.freq = 44100; _this->spec.format = AUDIO_S16LSB; _this->spec.channels = 2; _this->spec.samples = ppb_audiocfg->RecommendSampleFrameCount( instance, PP_AUDIOSAMPLERATE_44100, SAMPLE_FRAME_COUNT); /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&_this->spec); private->audio = ppb_audio->Create( instance, ppb_audiocfg->CreateStereo16Bit(instance, PP_AUDIOSAMPLERATE_44100, _this->spec.samples), nacl_audio_callback, _this); /* Start audio playback while we are still on the main thread. */ ppb_audio->StartPlayback(private->audio); return 0; } static int NACLAUDIO_Init(SDL_AudioDriverImpl * impl) { if (PSGetInstanceId() == 0) { return 0; } /* Set the function pointers */ impl->OpenDevice = NACLAUDIO_OpenDevice; impl->CloseDevice = NACLAUDIO_CloseDevice; impl->OnlyHasDefaultOutputDevice = 1; impl->ProvidesOwnCallbackThread = 1; /* * impl->WaitDevice = NACLAUDIO_WaitDevice; * impl->GetDeviceBuf = NACLAUDIO_GetDeviceBuf; * impl->PlayDevice = NACLAUDIO_PlayDevice; * impl->Deinitialize = NACLAUDIO_Deinitialize; */ return 1; } AudioBootStrap NACLAUDIO_bootstrap = { NACLAUDIO_DRIVER_NAME, "SDL NaCl Audio Driver", NACLAUDIO_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_NACL */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/nacl/SDL_naclaudio.c
C
apache-2.0
5,530
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_naclaudio_h_ #define SDL_naclaudio_h_ #include "SDL_audio.h" #include "../SDL_sysaudio.h" #include "SDL_mutex.h" #include "ppapi/c/ppb_audio.h" #define _THIS SDL_AudioDevice *_this #define private _this->hidden typedef struct SDL_PrivateAudioData { SDL_mutex* mutex; PP_Resource audio; } SDL_PrivateAudioData; #endif /* SDL_naclaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/nacl/SDL_naclaudio.h
C
apache-2.0
1,371
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_NAS /* Allow access to a raw mixing buffer */ #include <signal.h> #include <unistd.h> #include "SDL_timer.h" #include "SDL_audio.h" #include "SDL_loadso.h" #include "../SDL_audio_c.h" #include "SDL_nasaudio.h" static void (*NAS_AuCloseServer) (AuServer *); static void (*NAS_AuNextEvent) (AuServer *, AuBool, AuEvent *); static AuBool(*NAS_AuDispatchEvent) (AuServer *, AuEvent *); static void (*NAS_AuHandleEvents) (AuServer *); static AuFlowID(*NAS_AuCreateFlow) (AuServer *, AuStatus *); static void (*NAS_AuStartFlow) (AuServer *, AuFlowID, AuStatus *); static void (*NAS_AuSetElements) (AuServer *, AuFlowID, AuBool, int, AuElement *, AuStatus *); static void (*NAS_AuWriteElement) (AuServer *, AuFlowID, int, AuUint32, AuPointer, AuBool, AuStatus *); static AuUint32 (*NAS_AuReadElement) (AuServer *, AuFlowID, int, AuUint32, AuPointer, AuStatus *); static AuServer *(*NAS_AuOpenServer) (_AuConst char *, int, _AuConst char *, int, _AuConst char *, char **); static AuEventHandlerRec *(*NAS_AuRegisterEventHandler) (AuServer *, AuMask, int, AuID, AuEventHandlerCallback, AuPointer); #ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC static const char *nas_library = SDL_AUDIO_DRIVER_NAS_DYNAMIC; static void *nas_handle = NULL; static int load_nas_sym(const char *fn, void **addr) { *addr = SDL_LoadFunction(nas_handle, fn); if (*addr == NULL) { return 0; } return 1; } /* cast funcs to char* first, to please GCC's strict aliasing rules. */ #define SDL_NAS_SYM(x) \ if (!load_nas_sym(#x, (void **) (char *) &NAS_##x)) return -1 #else #define SDL_NAS_SYM(x) NAS_##x = x #endif static int load_nas_syms(void) { SDL_NAS_SYM(AuCloseServer); SDL_NAS_SYM(AuNextEvent); SDL_NAS_SYM(AuDispatchEvent); SDL_NAS_SYM(AuHandleEvents); SDL_NAS_SYM(AuCreateFlow); SDL_NAS_SYM(AuStartFlow); SDL_NAS_SYM(AuSetElements); SDL_NAS_SYM(AuWriteElement); SDL_NAS_SYM(AuReadElement); SDL_NAS_SYM(AuOpenServer); SDL_NAS_SYM(AuRegisterEventHandler); return 0; } #undef SDL_NAS_SYM #ifdef SDL_AUDIO_DRIVER_NAS_DYNAMIC static void UnloadNASLibrary(void) { if (nas_handle != NULL) { SDL_UnloadObject(nas_handle); nas_handle = NULL; } } static int LoadNASLibrary(void) { int retval = 0; if (nas_handle == NULL) { nas_handle = SDL_LoadObject(nas_library); if (nas_handle == NULL) { /* Copy error string so we can use it in a new SDL_SetError(). */ const char *origerr = SDL_GetError(); const size_t len = SDL_strlen(origerr) + 1; char *err = (char *) alloca(len); SDL_strlcpy(err, origerr, len); retval = -1; SDL_SetError("NAS: SDL_LoadObject('%s') failed: %s", nas_library, err); } else { retval = load_nas_syms(); if (retval < 0) { UnloadNASLibrary(); } } } return retval; } #else static void UnloadNASLibrary(void) { } static int LoadNASLibrary(void) { load_nas_syms(); return 0; } #endif /* SDL_AUDIO_DRIVER_NAS_DYNAMIC */ /* This function waits until it is possible to write a full sound buffer */ static void NAS_WaitDevice(_THIS) { while (this->hidden->buf_free < this->hidden->mixlen) { AuEvent ev; NAS_AuNextEvent(this->hidden->aud, AuTrue, &ev); NAS_AuDispatchEvent(this->hidden->aud, &ev); } } static void NAS_PlayDevice(_THIS) { while (this->hidden->mixlen > this->hidden->buf_free) { /* * We think the buffer is full? Yikes! Ask the server for events, * in the hope that some of them is LowWater events telling us more * of the buffer is free now than what we think. */ AuEvent ev; NAS_AuNextEvent(this->hidden->aud, AuTrue, &ev); NAS_AuDispatchEvent(this->hidden->aud, &ev); } this->hidden->buf_free -= this->hidden->mixlen; /* Write the audio data */ NAS_AuWriteElement(this->hidden->aud, this->hidden->flow, 0, this->hidden->mixlen, this->hidden->mixbuf, AuFalse, NULL); this->hidden->written += this->hidden->mixlen; #ifdef DEBUG_AUDIO fprintf(stderr, "Wrote %d bytes of audio data\n", this->hidden->mixlen); #endif } static Uint8 * NAS_GetDeviceBuf(_THIS) { return (this->hidden->mixbuf); } static int NAS_CaptureFromDevice(_THIS, void *buffer, int buflen) { struct SDL_PrivateAudioData *h = this->hidden; int retval; while (SDL_TRUE) { /* just keep the event queue moving and the server chattering. */ NAS_AuHandleEvents(h->aud); retval = (int) NAS_AuReadElement(h->aud, h->flow, 1, buflen, buffer, NULL); /*printf("read %d capture bytes\n", (int) retval);*/ if (retval == 0) { SDL_Delay(10); /* don't burn the CPU if we're waiting for data. */ } else { break; } } return retval; } static void NAS_FlushCapture(_THIS) { struct SDL_PrivateAudioData *h = this->hidden; AuUint32 total = 0; AuUint32 br; Uint8 buf[512]; do { /* just keep the event queue moving and the server chattering. */ NAS_AuHandleEvents(h->aud); br = NAS_AuReadElement(h->aud, h->flow, 1, sizeof (buf), buf, NULL); /*printf("flushed %d capture bytes\n", (int) br);*/ total += br; } while ((br == sizeof (buf)) && (total < this->spec.size)); } static void NAS_CloseDevice(_THIS) { if (this->hidden->aud) { NAS_AuCloseServer(this->hidden->aud); } SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); } static unsigned char sdlformat_to_auformat(unsigned int fmt) { switch (fmt) { case AUDIO_U8: return AuFormatLinearUnsigned8; case AUDIO_S8: return AuFormatLinearSigned8; case AUDIO_U16LSB: return AuFormatLinearUnsigned16LSB; case AUDIO_U16MSB: return AuFormatLinearUnsigned16MSB; case AUDIO_S16LSB: return AuFormatLinearSigned16LSB; case AUDIO_S16MSB: return AuFormatLinearSigned16MSB; } return AuNone; } static AuBool event_handler(AuServer * aud, AuEvent * ev, AuEventHandlerRec * hnd) { SDL_AudioDevice *this = (SDL_AudioDevice *) hnd->data; struct SDL_PrivateAudioData *h = this->hidden; if (this->iscapture) { return AuTrue; /* we don't (currently) care about any of this for capture devices */ } switch (ev->type) { case AuEventTypeElementNotify: { AuElementNotifyEvent *event = (AuElementNotifyEvent *) ev; switch (event->kind) { case AuElementNotifyKindLowWater: if (h->buf_free >= 0) { h->really += event->num_bytes; gettimeofday(&h->last_tv, 0); h->buf_free += event->num_bytes; } else { h->buf_free = event->num_bytes; } break; case AuElementNotifyKindState: switch (event->cur_state) { case AuStatePause: if (event->reason != AuReasonUser) { if (h->buf_free >= 0) { h->really += event->num_bytes; gettimeofday(&h->last_tv, 0); h->buf_free += event->num_bytes; } else { h->buf_free = event->num_bytes; } } break; } } } } return AuTrue; } static AuDeviceID find_device(_THIS) { /* These "Au" things are all macros, not functions... */ struct SDL_PrivateAudioData *h = this->hidden; const unsigned int devicekind = this->iscapture ? AuComponentKindPhysicalInput : AuComponentKindPhysicalOutput; const int numdevs = AuServerNumDevices(h->aud); const int nch = this->spec.channels; int i; /* Try to find exact match on channels first... */ for (i = 0; i < numdevs; i++) { const AuDeviceAttributes *dev = AuServerDevice(h->aud, i); if ((AuDeviceKind(dev) == devicekind) && (AuDeviceNumTracks(dev) == nch)) { return AuDeviceIdentifier(dev); } } /* Take anything, then... */ for (i = 0; i < numdevs; i++) { const AuDeviceAttributes *dev = AuServerDevice(h->aud, i); if (AuDeviceKind(dev) == devicekind) { this->spec.channels = AuDeviceNumTracks(dev); return AuDeviceIdentifier(dev); } } return AuNone; } static int NAS_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { AuElement elms[3]; int buffer_size; SDL_AudioFormat test_format, format; /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); /* Try for a closest match on audio format */ format = 0; for (test_format = SDL_FirstAudioFormat(this->spec.format); !format && test_format;) { format = sdlformat_to_auformat(test_format); if (format == AuNone) { test_format = SDL_NextAudioFormat(); } } if (format == 0) { return SDL_SetError("NAS: Couldn't find any hardware audio formats"); } this->spec.format = test_format; this->hidden->aud = NAS_AuOpenServer("", 0, NULL, 0, NULL, NULL); if (this->hidden->aud == 0) { return SDL_SetError("NAS: Couldn't open connection to NAS server"); } this->hidden->dev = find_device(this); if ((this->hidden->dev == AuNone) || (!(this->hidden->flow = NAS_AuCreateFlow(this->hidden->aud, 0)))) { return SDL_SetError("NAS: Couldn't find a fitting device on NAS server"); } buffer_size = this->spec.freq; if (buffer_size < 4096) buffer_size = 4096; if (buffer_size > 32768) buffer_size = 32768; /* So that the buffer won't get unmanageably big. */ /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&this->spec); if (iscapture) { AuMakeElementImportDevice(elms, this->spec.freq, this->hidden->dev, AuUnlimitedSamples, 0, NULL); AuMakeElementExportClient(elms + 1, 0, this->spec.freq, format, this->spec.channels, AuTrue, buffer_size, buffer_size, 0, NULL); } else { AuMakeElementImportClient(elms, this->spec.freq, format, this->spec.channels, AuTrue, buffer_size, buffer_size / 4, 0, NULL); AuMakeElementExportDevice(elms + 1, 0, this->hidden->dev, this->spec.freq, AuUnlimitedSamples, 0, NULL); } NAS_AuSetElements(this->hidden->aud, this->hidden->flow, AuTrue, 2, elms, NULL); NAS_AuRegisterEventHandler(this->hidden->aud, AuEventHandlerIDMask, 0, this->hidden->flow, event_handler, (AuPointer) this); NAS_AuStartFlow(this->hidden->aud, this->hidden->flow, NULL); /* Allocate mixing buffer */ if (!iscapture) { this->hidden->mixlen = this->spec.size; this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); } /* We're ready to rock and roll. :-) */ return 0; } static void NAS_Deinitialize(void) { UnloadNASLibrary(); } static int NAS_Init(SDL_AudioDriverImpl * impl) { if (LoadNASLibrary() < 0) { return 0; } else { AuServer *aud = NAS_AuOpenServer("", 0, NULL, 0, NULL, NULL); if (aud == NULL) { SDL_SetError("NAS: AuOpenServer() failed (no audio server?)"); return 0; } NAS_AuCloseServer(aud); } /* Set the function pointers */ impl->OpenDevice = NAS_OpenDevice; impl->PlayDevice = NAS_PlayDevice; impl->WaitDevice = NAS_WaitDevice; impl->GetDeviceBuf = NAS_GetDeviceBuf; impl->CaptureFromDevice = NAS_CaptureFromDevice; impl->FlushCapture = NAS_FlushCapture; impl->CloseDevice = NAS_CloseDevice; impl->Deinitialize = NAS_Deinitialize; impl->OnlyHasDefaultOutputDevice = 1; impl->OnlyHasDefaultCaptureDevice = 1; impl->HasCaptureSupport = SDL_TRUE; return 1; /* this audio target is available. */ } AudioBootStrap NAS_bootstrap = { "nas", "Network Audio System", NAS_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_NAS */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/nas/SDL_nasaudio.c
C
apache-2.0
13,964
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_nasaudio_h_ #define SDL_nasaudio_h_ #ifdef __sgi #include <nas/audiolib.h> #else #include <audio/audiolib.h> #endif #include <sys/time.h> #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { AuServer *aud; AuFlowID flow; AuDeviceID dev; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; int written; int really; int bps; struct timeval last_tv; int buf_free; }; #endif /* SDL_nasaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/nas/SDL_nasaudio.h
C
apache-2.0
1,558
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_NETBSD /* * Driver for native NetBSD audio(4). * nia@NetBSD.org */ #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/audioio.h> #include "SDL_timer.h" #include "SDL_audio.h" #include "../../core/unix/SDL_poll.h" #include "../SDL_audio_c.h" #include "../SDL_audiodev_c.h" #include "SDL_netbsdaudio.h" /* #define DEBUG_AUDIO */ static void NETBSDAUDIO_DetectDevices(void) { SDL_EnumUnixAudioDevices(0, NULL); } static void NETBSDAUDIO_Status(_THIS) { #ifdef DEBUG_AUDIO /* *INDENT-OFF* */ audio_info_t info; const struct audio_prinfo *prinfo; if (ioctl(this->hidden->audio_fd, AUDIO_GETINFO, &info) < 0) { fprintf(stderr, "AUDIO_GETINFO failed.\n"); return; } prinfo = this->iscapture ? &info.record : &info.play; fprintf(stderr, "\n" "[%s info]\n" "buffer size : %d bytes\n" "sample rate : %i Hz\n" "channels : %i\n" "precision : %i-bit\n" "encoding : 0x%x\n" "seek : %i\n" "sample count : %i\n" "EOF count : %i\n" "paused : %s\n" "error occured : %s\n" "waiting : %s\n" "active : %s\n" "", this->iscapture ? "record" : "play", prinfo->buffer_size, prinfo->sample_rate, prinfo->channels, prinfo->precision, prinfo->encoding, prinfo->seek, prinfo->samples, prinfo->eof, prinfo->pause ? "yes" : "no", prinfo->error ? "yes" : "no", prinfo->waiting ? "yes" : "no", prinfo->active ? "yes" : "no"); fprintf(stderr, "\n" "[audio info]\n" "monitor_gain : %i\n" "hw block size : %d bytes\n" "hi watermark : %i\n" "lo watermark : %i\n" "audio mode : %s\n" "", info.monitor_gain, info.blocksize, info.hiwat, info.lowat, (info.mode == AUMODE_PLAY) ? "PLAY" : (info.mode = AUMODE_RECORD) ? "RECORD" : (info.mode == AUMODE_PLAY_ALL ? "PLAY_ALL" : "?")); fprintf(stderr, "\n" "[audio spec]\n" "format : 0x%x\n" "size : %u\n" "", this->spec.format, this->spec.size); /* *INDENT-ON* */ #endif /* DEBUG_AUDIO */ } static void NETBSDAUDIO_PlayDevice(_THIS) { struct SDL_PrivateAudioData *h = this->hidden; int written; /* Write the audio data */ written = write(h->audio_fd, h->mixbuf, h->mixlen); if (written == -1) { /* Non recoverable error has occurred. It should be reported!!! */ SDL_OpenedAudioDeviceDisconnected(this); perror("audio"); return; } #ifdef DEBUG_AUDIO fprintf(stderr, "Wrote %d bytes of audio data\n", written); #endif } static Uint8 * NETBSDAUDIO_GetDeviceBuf(_THIS) { return (this->hidden->mixbuf); } static int NETBSDAUDIO_CaptureFromDevice(_THIS, void *_buffer, int buflen) { Uint8 *buffer = (Uint8 *) _buffer; int br; br = read(this->hidden->audio_fd, buffer, buflen); if (br == -1) { /* Non recoverable error has occurred. It should be reported!!! */ perror("audio"); return -1; } #ifdef DEBUG_AUDIO fprintf(stderr, "Captured %d bytes of audio data\n", br); #endif return 0; } static void NETBSDAUDIO_FlushCapture(_THIS) { audio_info_t info; size_t remain; Uint8 buf[512]; if (ioctl(this->hidden->audio_fd, AUDIO_GETINFO, &info) < 0) { return; /* oh well. */ } remain = (size_t) (info.record.samples * (SDL_AUDIO_BITSIZE(this->spec.format) / 8)); while (remain > 0) { const size_t len = SDL_min(sizeof (buf), remain); const int br = read(this->hidden->audio_fd, buf, len); if (br <= 0) { return; /* oh well. */ } remain -= br; } } static void NETBSDAUDIO_CloseDevice(_THIS) { if (this->hidden->audio_fd >= 0) { close(this->hidden->audio_fd); } SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); } static int NETBSDAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { SDL_AudioFormat format = 0; audio_info_t info; struct audio_prinfo *prinfo = iscapture ? &info.record : &info.play; /* We don't care what the devname is...we'll try to open anything. */ /* ...but default to first name in the list... */ if (devname == NULL) { devname = SDL_GetAudioDeviceName(0, iscapture); if (devname == NULL) { return SDL_SetError("No such audio device"); } } /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); /* Open the audio device */ this->hidden->audio_fd = open(devname, iscapture ? O_RDONLY : O_WRONLY); if (this->hidden->audio_fd < 0) { return SDL_SetError("Couldn't open %s: %s", devname, strerror(errno)); } AUDIO_INITINFO(&info); prinfo->encoding = AUDIO_ENCODING_NONE; for (format = SDL_FirstAudioFormat(this->spec.format); format;) { switch (format) { case AUDIO_U8: prinfo->encoding = AUDIO_ENCODING_ULINEAR; prinfo->precision = 8; break; case AUDIO_S8: prinfo->encoding = AUDIO_ENCODING_SLINEAR; prinfo->precision = 8; break; case AUDIO_S16LSB: prinfo->encoding = AUDIO_ENCODING_SLINEAR_LE; prinfo->precision = 16; break; case AUDIO_S16MSB: prinfo->encoding = AUDIO_ENCODING_SLINEAR_BE; prinfo->precision = 16; break; case AUDIO_U16LSB: prinfo->encoding = AUDIO_ENCODING_ULINEAR_LE; prinfo->precision = 16; break; case AUDIO_U16MSB: prinfo->encoding = AUDIO_ENCODING_ULINEAR_BE; prinfo->precision = 16; break; case AUDIO_S32LSB: prinfo->encoding = AUDIO_ENCODING_SLINEAR_LE; prinfo->precision = 32; break; case AUDIO_S32MSB: prinfo->encoding = AUDIO_ENCODING_SLINEAR_BE; prinfo->precision = 32; break; } if (prinfo->encoding != AUDIO_ENCODING_NONE) { break; } format = SDL_NextAudioFormat(); } if (prinfo->encoding == AUDIO_ENCODING_NONE) { return SDL_SetError("No supported encoding for 0x%x", this->spec.format); } this->spec.format = format; /* Calculate spec parameters based on our chosen format */ SDL_CalculateAudioSpec(&this->spec); info.mode = iscapture ? AUMODE_RECORD : AUMODE_PLAY; info.blocksize = this->spec.size; info.hiwat = 5; info.lowat = 3; prinfo->sample_rate = this->spec.freq; prinfo->channels = this->spec.channels; (void) ioctl(this->hidden->audio_fd, AUDIO_SETINFO, &info); (void) ioctl(this->hidden->audio_fd, AUDIO_GETINFO, &info); this->spec.freq = prinfo->sample_rate; this->spec.channels = prinfo->channels; if (!iscapture) { /* Allocate mixing buffer */ this->hidden->mixlen = this->spec.size; this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); } NETBSDAUDIO_Status(this); /* We're ready to rock and roll. :-) */ return 0; } static int NETBSDAUDIO_Init(SDL_AudioDriverImpl * impl) { /* Set the function pointers */ impl->DetectDevices = NETBSDAUDIO_DetectDevices; impl->OpenDevice = NETBSDAUDIO_OpenDevice; impl->PlayDevice = NETBSDAUDIO_PlayDevice; impl->GetDeviceBuf = NETBSDAUDIO_GetDeviceBuf; impl->CloseDevice = NETBSDAUDIO_CloseDevice; impl->CaptureFromDevice = NETBSDAUDIO_CaptureFromDevice; impl->FlushCapture = NETBSDAUDIO_FlushCapture; impl->HasCaptureSupport = SDL_TRUE; impl->AllowsArbitraryDeviceNames = 1; return 1; /* this audio target is available. */ } AudioBootStrap NETBSDAUDIO_bootstrap = { "netbsd", "NetBSD audio", NETBSDAUDIO_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_NETBSD */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/netbsd/SDL_netbsdaudio.c
C
apache-2.0
9,709
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_netbsdaudio_h_ #define SDL_netbsdaudio_h_ #include "../SDL_sysaudio.h" #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The file descriptor for the audio device */ int audio_fd; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; /* Support for audio timing using a timer, in addition to SDL_IOReady() */ float frame_ticks; float next_frame; }; #define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ #endif /* SDL_netbsdaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/netbsd/SDL_netbsdaudio.h
C
apache-2.0
1,530
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_OPENSLES /* For more discussion of low latency audio on Android, see this: https://googlesamples.github.io/android-audio-high-performance/guides/opensl_es.html */ #include "SDL_assert.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "../../core/android/SDL_android.h" #include "SDL_openslES.h" /* for native audio */ #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #include <android/log.h> #if 0 #define LOG_TAG "SDL_openslES" #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) //#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG,__VA_ARGS__) #define LOGV(...) #else #define LOGE(...) #define LOGI(...) #define LOGV(...) #endif /* #define SL_SPEAKER_FRONT_LEFT ((SLuint32) 0x00000001) #define SL_SPEAKER_FRONT_RIGHT ((SLuint32) 0x00000002) #define SL_SPEAKER_FRONT_CENTER ((SLuint32) 0x00000004) #define SL_SPEAKER_LOW_FREQUENCY ((SLuint32) 0x00000008) #define SL_SPEAKER_BACK_LEFT ((SLuint32) 0x00000010) #define SL_SPEAKER_BACK_RIGHT ((SLuint32) 0x00000020) #define SL_SPEAKER_FRONT_LEFT_OF_CENTER ((SLuint32) 0x00000040) #define SL_SPEAKER_FRONT_RIGHT_OF_CENTER ((SLuint32) 0x00000080) #define SL_SPEAKER_BACK_CENTER ((SLuint32) 0x00000100) #define SL_SPEAKER_SIDE_LEFT ((SLuint32) 0x00000200) #define SL_SPEAKER_SIDE_RIGHT ((SLuint32) 0x00000400) #define SL_SPEAKER_TOP_CENTER ((SLuint32) 0x00000800) #define SL_SPEAKER_TOP_FRONT_LEFT ((SLuint32) 0x00001000) #define SL_SPEAKER_TOP_FRONT_CENTER ((SLuint32) 0x00002000) #define SL_SPEAKER_TOP_FRONT_RIGHT ((SLuint32) 0x00004000) #define SL_SPEAKER_TOP_BACK_LEFT ((SLuint32) 0x00008000) #define SL_SPEAKER_TOP_BACK_CENTER ((SLuint32) 0x00010000) #define SL_SPEAKER_TOP_BACK_RIGHT ((SLuint32) 0x00020000) */ #define SL_ANDROID_SPEAKER_STEREO (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT) #define SL_ANDROID_SPEAKER_QUAD (SL_ANDROID_SPEAKER_STEREO | SL_SPEAKER_BACK_LEFT | SL_SPEAKER_BACK_RIGHT) #define SL_ANDROID_SPEAKER_5DOT1 (SL_ANDROID_SPEAKER_QUAD | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY) #define SL_ANDROID_SPEAKER_7DOT1 (SL_ANDROID_SPEAKER_5DOT1 | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT) /* engine interfaces */ static SLObjectItf engineObject; static SLEngineItf engineEngine; /* output mix interfaces */ static SLObjectItf outputMixObject; /* buffer queue player interfaces */ static SLObjectItf bqPlayerObject; static SLPlayItf bqPlayerPlay; static SLAndroidSimpleBufferQueueItf bqPlayerBufferQueue; #if 0 static SLVolumeItf bqPlayerVolume; #endif /* recorder interfaces */ static SLObjectItf recorderObject; static SLRecordItf recorderRecord; static SLAndroidSimpleBufferQueueItf recorderBufferQueue; #if 0 static const char *sldevaudiorecorderstr = "SLES Audio Recorder"; static const char *sldevaudioplayerstr = "SLES Audio Player"; #define SLES_DEV_AUDIO_RECORDER sldevaudiorecorderstr #define SLES_DEV_AUDIO_PLAYER sldevaudioplayerstr static void openslES_DetectDevices( int iscapture ) { LOGI( "openSLES_DetectDevices()" ); if ( iscapture ) addfn( SLES_DEV_AUDIO_RECORDER ); else addfn( SLES_DEV_AUDIO_PLAYER ); } #endif static void openslES_DestroyEngine(void) { LOGI("openslES_DestroyEngine()"); /* destroy output mix object, and invalidate all associated interfaces */ if (outputMixObject != NULL) { (*outputMixObject)->Destroy(outputMixObject); outputMixObject = NULL; } /* destroy engine object, and invalidate all associated interfaces */ if (engineObject != NULL) { (*engineObject)->Destroy(engineObject); engineObject = NULL; engineEngine = NULL; } } static int openslES_CreateEngine(void) { SLresult result; LOGI("openSLES_CreateEngine()"); /* create engine */ result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); if (SL_RESULT_SUCCESS != result) { LOGE("slCreateEngine failed: %d", result); goto error; } LOGI("slCreateEngine OK"); /* realize the engine */ result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != result) { LOGE("RealizeEngine failed: %d", result); goto error; } LOGI("RealizeEngine OK"); /* get the engine interface, which is needed in order to create other objects */ result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); if (SL_RESULT_SUCCESS != result) { LOGE("EngineGetInterface failed: %d", result); goto error; } LOGI("EngineGetInterface OK"); /* create output mix */ const SLInterfaceID ids[1] = { SL_IID_VOLUME }; const SLboolean req[1] = { SL_BOOLEAN_FALSE }; result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 1, ids, req); if (SL_RESULT_SUCCESS != result) { LOGE("CreateOutputMix failed: %d", result); goto error; } LOGI("CreateOutputMix OK"); /* realize the output mix */ result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != result) { LOGE("RealizeOutputMix failed: %d", result); goto error; } return 1; error: openslES_DestroyEngine(); return 0; } /* this callback handler is called every time a buffer finishes recording */ static void bqRecorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context) { struct SDL_PrivateAudioData *audiodata = (struct SDL_PrivateAudioData *) context; LOGV("SLES: Recording Callback"); SDL_SemPost(audiodata->playsem); } static void openslES_DestroyPCMRecorder(_THIS) { struct SDL_PrivateAudioData *audiodata = this->hidden; SLresult result; /* stop recording */ if (recorderRecord != NULL) { result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_STOPPED); if (SL_RESULT_SUCCESS != result) { LOGE("SetRecordState stopped: %d", result); } } /* destroy audio recorder object, and invalidate all associated interfaces */ if (recorderObject != NULL) { (*recorderObject)->Destroy(recorderObject); recorderObject = NULL; recorderRecord = NULL; recorderBufferQueue = NULL; } if (audiodata->playsem) { SDL_DestroySemaphore(audiodata->playsem); audiodata->playsem = NULL; } if (audiodata->mixbuff) { SDL_free(audiodata->mixbuff); } } static int openslES_CreatePCMRecorder(_THIS) { struct SDL_PrivateAudioData *audiodata = this->hidden; SLDataFormat_PCM format_pcm; SLresult result; int i; if (!Android_JNI_RequestPermission("android.permission.RECORD_AUDIO")) { LOGE("This app doesn't have RECORD_AUDIO permission"); return SDL_SetError("This app doesn't have RECORD_AUDIO permission"); } /* Just go with signed 16-bit audio as it's the most compatible */ this->spec.format = AUDIO_S16SYS; this->spec.channels = 1; /*this->spec.freq = SL_SAMPLINGRATE_16 / 1000;*/ /* Update the fragment size as size in bytes */ SDL_CalculateAudioSpec(&this->spec); LOGI("Try to open %u hz %u bit chan %u %s samples %u", this->spec.freq, SDL_AUDIO_BITSIZE(this->spec.format), this->spec.channels, (this->spec.format & 0x1000) ? "BE" : "LE", this->spec.samples); /* configure audio source */ SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, NULL}; SLDataSource audioSrc = {&loc_dev, NULL}; /* configure audio sink */ SLDataLocator_AndroidSimpleBufferQueue loc_bufq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, NUM_BUFFERS }; format_pcm.formatType = SL_DATAFORMAT_PCM; format_pcm.numChannels = this->spec.channels; format_pcm.samplesPerSec = this->spec.freq * 1000; /* / kilo Hz to milli Hz */ format_pcm.bitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format); format_pcm.containerSize = SDL_AUDIO_BITSIZE(this->spec.format); format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; format_pcm.channelMask = SL_SPEAKER_FRONT_CENTER; SLDataSink audioSnk = { &loc_bufq, &format_pcm }; /* create audio recorder */ /* (requires the RECORD_AUDIO permission) */ const SLInterfaceID ids[1] = { SL_IID_ANDROIDSIMPLEBUFFERQUEUE, }; const SLboolean req[1] = { SL_BOOLEAN_TRUE, }; result = (*engineEngine)->CreateAudioRecorder(engineEngine, &recorderObject, &audioSrc, &audioSnk, 1, ids, req); if (SL_RESULT_SUCCESS != result) { LOGE("CreateAudioRecorder failed: %d", result); goto failed; } /* realize the recorder */ result = (*recorderObject)->Realize(recorderObject, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != result) { LOGE("RealizeAudioPlayer failed: %d", result); goto failed; } /* get the record interface */ result = (*recorderObject)->GetInterface(recorderObject, SL_IID_RECORD, &recorderRecord); if (SL_RESULT_SUCCESS != result) { LOGE("SL_IID_RECORD interface get failed: %d", result); goto failed; } /* get the buffer queue interface */ result = (*recorderObject)->GetInterface(recorderObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &recorderBufferQueue); if (SL_RESULT_SUCCESS != result) { LOGE("SL_IID_BUFFERQUEUE interface get failed: %d", result); goto failed; } /* register callback on the buffer queue */ /* context is '(SDL_PrivateAudioData *)this->hidden' */ result = (*recorderBufferQueue)->RegisterCallback(recorderBufferQueue, bqRecorderCallback, this->hidden); if (SL_RESULT_SUCCESS != result) { LOGE("RegisterCallback failed: %d", result); goto failed; } /* Create the audio buffer semaphore */ audiodata->playsem = SDL_CreateSemaphore(0); if (!audiodata->playsem) { LOGE("cannot create Semaphore!"); goto failed; } /* Create the sound buffers */ audiodata->mixbuff = (Uint8 *) SDL_malloc(NUM_BUFFERS * this->spec.size); if (audiodata->mixbuff == NULL) { LOGE("mixbuffer allocate - out of memory"); goto failed; } for (i = 0; i < NUM_BUFFERS; i++) { audiodata->pmixbuff[i] = audiodata->mixbuff + i * this->spec.size; } /* in case already recording, stop recording and clear buffer queue */ result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_STOPPED); if (SL_RESULT_SUCCESS != result) { LOGE("Record set state failed: %d", result); goto failed; } /* enqueue empty buffers to be filled by the recorder */ for (i = 0; i < NUM_BUFFERS; i++) { result = (*recorderBufferQueue)->Enqueue(recorderBufferQueue, audiodata->pmixbuff[i], this->spec.size); if (SL_RESULT_SUCCESS != result) { LOGE("Record enqueue buffers failed: %d", result); goto failed; } } /* start recording */ result = (*recorderRecord)->SetRecordState(recorderRecord, SL_RECORDSTATE_RECORDING); if (SL_RESULT_SUCCESS != result) { LOGE("Record set state failed: %d", result); goto failed; } return 0; failed: openslES_DestroyPCMRecorder(this); return SDL_SetError("Open device failed!"); } /* this callback handler is called every time a buffer finishes playing */ static void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) { struct SDL_PrivateAudioData *audiodata = (struct SDL_PrivateAudioData *) context; LOGV("SLES: Playback Callback"); SDL_SemPost(audiodata->playsem); } static void openslES_DestroyPCMPlayer(_THIS) { struct SDL_PrivateAudioData *audiodata = this->hidden; SLresult result; /* set the player's state to 'stopped' */ if (bqPlayerPlay != NULL) { result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_STOPPED); if (SL_RESULT_SUCCESS != result) { LOGE("SetPlayState stopped failed: %d", result); } } /* destroy buffer queue audio player object, and invalidate all associated interfaces */ if (bqPlayerObject != NULL) { (*bqPlayerObject)->Destroy(bqPlayerObject); bqPlayerObject = NULL; bqPlayerPlay = NULL; bqPlayerBufferQueue = NULL; } if (audiodata->playsem) { SDL_DestroySemaphore(audiodata->playsem); audiodata->playsem = NULL; } if (audiodata->mixbuff) { SDL_free(audiodata->mixbuff); } } static int openslES_CreatePCMPlayer(_THIS) { struct SDL_PrivateAudioData *audiodata = this->hidden; SLDataFormat_PCM format_pcm; SLresult result; int i; /* If we want to add floating point audio support (requires API level 21) it can be done as described here: https://developer.android.com/ndk/guides/audio/opensl/android-extensions.html#floating-point */ #if 1 /* Just go with signed 16-bit audio as it's the most compatible */ this->spec.format = AUDIO_S16SYS; #else SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format); while (test_format != 0) { if (SDL_AUDIO_ISSIGNED(test_format) && SDL_AUDIO_ISINT(test_format)) { break; } test_format = SDL_NextAudioFormat(); } if (test_format == 0) { /* Didn't find a compatible format : */ LOGI( "No compatible audio format, using signed 16-bit audio" ); test_format = AUDIO_S16SYS; } this->spec.format = test_format; #endif /* Update the fragment size as size in bytes */ SDL_CalculateAudioSpec(&this->spec); LOGI("Try to open %u hz %u bit chan %u %s samples %u", this->spec.freq, SDL_AUDIO_BITSIZE(this->spec.format), this->spec.channels, (this->spec.format & 0x1000) ? "BE" : "LE", this->spec.samples); /* configure audio source */ SLDataLocator_AndroidSimpleBufferQueue loc_bufq = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, NUM_BUFFERS }; format_pcm.formatType = SL_DATAFORMAT_PCM; format_pcm.numChannels = this->spec.channels; format_pcm.samplesPerSec = this->spec.freq * 1000; /* / kilo Hz to milli Hz */ format_pcm.bitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format); format_pcm.containerSize = SDL_AUDIO_BITSIZE(this->spec.format); if (SDL_AUDIO_ISBIGENDIAN(this->spec.format)) { format_pcm.endianness = SL_BYTEORDER_BIGENDIAN; } else { format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; } switch (this->spec.channels) { case 1: format_pcm.channelMask = SL_SPEAKER_FRONT_LEFT; break; case 2: format_pcm.channelMask = SL_ANDROID_SPEAKER_STEREO; break; case 3: format_pcm.channelMask = SL_ANDROID_SPEAKER_STEREO | SL_SPEAKER_FRONT_CENTER; break; case 4: format_pcm.channelMask = SL_ANDROID_SPEAKER_QUAD; break; case 5: format_pcm.channelMask = SL_ANDROID_SPEAKER_QUAD | SL_SPEAKER_FRONT_CENTER; break; case 6: format_pcm.channelMask = SL_ANDROID_SPEAKER_5DOT1; break; case 7: format_pcm.channelMask = SL_ANDROID_SPEAKER_5DOT1 | SL_SPEAKER_BACK_CENTER; break; case 8: format_pcm.channelMask = SL_ANDROID_SPEAKER_7DOT1; break; default: /* Unknown number of channels, fall back to stereo */ this->spec.channels = 2; format_pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; break; } SLDataSource audioSrc = { &loc_bufq, &format_pcm }; /* configure audio sink */ SLDataLocator_OutputMix loc_outmix = { SL_DATALOCATOR_OUTPUTMIX, outputMixObject }; SLDataSink audioSnk = { &loc_outmix, NULL }; /* create audio player */ const SLInterfaceID ids[2] = { SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_VOLUME }; const SLboolean req[2] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE, }; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 2, ids, req); if (SL_RESULT_SUCCESS != result) { LOGE("CreateAudioPlayer failed: %d", result); goto failed; } /* realize the player */ result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != result) { LOGE("RealizeAudioPlayer failed: %d", result); goto failed; } /* get the play interface */ result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay); if (SL_RESULT_SUCCESS != result) { LOGE("SL_IID_PLAY interface get failed: %d", result); goto failed; } /* get the buffer queue interface */ result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &bqPlayerBufferQueue); if (SL_RESULT_SUCCESS != result) { LOGE("SL_IID_BUFFERQUEUE interface get failed: %d", result); goto failed; } /* register callback on the buffer queue */ /* context is '(SDL_PrivateAudioData *)this->hidden' */ result = (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, this->hidden); if (SL_RESULT_SUCCESS != result) { LOGE("RegisterCallback failed: %d", result); goto failed; } #if 0 /* get the volume interface */ result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_VOLUME, &bqPlayerVolume); if (SL_RESULT_SUCCESS != result) { LOGE("SL_IID_VOLUME interface get failed: %d", result); /* goto failed; */ } #endif /* Create the audio buffer semaphore */ audiodata->playsem = SDL_CreateSemaphore(NUM_BUFFERS - 1); if (!audiodata->playsem) { LOGE("cannot create Semaphore!"); goto failed; } /* Create the sound buffers */ audiodata->mixbuff = (Uint8 *) SDL_malloc(NUM_BUFFERS * this->spec.size); if (audiodata->mixbuff == NULL) { LOGE("mixbuffer allocate - out of memory"); goto failed; } for (i = 0; i < NUM_BUFFERS; i++) { audiodata->pmixbuff[i] = audiodata->mixbuff + i * this->spec.size; } /* set the player's state to playing */ result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING); if (SL_RESULT_SUCCESS != result) { LOGE("Play set state failed: %d", result); goto failed; } return 0; failed: openslES_DestroyPCMPlayer(this); return SDL_SetError("Open device failed!"); } static int openslES_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { this->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, (sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } if (iscapture) { LOGI("openslES_OpenDevice() %s for capture", devname); return openslES_CreatePCMRecorder(this); } else { LOGI("openslES_OpenDevice() %s for playing", devname); return openslES_CreatePCMPlayer(this); } } static void openslES_WaitDevice(_THIS) { struct SDL_PrivateAudioData *audiodata = this->hidden; LOGV("openslES_WaitDevice()"); /* Wait for an audio chunk to finish */ SDL_SemWait(audiodata->playsem); } static void openslES_PlayDevice(_THIS) { struct SDL_PrivateAudioData *audiodata = this->hidden; SLresult result; LOGV("======openslES_PlayDevice()======"); /* Queue it up */ result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, audiodata->pmixbuff[audiodata->next_buffer], this->spec.size); audiodata->next_buffer++; if (audiodata->next_buffer >= NUM_BUFFERS) { audiodata->next_buffer = 0; } /* If Enqueue fails, callback won't be called. * Post the semphore, not to run out of buffer */ if (SL_RESULT_SUCCESS != result) { SDL_SemPost(audiodata->playsem); } } /*/ n playn sem */ /* getbuf 0 - 1 */ /* fill buff 0 - 1 */ /* play 0 - 0 1 */ /* wait 1 0 0 */ /* getbuf 1 0 0 */ /* fill buff 1 0 0 */ /* play 0 0 0 */ /* wait */ /* */ /* okay.. */ static Uint8 * openslES_GetDeviceBuf(_THIS) { struct SDL_PrivateAudioData *audiodata = this->hidden; LOGV("openslES_GetDeviceBuf()"); return audiodata->pmixbuff[audiodata->next_buffer]; } static int openslES_CaptureFromDevice(_THIS, void *buffer, int buflen) { struct SDL_PrivateAudioData *audiodata = this->hidden; SLresult result; /* Wait for new recorded data */ SDL_SemWait(audiodata->playsem); /* Copy it to the output buffer */ SDL_assert(buflen == this->spec.size); SDL_memcpy(buffer, audiodata->pmixbuff[audiodata->next_buffer], this->spec.size); /* Re-enqueue the buffer */ result = (*recorderBufferQueue)->Enqueue(recorderBufferQueue, audiodata->pmixbuff[audiodata->next_buffer], this->spec.size); if (SL_RESULT_SUCCESS != result) { LOGE("Record enqueue buffers failed: %d", result); return -1; } audiodata->next_buffer++; if (audiodata->next_buffer >= NUM_BUFFERS) { audiodata->next_buffer = 0; } return this->spec.size; } static void openslES_CloseDevice(_THIS) { /* struct SDL_PrivateAudioData *audiodata = this->hidden; */ if (this->iscapture) { LOGI("openslES_CloseDevice() for capture"); openslES_DestroyPCMRecorder(this); } else { LOGI("openslES_CloseDevice() for playing"); openslES_DestroyPCMPlayer(this); } SDL_free(this->hidden); } static int openslES_Init(SDL_AudioDriverImpl * impl) { LOGI("openslES_Init() called"); if (!openslES_CreateEngine()) { return 0; } LOGI("openslES_Init() - set pointers"); /* Set the function pointers */ /* impl->DetectDevices = openslES_DetectDevices; */ impl->OpenDevice = openslES_OpenDevice; impl->WaitDevice = openslES_WaitDevice; impl->PlayDevice = openslES_PlayDevice; impl->GetDeviceBuf = openslES_GetDeviceBuf; impl->CaptureFromDevice = openslES_CaptureFromDevice; impl->CloseDevice = openslES_CloseDevice; impl->Deinitialize = openslES_DestroyEngine; /* and the capabilities */ impl->HasCaptureSupport = 1; impl->OnlyHasDefaultOutputDevice = 1; impl->OnlyHasDefaultCaptureDevice = 1; LOGI("openslES_Init() - success"); /* this audio target is available. */ return 1; } AudioBootStrap openslES_bootstrap = { "openslES", "opensl ES audio driver", openslES_Init, 0 }; void openslES_ResumeDevices(void) { if (bqPlayerPlay != NULL) { /* set the player's state to 'playing' */ SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING); if (SL_RESULT_SUCCESS != result) { LOGE("openslES_ResumeDevices failed: %d", result); } } } void openslES_PauseDevices(void) { if (bqPlayerPlay != NULL) { /* set the player's state to 'paused' */ SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PAUSED); if (SL_RESULT_SUCCESS != result) { LOGE("openslES_PauseDevices failed: %d", result); } } } #endif /* SDL_AUDIO_DRIVER_OPENSLES */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/openslES/SDL_openslES.c
C
apache-2.0
24,514
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_openslesaudio_h #define _SDL_openslesaudio_h #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this #define NUM_BUFFERS 2 /* -- Don't lower this! */ struct SDL_PrivateAudioData { Uint8 *mixbuff; int next_buffer; Uint8 *pmixbuff[NUM_BUFFERS]; SDL_sem *playsem; }; void openslES_ResumeDevices(void); void openslES_PauseDevices(void); #endif /* _SDL_openslesaudio_h */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/openslES/SDL_openslES.h
C
apache-2.0
1,492
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_PAUDIO /* Allow access to a raw mixing buffer */ #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include "SDL_timer.h" #include "SDL_audio.h" #include "SDL_stdinc.h" #include "../SDL_audio_c.h" #include "../../core/unix/SDL_poll.h" #include "SDL_paudio.h" /* #define DEBUG_AUDIO */ /* A conflict within AIX 4.3.3 <sys/> headers and probably others as well. * I guess nobody ever uses audio... Shame over AIX header files. */ #include <sys/machine.h> #undef BIG_ENDIAN #include <sys/audio.h> /* Open the audio device for playback, and don't block if busy */ /* #define OPEN_FLAGS (O_WRONLY|O_NONBLOCK) */ #define OPEN_FLAGS O_WRONLY /* Get the name of the audio device we use for output */ #ifndef _PATH_DEV_DSP #define _PATH_DEV_DSP "/dev/%caud%c/%c" #endif static char devsettings[][3] = { {'p', '0', '1'}, {'p', '0', '2'}, {'p', '0', '3'}, {'p', '0', '4'}, {'p', '1', '1'}, {'p', '1', '2'}, {'p', '1', '3'}, {'p', '1', '4'}, {'p', '2', '1'}, {'p', '2', '2'}, {'p', '2', '3'}, {'p', '2', '4'}, {'p', '3', '1'}, {'p', '3', '2'}, {'p', '3', '3'}, {'p', '3', '4'}, {'b', '0', '1'}, {'b', '0', '2'}, {'b', '0', '3'}, {'b', '0', '4'}, {'b', '1', '1'}, {'b', '1', '2'}, {'b', '1', '3'}, {'b', '1', '4'}, {'b', '2', '1'}, {'b', '2', '2'}, {'b', '2', '3'}, {'b', '2', '4'}, {'b', '3', '1'}, {'b', '3', '2'}, {'b', '3', '3'}, {'b', '3', '4'}, {'\0', '\0', '\0'} }; static int OpenUserDefinedDevice(char *path, int maxlen, int flags) { const char *audiodev; int fd; /* Figure out what our audio device is */ if ((audiodev = SDL_getenv("SDL_PATH_DSP")) == NULL) { audiodev = SDL_getenv("AUDIODEV"); } if (audiodev == NULL) { return -1; } fd = open(audiodev, flags, 0); if (path != NULL) { SDL_strlcpy(path, audiodev, maxlen); path[maxlen - 1] = '\0'; } return fd; } static int OpenAudioPath(char *path, int maxlen, int flags, int classic) { struct stat sb; int cycle = 0; int fd = OpenUserDefinedDevice(path, maxlen, flags); if (fd != -1) { return fd; } /* !!! FIXME: do we really need a table here? */ while (devsettings[cycle][0] != '\0') { char audiopath[1024]; SDL_snprintf(audiopath, SDL_arraysize(audiopath), _PATH_DEV_DSP, devsettings[cycle][0], devsettings[cycle][1], devsettings[cycle][2]); if (stat(audiopath, &sb) == 0) { fd = open(audiopath, flags, 0); if (fd >= 0) { if (path != NULL) { SDL_strlcpy(path, audiopath, maxlen); } return fd; } } } return -1; } /* This function waits until it is possible to write a full sound buffer */ static void PAUDIO_WaitDevice(_THIS) { fd_set fdset; /* See if we need to use timed audio synchronization */ if (this->hidden->frame_ticks) { /* Use timer for general audio synchronization */ Sint32 ticks; ticks = ((Sint32) (this->hidden->next_frame - SDL_GetTicks())) - FUDGE_TICKS; if (ticks > 0) { SDL_Delay(ticks); } } else { int timeoutMS; audio_buffer paud_bufinfo; if (ioctl(this->hidden->audio_fd, AUDIO_BUFFER, &paud_bufinfo) < 0) { #ifdef DEBUG_AUDIO fprintf(stderr, "Couldn't get audio buffer information\n"); #endif timeoutMS = 10 * 1000; } else { timeoutMS = paud_bufinfo.write_buf_time; #ifdef DEBUG_AUDIO fprintf(stderr, "Waiting for write_buf_time=%d ms\n", timeoutMS); #endif } #ifdef DEBUG_AUDIO fprintf(stderr, "Waiting for audio to get ready\n"); #endif if (SDL_IOReady(this->hidden->audio_fd, SDL_TRUE, timeoutMS) <= 0) { /* * In general we should never print to the screen, * but in this case we have no other way of letting * the user know what happened. */ fprintf(stderr, "SDL: %s - Audio timeout - buggy audio driver? (disabled)\n", strerror(errno)); SDL_OpenedAudioDeviceDisconnected(this); /* Don't try to close - may hang */ this->hidden->audio_fd = -1; #ifdef DEBUG_AUDIO fprintf(stderr, "Done disabling audio\n"); #endif } #ifdef DEBUG_AUDIO fprintf(stderr, "Ready!\n"); #endif } } static void PAUDIO_PlayDevice(_THIS) { int written = 0; const Uint8 *mixbuf = this->hidden->mixbuf; const size_t mixlen = this->hidden->mixlen; /* Write the audio data, checking for EAGAIN on broken audio drivers */ do { written = write(this->hidden->audio_fd, mixbuf, mixlen); if ((written < 0) && ((errno == 0) || (errno == EAGAIN))) { SDL_Delay(1); /* Let a little CPU time go by */ } } while ((written < 0) && ((errno == 0) || (errno == EAGAIN) || (errno == EINTR))); /* If timer synchronization is enabled, set the next write frame */ if (this->hidden->frame_ticks) { this->hidden->next_frame += this->hidden->frame_ticks; } /* If we couldn't write, assume fatal error for now */ if (written < 0) { SDL_OpenedAudioDeviceDisconnected(this); } #ifdef DEBUG_AUDIO fprintf(stderr, "Wrote %d bytes of audio data\n", written); #endif } static Uint8 * PAUDIO_GetDeviceBuf(_THIS) { return this->hidden->mixbuf; } static void PAUDIO_CloseDevice(_THIS) { if (this->hidden->audio_fd >= 0) { close(this->hidden->audio_fd); } SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); } static int PAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { const char *workaround = SDL_getenv("SDL_DSP_NOSELECT"); char audiodev[1024]; const char *err = NULL; int format; int bytes_per_sample; SDL_AudioFormat test_format; audio_init paud_init; audio_buffer paud_bufinfo; audio_control paud_control; audio_change paud_change; int fd = -1; /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); /* Open the audio device */ fd = OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0); this->hidden->audio_fd = fd; if (fd < 0) { return SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno)); } /* * We can't set the buffer size - just ask the device for the maximum * that we can have. */ if (ioctl(fd, AUDIO_BUFFER, &paud_bufinfo) < 0) { return SDL_SetError("Couldn't get audio buffer information"); } if (this->spec.channels > 1) this->spec.channels = 2; else this->spec.channels = 1; /* * Fields in the audio_init structure: * * Ignored by us: * * paud.loadpath[LOAD_PATH]; * DSP code to load, MWave chip only? * paud.slot_number; * slot number of the adapter * paud.device_id; * adapter identification number * * Input: * * paud.srate; * the sampling rate in Hz * paud.bits_per_sample; * 8, 16, 32, ... * paud.bsize; * block size for this rate * paud.mode; * ADPCM, PCM, MU_LAW, A_LAW, SOURCE_MIX * paud.channels; * 1=mono, 2=stereo * paud.flags; * FIXED - fixed length data * * LEFT_ALIGNED, RIGHT_ALIGNED (var len only) * * TWOS_COMPLEMENT - 2's complement data * * SIGNED - signed? comment seems wrong in sys/audio.h * * BIG_ENDIAN * paud.operation; * PLAY, RECORD * * Output: * * paud.flags; * PITCH - pitch is supported * * INPUT - input is supported * * OUTPUT - output is supported * * MONITOR - monitor is supported * * VOLUME - volume is supported * * VOLUME_DELAY - volume delay is supported * * BALANCE - balance is supported * * BALANCE_DELAY - balance delay is supported * * TREBLE - treble control is supported * * BASS - bass control is supported * * BESTFIT_PROVIDED - best fit returned * * LOAD_CODE - DSP load needed * paud.rc; * NO_PLAY - DSP code can't do play requests * * NO_RECORD - DSP code can't do record requests * * INVALID_REQUEST - request was invalid * * CONFLICT - conflict with open's flags * * OVERLOADED - out of DSP MIPS or memory * paud.position_resolution; * smallest increment for position */ paud_init.srate = this->spec.freq; paud_init.mode = PCM; paud_init.operation = PLAY; paud_init.channels = this->spec.channels; /* Try for a closest match on audio format */ format = 0; for (test_format = SDL_FirstAudioFormat(this->spec.format); !format && test_format;) { #ifdef DEBUG_AUDIO fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif switch (test_format) { case AUDIO_U8: bytes_per_sample = 1; paud_init.bits_per_sample = 8; paud_init.flags = TWOS_COMPLEMENT | FIXED; format = 1; break; case AUDIO_S8: bytes_per_sample = 1; paud_init.bits_per_sample = 8; paud_init.flags = SIGNED | TWOS_COMPLEMENT | FIXED; format = 1; break; case AUDIO_S16LSB: bytes_per_sample = 2; paud_init.bits_per_sample = 16; paud_init.flags = SIGNED | TWOS_COMPLEMENT | FIXED; format = 1; break; case AUDIO_S16MSB: bytes_per_sample = 2; paud_init.bits_per_sample = 16; paud_init.flags = BIG_ENDIAN | SIGNED | TWOS_COMPLEMENT | FIXED; format = 1; break; case AUDIO_U16LSB: bytes_per_sample = 2; paud_init.bits_per_sample = 16; paud_init.flags = TWOS_COMPLEMENT | FIXED; format = 1; break; case AUDIO_U16MSB: bytes_per_sample = 2; paud_init.bits_per_sample = 16; paud_init.flags = BIG_ENDIAN | TWOS_COMPLEMENT | FIXED; format = 1; break; default: break; } if (!format) { test_format = SDL_NextAudioFormat(); } } if (format == 0) { #ifdef DEBUG_AUDIO fprintf(stderr, "Couldn't find any hardware audio formats\n"); #endif return SDL_SetError("Couldn't find any hardware audio formats"); } this->spec.format = test_format; /* * We know the buffer size and the max number of subsequent writes * that can be pending. If more than one can pend, allow the application * to do something like double buffering between our write buffer and * the device's own buffer that we are filling with write() anyway. * * We calculate this->spec.samples like this because * SDL_CalculateAudioSpec() will give put paud_bufinfo.write_buf_cap * (or paud_bufinfo.write_buf_cap/2) into this->spec.size in return. */ if (paud_bufinfo.request_buf_cap == 1) { this->spec.samples = paud_bufinfo.write_buf_cap / bytes_per_sample / this->spec.channels; } else { this->spec.samples = paud_bufinfo.write_buf_cap / bytes_per_sample / this->spec.channels / 2; } paud_init.bsize = bytes_per_sample * this->spec.channels; SDL_CalculateAudioSpec(&this->spec); /* * The AIX paud device init can't modify the values of the audio_init * structure that we pass to it. So we don't need any recalculation * of this stuff and no reinit call as in linux dsp code. * * /dev/paud supports all of the encoding formats, so we don't need * to do anything like reopening the device, either. */ if (ioctl(fd, AUDIO_INIT, &paud_init) < 0) { switch (paud_init.rc) { case 1: err = "Couldn't set audio format: DSP can't do play requests"; break; case 2: err = "Couldn't set audio format: DSP can't do record requests"; break; case 4: err = "Couldn't set audio format: request was invalid"; break; case 5: err = "Couldn't set audio format: conflict with open's flags"; break; case 6: err = "Couldn't set audio format: out of DSP MIPS or memory"; break; default: err = "Couldn't set audio format: not documented in sys/audio.h"; break; } } if (err != NULL) { return SDL_SetError("Paudio: %s", err); } /* Allocate mixing buffer */ this->hidden->mixlen = this->spec.size; this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size); /* * Set some paramters: full volume, first speaker that we can find. * Ignore the other settings for now. */ paud_change.input = AUDIO_IGNORE; /* the new input source */ paud_change.output = OUTPUT_1; /* EXTERNAL_SPEAKER,INTERNAL_SPEAKER,OUTPUT_1 */ paud_change.monitor = AUDIO_IGNORE; /* the new monitor state */ paud_change.volume = 0x7fffffff; /* volume level [0-0x7fffffff] */ paud_change.volume_delay = AUDIO_IGNORE; /* the new volume delay */ paud_change.balance = 0x3fffffff; /* the new balance */ paud_change.balance_delay = AUDIO_IGNORE; /* the new balance delay */ paud_change.treble = AUDIO_IGNORE; /* the new treble state */ paud_change.bass = AUDIO_IGNORE; /* the new bass state */ paud_change.pitch = AUDIO_IGNORE; /* the new pitch state */ paud_control.ioctl_request = AUDIO_CHANGE; paud_control.request_info = (char *) &paud_change; if (ioctl(fd, AUDIO_CONTROL, &paud_control) < 0) { #ifdef DEBUG_AUDIO fprintf(stderr, "Can't change audio display settings\n"); #endif } /* * Tell the device to expect data. Actual start will wait for * the first write() call. */ paud_control.ioctl_request = AUDIO_START; paud_control.position = 0; if (ioctl(fd, AUDIO_CONTROL, &paud_control) < 0) { #ifdef DEBUG_AUDIO fprintf(stderr, "Can't start audio play\n"); #endif return SDL_SetError("Can't start audio play"); } /* Check to see if we need to use SDL_IOReady() workaround */ if (workaround != NULL) { this->hidden->frame_ticks = (float) (this->spec.samples * 1000) / this->spec.freq; this->hidden->next_frame = SDL_GetTicks() + this->hidden->frame_ticks; } /* We're ready to rock and roll. :-) */ return 0; } static int PAUDIO_Init(SDL_AudioDriverImpl * impl) { /* !!! FIXME: not right for device enum? */ int fd = OpenAudioPath(NULL, 0, OPEN_FLAGS, 0); if (fd < 0) { SDL_SetError("PAUDIO: Couldn't open audio device"); return 0; } close(fd); /* Set the function pointers */ impl->OpenDevice = PAUDIO_OpenDevice; impl->PlayDevice = PAUDIO_PlayDevice; impl->PlayDevice = PAUDIO_WaitDevice; impl->GetDeviceBuf = PAUDIO_GetDeviceBuf; impl->CloseDevice = PAUDIO_CloseDevice; impl->OnlyHasDefaultOutputDevice = 1; /* !!! FIXME: add device enum! */ return 1; /* this audio target is available. */ } AudioBootStrap PAUDIO_bootstrap = { "paud", "AIX Paudio", PAUDIO_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_PAUDIO */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/paudio/SDL_paudio.c
C
apache-2.0
17,463
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_paudio_h_ #define SDL_paudio_h_ #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The file descriptor for the audio device */ int audio_fd; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; /* Support for audio timing using a timer, in addition to SDL_IOReady() */ float frame_ticks; float next_frame; }; #define FUDGE_TICKS 10 /* The scheduler overhead ticks per frame */ #endif /* SDL_paudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/paudio/SDL_paudio.h
C
apache-2.0
1,566
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_PSP #include <stdio.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #include "SDL_audio.h" #include "SDL_error.h" #include "SDL_timer.h" #include "../SDL_audio_c.h" #include "../SDL_audiodev_c.h" #include "../SDL_sysaudio.h" #include "SDL_pspaudio.h" #include <pspaudio.h> #include <pspthreadman.h> /* The tag name used by PSP audio */ #define PSPAUDIO_DRIVER_NAME "psp" static int PSPAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { int format, mixlen, i; this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc(sizeof(*this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); switch (this->spec.format & 0xff) { case 8: case 16: this->spec.format = AUDIO_S16LSB; break; default: return SDL_SetError("Unsupported audio format"); } /* The sample count must be a multiple of 64. */ this->spec.samples = PSP_AUDIO_SAMPLE_ALIGN(this->spec.samples); this->spec.freq = 44100; /* Update the fragment size as size in bytes. */ SDL_CalculateAudioSpec(&this->spec); /* Allocate the mixing buffer. Its size and starting address must be a multiple of 64 bytes. Our sample count is already a multiple of 64, so spec->size should be a multiple of 64 as well. */ mixlen = this->spec.size * NUM_BUFFERS; this->hidden->rawbuf = (Uint8 *) memalign(64, mixlen); if (this->hidden->rawbuf == NULL) { return SDL_SetError("Couldn't allocate mixing buffer"); } /* Setup the hardware channel. */ if (this->spec.channels == 1) { format = PSP_AUDIO_FORMAT_MONO; } else { this->spec.channels = 2; format = PSP_AUDIO_FORMAT_STEREO; } this->hidden->channel = sceAudioChReserve(PSP_AUDIO_NEXT_CHANNEL, this->spec.samples, format); if (this->hidden->channel < 0) { free(this->hidden->rawbuf); this->hidden->rawbuf = NULL; return SDL_SetError("Couldn't reserve hardware channel"); } memset(this->hidden->rawbuf, 0, mixlen); for (i = 0; i < NUM_BUFFERS; i++) { this->hidden->mixbufs[i] = &this->hidden->rawbuf[i * this->spec.size]; } this->hidden->next_buffer = 0; return 0; } static void PSPAUDIO_PlayDevice(_THIS) { Uint8 *mixbuf = this->hidden->mixbufs[this->hidden->next_buffer]; if (this->spec.channels == 1) { sceAudioOutputBlocking(this->hidden->channel, PSP_AUDIO_VOLUME_MAX, mixbuf); } else { sceAudioOutputPannedBlocking(this->hidden->channel, PSP_AUDIO_VOLUME_MAX, PSP_AUDIO_VOLUME_MAX, mixbuf); } this->hidden->next_buffer = (this->hidden->next_buffer + 1) % NUM_BUFFERS; } /* This function waits until it is possible to write a full sound buffer */ static void PSPAUDIO_WaitDevice(_THIS) { /* Because we block when sending audio, there's no need for this function to do anything. */ } static Uint8 *PSPAUDIO_GetDeviceBuf(_THIS) { return this->hidden->mixbufs[this->hidden->next_buffer]; } static void PSPAUDIO_CloseDevice(_THIS) { if (this->hidden->channel >= 0) { sceAudioChRelease(this->hidden->channel); } free(this->hidden->rawbuf); /* this uses memalign(), not SDL_malloc(). */ SDL_free(this->hidden); } static void PSPAUDIO_ThreadInit(_THIS) { /* Increase the priority of this audio thread by 1 to put it ahead of other SDL threads. */ SceUID thid; SceKernelThreadInfo status; thid = sceKernelGetThreadId(); status.size = sizeof(SceKernelThreadInfo); if (sceKernelReferThreadStatus(thid, &status) == 0) { sceKernelChangeThreadPriority(thid, status.currentPriority - 1); } } static int PSPAUDIO_Init(SDL_AudioDriverImpl * impl) { /* Set the function pointers */ impl->OpenDevice = PSPAUDIO_OpenDevice; impl->PlayDevice = PSPAUDIO_PlayDevice; impl->WaitDevice = PSPAUDIO_WaitDevice; impl->GetDeviceBuf = PSPAUDIO_GetDeviceBuf; impl->CloseDevice = PSPAUDIO_CloseDevice; impl->ThreadInit = PSPAUDIO_ThreadInit; /* PSP audio device */ impl->OnlyHasDefaultOutputDevice = 1; /* impl->HasCaptureSupport = 1; impl->OnlyHasDefaultCaptureDevice = 1; */ /* impl->DetectDevices = DSOUND_DetectDevices; impl->Deinitialize = DSOUND_Deinitialize; */ return 1; /* this audio target is available. */ } AudioBootStrap PSPAUDIO_bootstrap = { "psp", "PSP audio driver", PSPAUDIO_Init, 0 }; /* SDL_AUDI */ #endif /* SDL_AUDIO_DRIVER_PSP */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/psp/SDL_pspaudio.c
C
apache-2.0
5,604
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ #ifndef SDL_pspaudio_h_ #define SDL_pspaudio_h_ #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this #define NUM_BUFFERS 2 struct SDL_PrivateAudioData { /* The hardware output channel. */ int channel; /* The raw allocated mixing buffer. */ Uint8 *rawbuf; /* Individual mixing buffers. */ Uint8 *mixbufs[NUM_BUFFERS]; /* Index of the next available mixing buffer. */ int next_buffer; }; #endif /* SDL_pspaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/psp/SDL_pspaudio.h
C
apache-2.0
1,506
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /* The PulseAudio target for SDL 1.3 is based on the 1.3 arts target, with the appropriate parts replaced with the 1.2 PulseAudio target code. This was the cleanest way to move it to 1.3. The 1.2 target was written by Stéphan Kochen: stephan .a.t. kochen.nl */ #include "../../SDL_internal.h" #include "SDL_assert.h" #include "SDL_hints.h" #if SDL_AUDIO_DRIVER_PULSEAUDIO /* Allow access to a raw mixing buffer */ #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #include <unistd.h> #include <sys/types.h> #include <pulse/pulseaudio.h> #include "SDL_timer.h" #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_pulseaudio.h" #include "SDL_loadso.h" #include "../../thread/SDL_systhread.h" #if (PA_API_VERSION < 12) /** Return non-zero if the passed state is one of the connected states */ static SDL_INLINE int PA_CONTEXT_IS_GOOD(pa_context_state_t x) { return x == PA_CONTEXT_CONNECTING || x == PA_CONTEXT_AUTHORIZING || x == PA_CONTEXT_SETTING_NAME || x == PA_CONTEXT_READY; } /** Return non-zero if the passed state is one of the connected states */ static SDL_INLINE int PA_STREAM_IS_GOOD(pa_stream_state_t x) { return x == PA_STREAM_CREATING || x == PA_STREAM_READY; } #endif /* pulseaudio <= 0.9.10 */ static const char *(*PULSEAUDIO_pa_get_library_version) (void); static pa_channel_map *(*PULSEAUDIO_pa_channel_map_init_auto) ( pa_channel_map *, unsigned, pa_channel_map_def_t); static const char * (*PULSEAUDIO_pa_strerror) (int); static pa_mainloop * (*PULSEAUDIO_pa_mainloop_new) (void); static pa_mainloop_api * (*PULSEAUDIO_pa_mainloop_get_api) (pa_mainloop *); static int (*PULSEAUDIO_pa_mainloop_iterate) (pa_mainloop *, int, int *); static int (*PULSEAUDIO_pa_mainloop_run) (pa_mainloop *, int *); static void (*PULSEAUDIO_pa_mainloop_quit) (pa_mainloop *, int); static void (*PULSEAUDIO_pa_mainloop_free) (pa_mainloop *); static pa_operation_state_t (*PULSEAUDIO_pa_operation_get_state) ( pa_operation *); static void (*PULSEAUDIO_pa_operation_cancel) (pa_operation *); static void (*PULSEAUDIO_pa_operation_unref) (pa_operation *); static pa_context * (*PULSEAUDIO_pa_context_new) (pa_mainloop_api *, const char *); static int (*PULSEAUDIO_pa_context_connect) (pa_context *, const char *, pa_context_flags_t, const pa_spawn_api *); static pa_operation * (*PULSEAUDIO_pa_context_get_sink_info_list) (pa_context *, pa_sink_info_cb_t, void *); static pa_operation * (*PULSEAUDIO_pa_context_get_source_info_list) (pa_context *, pa_source_info_cb_t, void *); static pa_operation * (*PULSEAUDIO_pa_context_get_sink_info_by_index) (pa_context *, uint32_t, pa_sink_info_cb_t, void *); static pa_operation * (*PULSEAUDIO_pa_context_get_source_info_by_index) (pa_context *, uint32_t, pa_source_info_cb_t, void *); static pa_context_state_t (*PULSEAUDIO_pa_context_get_state) (pa_context *); static pa_operation * (*PULSEAUDIO_pa_context_subscribe) (pa_context *, pa_subscription_mask_t, pa_context_success_cb_t, void *); static void (*PULSEAUDIO_pa_context_set_subscribe_callback) (pa_context *, pa_context_subscribe_cb_t, void *); static void (*PULSEAUDIO_pa_context_disconnect) (pa_context *); static void (*PULSEAUDIO_pa_context_unref) (pa_context *); static pa_stream * (*PULSEAUDIO_pa_stream_new) (pa_context *, const char *, const pa_sample_spec *, const pa_channel_map *); static int (*PULSEAUDIO_pa_stream_connect_playback) (pa_stream *, const char *, const pa_buffer_attr *, pa_stream_flags_t, pa_cvolume *, pa_stream *); static int (*PULSEAUDIO_pa_stream_connect_record) (pa_stream *, const char *, const pa_buffer_attr *, pa_stream_flags_t); static pa_stream_state_t (*PULSEAUDIO_pa_stream_get_state) (pa_stream *); static size_t (*PULSEAUDIO_pa_stream_writable_size) (pa_stream *); static size_t (*PULSEAUDIO_pa_stream_readable_size) (pa_stream *); static int (*PULSEAUDIO_pa_stream_write) (pa_stream *, const void *, size_t, pa_free_cb_t, int64_t, pa_seek_mode_t); 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 *, pa_stream_success_cb_t, void *); static int (*PULSEAUDIO_pa_stream_disconnect) (pa_stream *); static void (*PULSEAUDIO_pa_stream_unref) (pa_stream *); static int load_pulseaudio_syms(void); #ifdef SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC static const char *pulseaudio_library = SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC; static void *pulseaudio_handle = NULL; static int load_pulseaudio_sym(const char *fn, void **addr) { *addr = SDL_LoadFunction(pulseaudio_handle, fn); if (*addr == NULL) { /* Don't call SDL_SetError(): SDL_LoadFunction already did. */ return 0; } return 1; } /* cast funcs to char* first, to please GCC's strict aliasing rules. */ #define SDL_PULSEAUDIO_SYM(x) \ if (!load_pulseaudio_sym(#x, (void **) (char *) &PULSEAUDIO_##x)) return -1 static void UnloadPulseAudioLibrary(void) { if (pulseaudio_handle != NULL) { SDL_UnloadObject(pulseaudio_handle); pulseaudio_handle = NULL; } } static int LoadPulseAudioLibrary(void) { int retval = 0; if (pulseaudio_handle == NULL) { pulseaudio_handle = SDL_LoadObject(pulseaudio_library); if (pulseaudio_handle == NULL) { retval = -1; /* Don't call SDL_SetError(): SDL_LoadObject already did. */ } else { retval = load_pulseaudio_syms(); if (retval < 0) { UnloadPulseAudioLibrary(); } } } return retval; } #else #define SDL_PULSEAUDIO_SYM(x) PULSEAUDIO_##x = x static void UnloadPulseAudioLibrary(void) { } static int LoadPulseAudioLibrary(void) { load_pulseaudio_syms(); return 0; } #endif /* SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC */ static int load_pulseaudio_syms(void) { SDL_PULSEAUDIO_SYM(pa_get_library_version); SDL_PULSEAUDIO_SYM(pa_mainloop_new); SDL_PULSEAUDIO_SYM(pa_mainloop_get_api); SDL_PULSEAUDIO_SYM(pa_mainloop_iterate); SDL_PULSEAUDIO_SYM(pa_mainloop_run); SDL_PULSEAUDIO_SYM(pa_mainloop_quit); SDL_PULSEAUDIO_SYM(pa_mainloop_free); SDL_PULSEAUDIO_SYM(pa_operation_get_state); SDL_PULSEAUDIO_SYM(pa_operation_cancel); SDL_PULSEAUDIO_SYM(pa_operation_unref); SDL_PULSEAUDIO_SYM(pa_context_new); SDL_PULSEAUDIO_SYM(pa_context_connect); SDL_PULSEAUDIO_SYM(pa_context_get_sink_info_list); SDL_PULSEAUDIO_SYM(pa_context_get_source_info_list); SDL_PULSEAUDIO_SYM(pa_context_get_sink_info_by_index); SDL_PULSEAUDIO_SYM(pa_context_get_source_info_by_index); SDL_PULSEAUDIO_SYM(pa_context_get_state); SDL_PULSEAUDIO_SYM(pa_context_subscribe); SDL_PULSEAUDIO_SYM(pa_context_set_subscribe_callback); SDL_PULSEAUDIO_SYM(pa_context_disconnect); SDL_PULSEAUDIO_SYM(pa_context_unref); SDL_PULSEAUDIO_SYM(pa_stream_new); SDL_PULSEAUDIO_SYM(pa_stream_connect_playback); SDL_PULSEAUDIO_SYM(pa_stream_connect_record); SDL_PULSEAUDIO_SYM(pa_stream_get_state); SDL_PULSEAUDIO_SYM(pa_stream_writable_size); SDL_PULSEAUDIO_SYM(pa_stream_readable_size); SDL_PULSEAUDIO_SYM(pa_stream_write); SDL_PULSEAUDIO_SYM(pa_stream_drain); SDL_PULSEAUDIO_SYM(pa_stream_disconnect); SDL_PULSEAUDIO_SYM(pa_stream_peek); SDL_PULSEAUDIO_SYM(pa_stream_drop); SDL_PULSEAUDIO_SYM(pa_stream_flush); SDL_PULSEAUDIO_SYM(pa_stream_unref); SDL_PULSEAUDIO_SYM(pa_channel_map_init_auto); SDL_PULSEAUDIO_SYM(pa_strerror); return 0; } static SDL_INLINE int squashVersion(const int major, const int minor, const int patch) { return ((major & 0xFF) << 16) | ((minor & 0xFF) << 8) | (patch & 0xFF); } /* Workaround for older pulse: pa_context_new() must have non-NULL appname */ static const char * getAppName(void) { const char *retval = SDL_GetHint(SDL_HINT_AUDIO_DEVICE_APP_NAME); if (!retval || !*retval) { const char *verstr = PULSEAUDIO_pa_get_library_version(); retval = "SDL Application"; /* the "oh well" default. */ if (verstr != NULL) { int maj, min, patch; if (SDL_sscanf(verstr, "%d.%d.%d", &maj, &min, &patch) == 3) { if (squashVersion(maj, min, patch) >= squashVersion(0, 9, 15)) { retval = NULL; /* 0.9.15+ handles NULL correctly. */ } } } } return retval; } static void WaitForPulseOperation(pa_mainloop *mainloop, pa_operation *o) { /* This checks for NO errors currently. Either fix that, check results elsewhere, or do things you don't care about. */ if (mainloop && o) { SDL_bool okay = SDL_TRUE; while (okay && (PULSEAUDIO_pa_operation_get_state(o) == PA_OPERATION_RUNNING)) { okay = (PULSEAUDIO_pa_mainloop_iterate(mainloop, 1, NULL) >= 0); } PULSEAUDIO_pa_operation_unref(o); } } static void DisconnectFromPulseServer(pa_mainloop *mainloop, pa_context *context) { if (context) { PULSEAUDIO_pa_context_disconnect(context); PULSEAUDIO_pa_context_unref(context); } if (mainloop != NULL) { PULSEAUDIO_pa_mainloop_free(mainloop); } } static int ConnectToPulseServer_Internal(pa_mainloop **_mainloop, pa_context **_context) { pa_mainloop *mainloop = NULL; pa_context *context = NULL; pa_mainloop_api *mainloop_api = NULL; int state = 0; *_mainloop = NULL; *_context = NULL; /* Set up a new main loop */ if (!(mainloop = PULSEAUDIO_pa_mainloop_new())) { return SDL_SetError("pa_mainloop_new() failed"); } *_mainloop = mainloop; mainloop_api = PULSEAUDIO_pa_mainloop_get_api(mainloop); SDL_assert(mainloop_api); /* this never fails, right? */ context = PULSEAUDIO_pa_context_new(mainloop_api, getAppName()); if (!context) { return SDL_SetError("pa_context_new() failed"); } *_context = context; /* Connect to the PulseAudio server */ if (PULSEAUDIO_pa_context_connect(context, NULL, 0, NULL) < 0) { return SDL_SetError("Could not setup connection to PulseAudio"); } do { if (PULSEAUDIO_pa_mainloop_iterate(mainloop, 1, NULL) < 0) { return SDL_SetError("pa_mainloop_iterate() failed"); } state = PULSEAUDIO_pa_context_get_state(context); if (!PA_CONTEXT_IS_GOOD(state)) { return SDL_SetError("Could not connect to PulseAudio"); } } while (state != PA_CONTEXT_READY); return 0; /* connected and ready! */ } static int ConnectToPulseServer(pa_mainloop **_mainloop, pa_context **_context) { const int retval = ConnectToPulseServer_Internal(_mainloop, _context); if (retval < 0) { DisconnectFromPulseServer(*_mainloop, *_context); } return retval; } /* This function waits until it is possible to write a full sound buffer */ static void PULSEAUDIO_WaitDevice(_THIS) { struct SDL_PrivateAudioData *h = this->hidden; while (SDL_AtomicGet(&this->enabled)) { if (PULSEAUDIO_pa_context_get_state(h->context) != PA_CONTEXT_READY || PULSEAUDIO_pa_stream_get_state(h->stream) != PA_STREAM_READY || PULSEAUDIO_pa_mainloop_iterate(h->mainloop, 1, NULL) < 0) { SDL_OpenedAudioDeviceDisconnected(this); return; } if (PULSEAUDIO_pa_stream_writable_size(h->stream) >= h->mixlen) { return; } } } static void PULSEAUDIO_PlayDevice(_THIS) { /* Write the audio data */ struct SDL_PrivateAudioData *h = this->hidden; if (SDL_AtomicGet(&this->enabled)) { if (PULSEAUDIO_pa_stream_write(h->stream, h->mixbuf, h->mixlen, NULL, 0LL, PA_SEEK_RELATIVE) < 0) { SDL_OpenedAudioDeviceDisconnected(this); } } } static Uint8 * PULSEAUDIO_GetDeviceBuf(_THIS) { return (this->hidden->mixbuf); } static int PULSEAUDIO_CaptureFromDevice(_THIS, void *buffer, int buflen) { struct SDL_PrivateAudioData *h = this->hidden; const void *data = NULL; size_t nbytes = 0; while (SDL_AtomicGet(&this->enabled)) { if (h->capturebuf != NULL) { const int cpy = SDL_min(buflen, h->capturelen); SDL_memcpy(buffer, h->capturebuf, cpy); /*printf("PULSEAUDIO: fed %d captured bytes\n", cpy);*/ h->capturebuf += cpy; h->capturelen -= cpy; if (h->capturelen == 0) { h->capturebuf = NULL; PULSEAUDIO_pa_stream_drop(h->stream); /* done with this fragment. */ } return cpy; /* new data, return it. */ } if (PULSEAUDIO_pa_context_get_state(h->context) != PA_CONTEXT_READY || PULSEAUDIO_pa_stream_get_state(h->stream) != PA_STREAM_READY || PULSEAUDIO_pa_mainloop_iterate(h->mainloop, 1, NULL) < 0) { SDL_OpenedAudioDeviceDisconnected(this); return -1; /* uhoh, pulse failed! */ } if (PULSEAUDIO_pa_stream_readable_size(h->stream) == 0) { continue; /* no data available yet. */ } /* a new fragment is available! */ PULSEAUDIO_pa_stream_peek(h->stream, &data, &nbytes); SDL_assert(nbytes > 0); if (data == NULL) { /* NULL==buffer had a hole. Ignore that. */ PULSEAUDIO_pa_stream_drop(h->stream); /* drop this fragment. */ } else { /* store this fragment's data, start feeding it to SDL. */ /*printf("PULSEAUDIO: captured %d new bytes\n", (int) nbytes);*/ h->capturebuf = (const Uint8 *) data; h->capturelen = nbytes; } } return -1; /* not enabled? */ } static void PULSEAUDIO_FlushCapture(_THIS) { struct SDL_PrivateAudioData *h = this->hidden; const void *data = NULL; size_t nbytes = 0; if (h->capturebuf != NULL) { PULSEAUDIO_pa_stream_drop(h->stream); h->capturebuf = NULL; h->capturelen = 0; } while (SDL_AtomicGet(&this->enabled)) { if (PULSEAUDIO_pa_context_get_state(h->context) != PA_CONTEXT_READY || PULSEAUDIO_pa_stream_get_state(h->stream) != PA_STREAM_READY || PULSEAUDIO_pa_mainloop_iterate(h->mainloop, 1, NULL) < 0) { SDL_OpenedAudioDeviceDisconnected(this); return; /* uhoh, pulse failed! */ } if (PULSEAUDIO_pa_stream_readable_size(h->stream) == 0) { break; /* no data available, so we're done. */ } /* a new fragment is available! Just dump it. */ PULSEAUDIO_pa_stream_peek(h->stream, &data, &nbytes); PULSEAUDIO_pa_stream_drop(h->stream); /* drop this fragment. */ } } static void PULSEAUDIO_CloseDevice(_THIS) { if (this->hidden->stream) { if (this->hidden->capturebuf != NULL) { PULSEAUDIO_pa_stream_drop(this->hidden->stream); } PULSEAUDIO_pa_stream_disconnect(this->hidden->stream); PULSEAUDIO_pa_stream_unref(this->hidden->stream); } DisconnectFromPulseServer(this->hidden->mainloop, this->hidden->context); SDL_free(this->hidden->mixbuf); SDL_free(this->hidden->device_name); SDL_free(this->hidden); } static void SinkDeviceNameCallback(pa_context *c, const pa_sink_info *i, int is_last, void *data) { if (i) { char **devname = (char **) data; *devname = SDL_strdup(i->name); } } static void SourceDeviceNameCallback(pa_context *c, const pa_source_info *i, int is_last, void *data) { if (i) { char **devname = (char **) data; *devname = SDL_strdup(i->name); } } static SDL_bool FindDeviceName(struct SDL_PrivateAudioData *h, const int iscapture, void *handle) { const uint32_t idx = ((uint32_t) ((size_t) handle)) - 1; if (handle == NULL) { /* NULL == default device. */ return SDL_TRUE; } if (iscapture) { WaitForPulseOperation(h->mainloop, PULSEAUDIO_pa_context_get_source_info_by_index(h->context, idx, SourceDeviceNameCallback, &h->device_name)); } else { WaitForPulseOperation(h->mainloop, PULSEAUDIO_pa_context_get_sink_info_by_index(h->context, idx, SinkDeviceNameCallback, &h->device_name)); } return (h->device_name != NULL); } static int PULSEAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { struct SDL_PrivateAudioData *h = NULL; Uint16 test_format = 0; pa_sample_spec paspec; pa_buffer_attr paattr; pa_channel_map pacmap; pa_stream_flags_t flags = 0; const char *name = NULL; int state = 0; int rc = 0; /* Initialize all variables that we clean on shutdown */ h = this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); paspec.format = PA_SAMPLE_INVALID; /* Try for a closest match on audio format */ for (test_format = SDL_FirstAudioFormat(this->spec.format); (paspec.format == PA_SAMPLE_INVALID) && test_format;) { #ifdef DEBUG_AUDIO fprintf(stderr, "Trying format 0x%4.4x\n", test_format); #endif switch (test_format) { case AUDIO_U8: paspec.format = PA_SAMPLE_U8; break; case AUDIO_S16LSB: paspec.format = PA_SAMPLE_S16LE; break; case AUDIO_S16MSB: paspec.format = PA_SAMPLE_S16BE; break; case AUDIO_S32LSB: paspec.format = PA_SAMPLE_S32LE; break; case AUDIO_S32MSB: paspec.format = PA_SAMPLE_S32BE; break; case AUDIO_F32LSB: paspec.format = PA_SAMPLE_FLOAT32LE; break; case AUDIO_F32MSB: paspec.format = PA_SAMPLE_FLOAT32BE; break; default: paspec.format = PA_SAMPLE_INVALID; break; } if (paspec.format == PA_SAMPLE_INVALID) { test_format = SDL_NextAudioFormat(); } } if (paspec.format == PA_SAMPLE_INVALID) { return SDL_SetError("Couldn't find any hardware audio formats"); } this->spec.format = test_format; /* Calculate the final parameters for this audio specification */ #ifdef PA_STREAM_ADJUST_LATENCY this->spec.samples /= 2; /* Mix in smaller chunck to avoid underruns */ #endif SDL_CalculateAudioSpec(&this->spec); /* Allocate mixing buffer */ if (!iscapture) { h->mixlen = this->spec.size; h->mixbuf = (Uint8 *) SDL_malloc(h->mixlen); if (h->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(h->mixbuf, this->spec.silence, this->spec.size); } paspec.channels = this->spec.channels; paspec.rate = this->spec.freq; /* Reduced prebuffering compared to the defaults. */ #ifdef PA_STREAM_ADJUST_LATENCY /* 2x original requested bufsize */ paattr.tlength = h->mixlen * 4; paattr.prebuf = -1; paattr.maxlength = -1; /* -1 can lead to pa_stream_writable_size() >= mixlen never being true */ paattr.minreq = h->mixlen; flags = PA_STREAM_ADJUST_LATENCY; #else paattr.tlength = h->mixlen*2; paattr.prebuf = h->mixlen*2; paattr.maxlength = h->mixlen*2; paattr.minreq = h->mixlen; #endif if (ConnectToPulseServer(&h->mainloop, &h->context) < 0) { return SDL_SetError("Could not connect to PulseAudio server"); } if (!FindDeviceName(h, iscapture, handle)) { return SDL_SetError("Requested PulseAudio sink/source missing?"); } /* The SDL ALSA output hints us that we use Windows' channel mapping */ /* http://bugzilla.libsdl.org/show_bug.cgi?id=110 */ PULSEAUDIO_pa_channel_map_init_auto(&pacmap, this->spec.channels, PA_CHANNEL_MAP_WAVEEX); name = SDL_GetHint(SDL_HINT_AUDIO_DEVICE_STREAM_NAME); h->stream = PULSEAUDIO_pa_stream_new( h->context, (name && *name) ? name : "Audio Stream", /* stream description */ &paspec, /* sample format spec */ &pacmap /* channel map */ ); if (h->stream == NULL) { return SDL_SetError("Could not set up PulseAudio stream"); } /* now that we have multi-device support, don't move a stream from a device that was unplugged to something else, unless we're default. */ if (h->device_name != NULL) { flags |= PA_STREAM_DONT_MOVE; } if (iscapture) { rc = PULSEAUDIO_pa_stream_connect_record(h->stream, h->device_name, &paattr, flags); } else { rc = PULSEAUDIO_pa_stream_connect_playback(h->stream, h->device_name, &paattr, flags, NULL, NULL); } if (rc < 0) { return SDL_SetError("Could not connect PulseAudio stream"); } do { if (PULSEAUDIO_pa_mainloop_iterate(h->mainloop, 1, NULL) < 0) { return SDL_SetError("pa_mainloop_iterate() failed"); } state = PULSEAUDIO_pa_stream_get_state(h->stream); if (!PA_STREAM_IS_GOOD(state)) { return SDL_SetError("Could not connect PulseAudio stream"); } } while (state != PA_STREAM_READY); /* We're ready to rock and roll. :-) */ return 0; } static pa_mainloop *hotplug_mainloop = NULL; static pa_context *hotplug_context = NULL; static SDL_Thread *hotplug_thread = NULL; /* device handles are device index + 1, cast to void*, so we never pass a NULL. */ /* This is called when PulseAudio adds an output ("sink") device. */ static void SinkInfoCallback(pa_context *c, const pa_sink_info *i, int is_last, void *data) { if (i) { SDL_AddAudioDevice(SDL_FALSE, i->description, (void *) ((size_t) i->index+1)); } } /* This is called when PulseAudio adds a capture ("source") device. */ static void SourceInfoCallback(pa_context *c, const pa_source_info *i, int is_last, void *data) { if (i) { /* Skip "monitor" sources. These are just output from other sinks. */ if (i->monitor_of_sink == PA_INVALID_INDEX) { SDL_AddAudioDevice(SDL_TRUE, i->description, (void *) ((size_t) i->index+1)); } } } /* This is called when PulseAudio has a device connected/removed/changed. */ static void HotplugCallback(pa_context *c, pa_subscription_event_type_t t, uint32_t idx, void *data) { const SDL_bool added = ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_NEW); const SDL_bool removed = ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE); if (added || removed) { /* we only care about add/remove events. */ const SDL_bool sink = ((t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) == PA_SUBSCRIPTION_EVENT_SINK); const SDL_bool source = ((t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) == PA_SUBSCRIPTION_EVENT_SOURCE); /* adds need sink details from the PulseAudio server. Another callback... */ if (added && sink) { PULSEAUDIO_pa_context_get_sink_info_by_index(hotplug_context, idx, SinkInfoCallback, NULL); } else if (added && source) { PULSEAUDIO_pa_context_get_source_info_by_index(hotplug_context, idx, SourceInfoCallback, NULL); } else if (removed && (sink || source)) { /* removes we can handle just with the device index. */ SDL_RemoveAudioDevice(source != 0, (void *) ((size_t) idx+1)); } } } /* this runs as a thread while the Pulse target is initialized to catch hotplug events. */ static int SDLCALL HotplugThread(void *data) { pa_operation *o; SDL_SetThreadPriority(SDL_THREAD_PRIORITY_LOW); PULSEAUDIO_pa_context_set_subscribe_callback(hotplug_context, HotplugCallback, NULL); o = PULSEAUDIO_pa_context_subscribe(hotplug_context, PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SOURCE, NULL, NULL); PULSEAUDIO_pa_operation_unref(o); /* don't wait for it, just do our thing. */ PULSEAUDIO_pa_mainloop_run(hotplug_mainloop, NULL); return 0; } static void PULSEAUDIO_DetectDevices() { WaitForPulseOperation(hotplug_mainloop, PULSEAUDIO_pa_context_get_sink_info_list(hotplug_context, SinkInfoCallback, NULL)); WaitForPulseOperation(hotplug_mainloop, PULSEAUDIO_pa_context_get_source_info_list(hotplug_context, SourceInfoCallback, NULL)); /* ok, we have a sane list, let's set up hotplug notifications now... */ hotplug_thread = SDL_CreateThreadInternal(HotplugThread, "PulseHotplug", 256 * 1024, NULL); } static void PULSEAUDIO_Deinitialize(void) { if (hotplug_thread) { PULSEAUDIO_pa_mainloop_quit(hotplug_mainloop, 0); SDL_WaitThread(hotplug_thread, NULL); hotplug_thread = NULL; } DisconnectFromPulseServer(hotplug_mainloop, hotplug_context); hotplug_mainloop = NULL; hotplug_context = NULL; UnloadPulseAudioLibrary(); } static int PULSEAUDIO_Init(SDL_AudioDriverImpl * impl) { if (LoadPulseAudioLibrary() < 0) { return 0; } if (ConnectToPulseServer(&hotplug_mainloop, &hotplug_context) < 0) { UnloadPulseAudioLibrary(); return 0; } /* Set the function pointers */ impl->DetectDevices = PULSEAUDIO_DetectDevices; impl->OpenDevice = PULSEAUDIO_OpenDevice; impl->PlayDevice = PULSEAUDIO_PlayDevice; impl->WaitDevice = PULSEAUDIO_WaitDevice; impl->GetDeviceBuf = PULSEAUDIO_GetDeviceBuf; impl->CloseDevice = PULSEAUDIO_CloseDevice; impl->Deinitialize = PULSEAUDIO_Deinitialize; impl->CaptureFromDevice = PULSEAUDIO_CaptureFromDevice; impl->FlushCapture = PULSEAUDIO_FlushCapture; impl->HasCaptureSupport = SDL_TRUE; return 1; /* this audio target is available. */ } AudioBootStrap PULSEAUDIO_bootstrap = { "pulseaudio", "PulseAudio", PULSEAUDIO_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_PULSEAUDIO */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/pulseaudio/SDL_pulseaudio.c
C
apache-2.0
27,043
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_pulseaudio_h_ #define SDL_pulseaudio_h_ #include <pulse/simple.h> #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { char *device_name; /* pulseaudio structures */ pa_mainloop *mainloop; pa_context *context; pa_stream *stream; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; const Uint8 *capturebuf; int capturelen; }; #endif /* SDL_pulseaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/pulseaudio/SDL_pulseaudio.h
C
apache-2.0
1,517
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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. */ /* * !!! FIXME: streamline this a little by removing all the * !!! FIXME: if (capture) {} else {} sections that are identical * !!! FIXME: except for one flag. */ /* !!! FIXME: can this target support hotplugging? */ /* !!! FIXME: ...does SDL2 even support QNX? */ #include "../../SDL_internal.h" #if SDL_AUDIO_DRIVER_QSA #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <sys/types.h> #include <sys/time.h> #include <sched.h> #include <sys/select.h> #include <sys/neutrino.h> #include <sys/asoundlib.h> #include "SDL_timer.h" #include "SDL_audio.h" #include "../../core/unix/SDL_poll.h" #include "../SDL_audio_c.h" #include "SDL_qsa_audio.h" /* default channel communication parameters */ #define DEFAULT_CPARAMS_RATE 44100 #define DEFAULT_CPARAMS_VOICES 1 #define DEFAULT_CPARAMS_FRAG_SIZE 4096 #define DEFAULT_CPARAMS_FRAGS_MIN 1 #define DEFAULT_CPARAMS_FRAGS_MAX 1 /* List of found devices */ #define QSA_MAX_DEVICES 32 #define QSA_MAX_NAME_LENGTH 81+16 /* Hardcoded in QSA, can't be changed */ typedef struct _QSA_Device { char name[QSA_MAX_NAME_LENGTH]; /* Long audio device name for SDL */ int cardno; int deviceno; } QSA_Device; QSA_Device qsa_playback_device[QSA_MAX_DEVICES]; uint32_t qsa_playback_devices; QSA_Device qsa_capture_device[QSA_MAX_DEVICES]; uint32_t qsa_capture_devices; static SDL_INLINE int QSA_SetError(const char *fn, int status) { return SDL_SetError("QSA: %s() failed: %s", fn, snd_strerror(status)); } /* !!! FIXME: does this need to be here? Does the SDL version not work? */ static void QSA_ThreadInit(_THIS) { /* Increase default 10 priority to 25 to avoid jerky sound */ struct sched_param param; if (SchedGet(0, 0, &param) != -1) { param.sched_priority = param.sched_curpriority + 15; SchedSet(0, 0, SCHED_NOCHANGE, &param); } } /* PCM channel parameters initialize function */ static void QSA_InitAudioParams(snd_pcm_channel_params_t * cpars) { SDL_zerop(cpars); cpars->channel = SND_PCM_CHANNEL_PLAYBACK; cpars->mode = SND_PCM_MODE_BLOCK; cpars->start_mode = SND_PCM_START_DATA; cpars->stop_mode = SND_PCM_STOP_STOP; cpars->format.format = SND_PCM_SFMT_S16_LE; cpars->format.interleave = 1; cpars->format.rate = DEFAULT_CPARAMS_RATE; cpars->format.voices = DEFAULT_CPARAMS_VOICES; cpars->buf.block.frag_size = DEFAULT_CPARAMS_FRAG_SIZE; cpars->buf.block.frags_min = DEFAULT_CPARAMS_FRAGS_MIN; cpars->buf.block.frags_max = DEFAULT_CPARAMS_FRAGS_MAX; } /* This function waits until it is possible to write a full sound buffer */ static void QSA_WaitDevice(_THIS) { int result; /* Setup timeout for playing one fragment equal to 2 seconds */ /* If timeout occured than something wrong with hardware or driver */ /* For example, Vortex 8820 audio driver stucks on second DAC because */ /* it doesn't exist ! */ result = SDL_IOReady(this->hidden->audio_fd, !this->hidden->iscapture, 2 * 1000); switch (result) { case -1: SDL_SetError("QSA: SDL_IOReady() failed: %s", strerror(errno)); break; case 0: SDL_SetError("QSA: timeout on buffer waiting occured"); this->hidden->timeout_on_wait = 1; break; default: this->hidden->timeout_on_wait = 0; break; } } static void QSA_PlayDevice(_THIS) { snd_pcm_channel_status_t cstatus; int written; int status; int towrite; void *pcmbuffer; if (!SDL_AtomicGet(&this->enabled) || !this->hidden) { return; } towrite = this->spec.size; pcmbuffer = this->hidden->pcm_buf; /* Write the audio data, checking for EAGAIN (buffer full) and underrun */ do { written = snd_pcm_plugin_write(this->hidden->audio_handle, pcmbuffer, towrite); if (written != towrite) { /* Check if samples playback got stuck somewhere in hardware or in */ /* the audio device driver */ if ((errno == EAGAIN) && (written == 0)) { if (this->hidden->timeout_on_wait != 0) { SDL_SetError("QSA: buffer playback timeout"); return; } } /* Check for errors or conditions */ if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { /* Let a little CPU time go by and try to write again */ SDL_Delay(1); /* if we wrote some data */ towrite -= written; pcmbuffer += written * this->spec.channels; continue; } else { if ((errno == EINVAL) || (errno == EIO)) { SDL_zero(cstatus); if (!this->hidden->iscapture) { cstatus.channel = SND_PCM_CHANNEL_PLAYBACK; } else { cstatus.channel = SND_PCM_CHANNEL_CAPTURE; } status = snd_pcm_plugin_status(this->hidden->audio_handle, &cstatus); if (status < 0) { QSA_SetError("snd_pcm_plugin_status", status); return; } if ((cstatus.status == SND_PCM_STATUS_UNDERRUN) || (cstatus.status == SND_PCM_STATUS_READY)) { if (!this->hidden->iscapture) { status = snd_pcm_plugin_prepare(this->hidden-> audio_handle, SND_PCM_CHANNEL_PLAYBACK); } else { status = snd_pcm_plugin_prepare(this->hidden-> audio_handle, SND_PCM_CHANNEL_CAPTURE); } if (status < 0) { QSA_SetError("snd_pcm_plugin_prepare", status); return; } } continue; } else { return; } } } else { /* we wrote all remaining data */ towrite -= written; pcmbuffer += written * this->spec.channels; } } while ((towrite > 0) && SDL_AtomicGet(&this->enabled)); /* If we couldn't write, assume fatal error for now */ if (towrite != 0) { SDL_OpenedAudioDeviceDisconnected(this); } } static Uint8 * QSA_GetDeviceBuf(_THIS) { return this->hidden->pcm_buf; } static void QSA_CloseDevice(_THIS) { if (this->hidden->audio_handle != NULL) { if (!this->hidden->iscapture) { /* Finish playing available samples */ snd_pcm_plugin_flush(this->hidden->audio_handle, SND_PCM_CHANNEL_PLAYBACK); } else { /* Cancel unread samples during capture */ snd_pcm_plugin_flush(this->hidden->audio_handle, SND_PCM_CHANNEL_CAPTURE); } snd_pcm_close(this->hidden->audio_handle); } SDL_free(this->hidden->pcm_buf); SDL_free(this->hidden); } static int QSA_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { const QSA_Device *device = (const QSA_Device *) handle; int status = 0; int format = 0; SDL_AudioFormat test_format = 0; int found = 0; snd_pcm_channel_setup_t csetup; snd_pcm_channel_params_t cparams; /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_calloc(1, (sizeof (struct SDL_PrivateAudioData))); if (this->hidden == NULL) { return SDL_OutOfMemory(); } /* Initialize channel transfer parameters to default */ QSA_InitAudioParams(&cparams); /* Initialize channel direction: capture or playback */ this->hidden->iscapture = iscapture ? SDL_TRUE : SDL_FALSE; if (device != NULL) { /* Open requested audio device */ this->hidden->deviceno = device->deviceno; this->hidden->cardno = device->cardno; status = snd_pcm_open(&this->hidden->audio_handle, device->cardno, device->deviceno, iscapture ? SND_PCM_OPEN_CAPTURE : SND_PCM_OPEN_PLAYBACK); } else { /* Open system default audio device */ status = snd_pcm_open_preferred(&this->hidden->audio_handle, &this->hidden->cardno, &this->hidden->deviceno, iscapture ? SND_PCM_OPEN_CAPTURE : SND_PCM_OPEN_PLAYBACK); } /* Check if requested device is opened */ if (status < 0) { this->hidden->audio_handle = NULL; return QSA_SetError("snd_pcm_open", status); } /* Try for a closest match on audio format */ format = 0; /* can't use format as SND_PCM_SFMT_U8 = 0 in qsa */ found = 0; for (test_format = SDL_FirstAudioFormat(this->spec.format); !found;) { /* if match found set format to equivalent QSA format */ switch (test_format) { case AUDIO_U8: { format = SND_PCM_SFMT_U8; found = 1; } break; case AUDIO_S8: { format = SND_PCM_SFMT_S8; found = 1; } break; case AUDIO_S16LSB: { format = SND_PCM_SFMT_S16_LE; found = 1; } break; case AUDIO_S16MSB: { format = SND_PCM_SFMT_S16_BE; found = 1; } break; case AUDIO_U16LSB: { format = SND_PCM_SFMT_U16_LE; found = 1; } break; case AUDIO_U16MSB: { format = SND_PCM_SFMT_U16_BE; found = 1; } break; case AUDIO_S32LSB: { format = SND_PCM_SFMT_S32_LE; found = 1; } break; case AUDIO_S32MSB: { format = SND_PCM_SFMT_S32_BE; found = 1; } break; case AUDIO_F32LSB: { format = SND_PCM_SFMT_FLOAT_LE; found = 1; } break; case AUDIO_F32MSB: { format = SND_PCM_SFMT_FLOAT_BE; found = 1; } break; default: { break; } } if (!found) { test_format = SDL_NextAudioFormat(); } } /* assumes test_format not 0 on success */ if (test_format == 0) { return SDL_SetError("QSA: Couldn't find any hardware audio formats"); } this->spec.format = test_format; /* Set the audio format */ cparams.format.format = format; /* Set mono/stereo/4ch/6ch/8ch audio */ cparams.format.voices = this->spec.channels; /* Set rate */ cparams.format.rate = this->spec.freq; /* Setup the transfer parameters according to cparams */ status = snd_pcm_plugin_params(this->hidden->audio_handle, &cparams); if (status < 0) { return QSA_SetError("snd_pcm_plugin_params", status); } /* Make sure channel is setup right one last time */ SDL_zero(csetup); if (!this->hidden->iscapture) { csetup.channel = SND_PCM_CHANNEL_PLAYBACK; } else { csetup.channel = SND_PCM_CHANNEL_CAPTURE; } /* Setup an audio channel */ if (snd_pcm_plugin_setup(this->hidden->audio_handle, &csetup) < 0) { return SDL_SetError("QSA: Unable to setup channel"); } /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&this->spec); this->hidden->pcm_len = this->spec.size; if (this->hidden->pcm_len == 0) { this->hidden->pcm_len = csetup.buf.block.frag_size * this->spec.channels * (snd_pcm_format_width(format) / 8); } /* * Allocate memory to the audio buffer and initialize with silence * (Note that buffer size must be a multiple of fragment size, so find * closest multiple) */ this->hidden->pcm_buf = (Uint8 *) SDL_malloc(this->hidden->pcm_len); if (this->hidden->pcm_buf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->pcm_buf, this->spec.silence, this->hidden->pcm_len); /* get the file descriptor */ if (!this->hidden->iscapture) { this->hidden->audio_fd = snd_pcm_file_descriptor(this->hidden->audio_handle, SND_PCM_CHANNEL_PLAYBACK); } else { this->hidden->audio_fd = snd_pcm_file_descriptor(this->hidden->audio_handle, SND_PCM_CHANNEL_CAPTURE); } if (this->hidden->audio_fd < 0) { return QSA_SetError("snd_pcm_file_descriptor", status); } /* Prepare an audio channel */ if (!this->hidden->iscapture) { /* Prepare audio playback */ status = snd_pcm_plugin_prepare(this->hidden->audio_handle, SND_PCM_CHANNEL_PLAYBACK); } else { /* Prepare audio capture */ status = snd_pcm_plugin_prepare(this->hidden->audio_handle, SND_PCM_CHANNEL_CAPTURE); } if (status < 0) { return QSA_SetError("snd_pcm_plugin_prepare", status); } /* We're really ready to rock and roll. :-) */ return 0; } static void QSA_DetectDevices(void) { uint32_t it; uint32_t cards; uint32_t devices; int32_t status; /* Detect amount of available devices */ /* this value can be changed in the runtime */ cards = snd_cards(); /* If io-audio manager is not running we will get 0 as number */ /* of available audio devices */ if (cards == 0) { /* We have no any available audio devices */ return; } /* !!! FIXME: code duplication */ /* Find requested devices by type */ { /* output devices */ /* Playback devices enumeration requested */ for (it = 0; it < cards; it++) { devices = 0; do { status = snd_card_get_longname(it, qsa_playback_device [qsa_playback_devices].name, QSA_MAX_NAME_LENGTH); if (status == EOK) { snd_pcm_t *handle; /* Add device number to device name */ sprintf(qsa_playback_device[qsa_playback_devices].name + SDL_strlen(qsa_playback_device [qsa_playback_devices].name), " d%d", devices); /* Store associated card number id */ qsa_playback_device[qsa_playback_devices].cardno = it; /* Check if this device id could play anything */ status = snd_pcm_open(&handle, it, devices, SND_PCM_OPEN_PLAYBACK); if (status == EOK) { qsa_playback_device[qsa_playback_devices].deviceno = devices; status = snd_pcm_close(handle); if (status == EOK) { SDL_AddAudioDevice(SDL_FALSE, qsa_playback_device[qsa_playback_devices].name, &qsa_playback_device[qsa_playback_devices]); qsa_playback_devices++; } } else { /* Check if we got end of devices list */ if (status == -ENOENT) { break; } } } else { break; } /* Check if we reached maximum devices count */ if (qsa_playback_devices >= QSA_MAX_DEVICES) { break; } devices++; } while (1); /* Check if we reached maximum devices count */ if (qsa_playback_devices >= QSA_MAX_DEVICES) { break; } } } { /* capture devices */ /* Capture devices enumeration requested */ for (it = 0; it < cards; it++) { devices = 0; do { status = snd_card_get_longname(it, qsa_capture_device [qsa_capture_devices].name, QSA_MAX_NAME_LENGTH); if (status == EOK) { snd_pcm_t *handle; /* Add device number to device name */ sprintf(qsa_capture_device[qsa_capture_devices].name + SDL_strlen(qsa_capture_device [qsa_capture_devices].name), " d%d", devices); /* Store associated card number id */ qsa_capture_device[qsa_capture_devices].cardno = it; /* Check if this device id could play anything */ status = snd_pcm_open(&handle, it, devices, SND_PCM_OPEN_CAPTURE); if (status == EOK) { qsa_capture_device[qsa_capture_devices].deviceno = devices; status = snd_pcm_close(handle); if (status == EOK) { SDL_AddAudioDevice(SDL_TRUE, qsa_capture_device[qsa_capture_devices].name, &qsa_capture_device[qsa_capture_devices]); qsa_capture_devices++; } } else { /* Check if we got end of devices list */ if (status == -ENOENT) { break; } } /* Check if we reached maximum devices count */ if (qsa_capture_devices >= QSA_MAX_DEVICES) { break; } } else { break; } devices++; } while (1); /* Check if we reached maximum devices count */ if (qsa_capture_devices >= QSA_MAX_DEVICES) { break; } } } } static void QSA_Deinitialize(void) { /* Clear devices array on shutdown */ /* !!! FIXME: we zero these on init...any reason to do it here? */ SDL_zeroa(qsa_playback_device); SDL_zeroa(qsa_capture_device); qsa_playback_devices = 0; qsa_capture_devices = 0; } static int QSA_Init(SDL_AudioDriverImpl * impl) { /* Clear devices array */ SDL_zeroa(qsa_playback_device); SDL_zeroa(qsa_capture_device); qsa_playback_devices = 0; qsa_capture_devices = 0; /* Set function pointers */ /* DeviceLock and DeviceUnlock functions are used default, */ /* provided by SDL, which uses pthread_mutex for lock/unlock */ impl->DetectDevices = QSA_DetectDevices; impl->OpenDevice = QSA_OpenDevice; impl->ThreadInit = QSA_ThreadInit; impl->WaitDevice = QSA_WaitDevice; impl->PlayDevice = QSA_PlayDevice; impl->GetDeviceBuf = QSA_GetDeviceBuf; impl->CloseDevice = QSA_CloseDevice; impl->Deinitialize = QSA_Deinitialize; impl->LockDevice = NULL; impl->UnlockDevice = NULL; impl->ProvidesOwnCallbackThread = 0; impl->SkipMixerLock = 0; impl->HasCaptureSupport = 1; impl->OnlyHasDefaultOutputDevice = 0; impl->OnlyHasDefaultCaptureDevice = 0; return 1; /* this audio target is available. */ } AudioBootStrap QSAAUDIO_bootstrap = { "qsa", "QNX QSA Audio", QSA_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_QSA */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/qsa/SDL_qsa_audio.c
C
apache-2.0
22,014
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_QSA_AUDIO_H__ #define __SDL_QSA_AUDIO_H__ #include <sys/asoundlib.h> #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice* this struct SDL_PrivateAudioData { /* SDL capture state */ SDL_bool iscapture; /* The audio device handle */ int cardno; int deviceno; snd_pcm_t *audio_handle; /* The audio file descriptor */ int audio_fd; /* Select timeout status */ uint32_t timeout_on_wait; /* Raw mixing buffer */ Uint8 *pcm_buf; Uint32 pcm_len; }; #endif /* __SDL_QSA_AUDIO_H__ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/qsa/SDL_qsa_audio.h
C
apache-2.0
1,617
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_SNDIO /* OpenBSD sndio target */ #if HAVE_STDIO_H #include <stdio.h> #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #include <poll.h> #include <unistd.h> #include "SDL_audio.h" #include "../SDL_audio_c.h" #include "SDL_sndioaudio.h" #ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC #include "SDL_loadso.h" #endif #ifndef INFTIM #define INFTIM -1 #endif #ifndef SIO_DEVANY #define SIO_DEVANY "default" #endif static struct sio_hdl * (*SNDIO_sio_open)(const char *, unsigned int, int); static void (*SNDIO_sio_close)(struct sio_hdl *); static int (*SNDIO_sio_setpar)(struct sio_hdl *, struct sio_par *); static int (*SNDIO_sio_getpar)(struct sio_hdl *, struct sio_par *); static int (*SNDIO_sio_start)(struct sio_hdl *); static int (*SNDIO_sio_stop)(struct sio_hdl *); static size_t (*SNDIO_sio_read)(struct sio_hdl *, void *, size_t); static size_t (*SNDIO_sio_write)(struct sio_hdl *, const void *, size_t); static int (*SNDIO_sio_nfds)(struct sio_hdl *); static int (*SNDIO_sio_pollfd)(struct sio_hdl *, struct pollfd *, int); static int (*SNDIO_sio_revents)(struct sio_hdl *, struct pollfd *); static int (*SNDIO_sio_eof)(struct sio_hdl *); static void (*SNDIO_sio_initpar)(struct sio_par *); #ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC static const char *sndio_library = SDL_AUDIO_DRIVER_SNDIO_DYNAMIC; static void *sndio_handle = NULL; static int load_sndio_sym(const char *fn, void **addr) { *addr = SDL_LoadFunction(sndio_handle, fn); if (*addr == NULL) { /* Don't call SDL_SetError(): SDL_LoadFunction already did. */ return 0; } return 1; } /* cast funcs to char* first, to please GCC's strict aliasing rules. */ #define SDL_SNDIO_SYM(x) \ if (!load_sndio_sym(#x, (void **) (char *) &SNDIO_##x)) return -1 #else #define SDL_SNDIO_SYM(x) SNDIO_##x = x #endif static int load_sndio_syms(void) { SDL_SNDIO_SYM(sio_open); SDL_SNDIO_SYM(sio_close); SDL_SNDIO_SYM(sio_setpar); SDL_SNDIO_SYM(sio_getpar); SDL_SNDIO_SYM(sio_start); SDL_SNDIO_SYM(sio_stop); SDL_SNDIO_SYM(sio_read); SDL_SNDIO_SYM(sio_write); SDL_SNDIO_SYM(sio_nfds); SDL_SNDIO_SYM(sio_pollfd); SDL_SNDIO_SYM(sio_revents); SDL_SNDIO_SYM(sio_eof); SDL_SNDIO_SYM(sio_initpar); return 0; } #undef SDL_SNDIO_SYM #ifdef SDL_AUDIO_DRIVER_SNDIO_DYNAMIC static void UnloadSNDIOLibrary(void) { if (sndio_handle != NULL) { SDL_UnloadObject(sndio_handle); sndio_handle = NULL; } } static int LoadSNDIOLibrary(void) { int retval = 0; if (sndio_handle == NULL) { sndio_handle = SDL_LoadObject(sndio_library); if (sndio_handle == NULL) { retval = -1; /* Don't call SDL_SetError(): SDL_LoadObject already did. */ } else { retval = load_sndio_syms(); if (retval < 0) { UnloadSNDIOLibrary(); } } } return retval; } #else static void UnloadSNDIOLibrary(void) { } static int LoadSNDIOLibrary(void) { load_sndio_syms(); return 0; } #endif /* SDL_AUDIO_DRIVER_SNDIO_DYNAMIC */ static void SNDIO_WaitDevice(_THIS) { /* no-op; SNDIO_sio_write() blocks if necessary. */ } static void SNDIO_PlayDevice(_THIS) { const int written = SNDIO_sio_write(this->hidden->dev, this->hidden->mixbuf, this->hidden->mixlen); /* If we couldn't write, assume fatal error for now */ if ( written == 0 ) { SDL_OpenedAudioDeviceDisconnected(this); } #ifdef DEBUG_AUDIO fprintf(stderr, "Wrote %d bytes of audio data\n", written); #endif } static int SNDIO_CaptureFromDevice(_THIS, void *buffer, int buflen) { size_t r; int revents; int nfds; /* Emulate a blocking read */ r = SNDIO_sio_read(this->hidden->dev, buffer, buflen); while (r == 0 && !SNDIO_sio_eof(this->hidden->dev)) { if ((nfds = SNDIO_sio_pollfd(this->hidden->dev, this->hidden->pfd, POLLIN)) <= 0 || poll(this->hidden->pfd, nfds, INFTIM) < 0) { return -1; } revents = SNDIO_sio_revents(this->hidden->dev, this->hidden->pfd); if (revents & POLLIN) { r = SNDIO_sio_read(this->hidden->dev, buffer, buflen); } if (revents & POLLHUP) { break; } } return (int) r; } static void SNDIO_FlushCapture(_THIS) { char buf[512]; while (SNDIO_sio_read(this->hidden->dev, buf, sizeof(buf)) != 0) { /* do nothing */; } } static Uint8 * SNDIO_GetDeviceBuf(_THIS) { return this->hidden->mixbuf; } static void SNDIO_CloseDevice(_THIS) { if ( this->hidden->pfd != NULL ) { SDL_free(this->hidden->pfd); } if ( this->hidden->dev != NULL ) { SNDIO_sio_stop(this->hidden->dev); SNDIO_sio_close(this->hidden->dev); } SDL_free(this->hidden->mixbuf); SDL_free(this->hidden); } static int SNDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format); struct sio_par par; int status; this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc(sizeof(*this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); this->hidden->mixlen = this->spec.size; /* Capture devices must be non-blocking for SNDIO_FlushCapture */ if ((this->hidden->dev = SNDIO_sio_open(devname != NULL ? devname : SIO_DEVANY, iscapture ? SIO_REC : SIO_PLAY, iscapture)) == NULL) { return SDL_SetError("sio_open() failed"); } /* Allocate the pollfd array for capture devices */ if (iscapture && (this->hidden->pfd = SDL_malloc(sizeof(struct pollfd) * SNDIO_sio_nfds(this->hidden->dev))) == NULL) { return SDL_OutOfMemory(); } SNDIO_sio_initpar(&par); par.rate = this->spec.freq; par.pchan = this->spec.channels; par.round = this->spec.samples; par.appbufsz = par.round * 2; /* Try for a closest match on audio format */ status = -1; while (test_format && (status < 0)) { if (!SDL_AUDIO_ISFLOAT(test_format)) { par.le = SDL_AUDIO_ISLITTLEENDIAN(test_format) ? 1 : 0; par.sig = SDL_AUDIO_ISSIGNED(test_format) ? 1 : 0; par.bits = SDL_AUDIO_BITSIZE(test_format); if (SNDIO_sio_setpar(this->hidden->dev, &par) == 0) { continue; } if (SNDIO_sio_getpar(this->hidden->dev, &par) == 0) { return SDL_SetError("sio_getpar() failed"); } if (par.bps != SIO_BPS(par.bits)) { continue; } if ((par.bits == 8 * par.bps) || (par.msb)) { status = 0; break; } } test_format = SDL_NextAudioFormat(); } if (status < 0) { return SDL_SetError("sndio: Couldn't find any hardware audio formats"); } if ((par.bps == 4) && (par.sig) && (par.le)) this->spec.format = AUDIO_S32LSB; else if ((par.bps == 4) && (par.sig) && (!par.le)) this->spec.format = AUDIO_S32MSB; else if ((par.bps == 2) && (par.sig) && (par.le)) this->spec.format = AUDIO_S16LSB; else if ((par.bps == 2) && (par.sig) && (!par.le)) this->spec.format = AUDIO_S16MSB; else if ((par.bps == 2) && (!par.sig) && (par.le)) this->spec.format = AUDIO_U16LSB; else if ((par.bps == 2) && (!par.sig) && (!par.le)) this->spec.format = AUDIO_U16MSB; else if ((par.bps == 1) && (par.sig)) this->spec.format = AUDIO_S8; else if ((par.bps == 1) && (!par.sig)) this->spec.format = AUDIO_U8; else { return SDL_SetError("sndio: Got unsupported hardware audio format."); } this->spec.freq = par.rate; this->spec.channels = par.pchan; this->spec.samples = par.round; /* Calculate the final parameters for this audio specification */ SDL_CalculateAudioSpec(&this->spec); /* Allocate mixing buffer */ this->hidden->mixlen = this->spec.size; this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen); if (this->hidden->mixbuf == NULL) { return SDL_OutOfMemory(); } SDL_memset(this->hidden->mixbuf, this->spec.silence, this->hidden->mixlen); if (!SNDIO_sio_start(this->hidden->dev)) { return SDL_SetError("sio_start() failed"); } /* We're ready to rock and roll. :-) */ return 0; } static void SNDIO_Deinitialize(void) { UnloadSNDIOLibrary(); } static int SNDIO_Init(SDL_AudioDriverImpl * impl) { if (LoadSNDIOLibrary() < 0) { return 0; } /* Set the function pointers */ impl->OpenDevice = SNDIO_OpenDevice; impl->WaitDevice = SNDIO_WaitDevice; impl->PlayDevice = SNDIO_PlayDevice; impl->GetDeviceBuf = SNDIO_GetDeviceBuf; impl->CloseDevice = SNDIO_CloseDevice; impl->CaptureFromDevice = SNDIO_CaptureFromDevice; impl->FlushCapture = SNDIO_FlushCapture; impl->Deinitialize = SNDIO_Deinitialize; impl->AllowsArbitraryDeviceNames = 1; impl->HasCaptureSupport = SDL_TRUE; return 1; /* this audio target is available. */ } AudioBootStrap SNDIO_bootstrap = { "sndio", "OpenBSD sndio", SNDIO_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_SNDIO */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/sndio/SDL_sndioaudio.c
C
apache-2.0
10,426
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_sndioaudio_h_ #define SDL_sndioaudio_h_ #include <poll.h> #include <sndio.h> #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The audio device handle */ struct sio_hdl *dev; /* Raw mixing buffer */ Uint8 *mixbuf; int mixlen; /* Polling structures for non-blocking sndio devices */ struct pollfd *pfd; }; #endif /* SDL_sndioaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/sndio/SDL_sndioaudio.h
C
apache-2.0
1,493
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_sunaudio_h_ #define SDL_sunaudio_h_ #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #define _THIS SDL_AudioDevice *this struct SDL_PrivateAudioData { /* The file descriptor for the audio device */ int audio_fd; SDL_AudioFormat audio_fmt; /* The app audio format */ Uint8 *mixbuf; /* The app mixing buffer */ int ulaw_only; /* Flag -- does hardware only output U-law? */ Uint8 *ulaw_buf; /* The U-law mixing buffer */ Sint32 written; /* The number of samples written */ int fragsize; /* The audio fragment size in samples */ int frequency; /* The audio frequency in KHz */ }; #endif /* SDL_sunaudio_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/sun/SDL_sunaudio.h
C
apache-2.0
1,777
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" #if SDL_AUDIO_DRIVER_WASAPI #include "../../core/windows/SDL_windows.h" #include "SDL_audio.h" #include "SDL_timer.h" #include "../SDL_audio_c.h" #include "../SDL_sysaudio.h" #include "SDL_assert.h" #define COBJMACROS #include <mmdeviceapi.h> #include <audioclient.h> #include "SDL_wasapi.h" /* This constant isn't available on MinGW-w64 */ #ifndef AUDCLNT_STREAMFLAGS_RATEADJUST #define AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000 #endif /* these increment as default devices change. Opened default devices pick up changes in their threads. */ SDL_atomic_t WASAPI_DefaultPlaybackGeneration; SDL_atomic_t WASAPI_DefaultCaptureGeneration; /* This is a list of device id strings we have inflight, so we have consistent pointers to the same device. */ typedef struct DevIdList { WCHAR *str; struct DevIdList *next; } DevIdList; static DevIdList *deviceid_list = NULL; /* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */ static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483,{ 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } }; static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0,{ 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } }; static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static SDL_bool WStrEqual(const WCHAR *a, const WCHAR *b) { while (*a) { if (*a != *b) { return SDL_FALSE; } a++; b++; } return *b == 0; } static size_t WStrLen(const WCHAR *wstr) { size_t retval = 0; if (wstr) { while (*(wstr++)) { retval++; } } return retval; } static WCHAR * WStrDupe(const WCHAR *wstr) { const size_t len = (WStrLen(wstr) + 1) * sizeof (WCHAR); WCHAR *retval = (WCHAR *) SDL_malloc(len); if (retval) { SDL_memcpy(retval, wstr, len); } return retval; } void WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid) { DevIdList *i; DevIdList *next; DevIdList *prev = NULL; for (i = deviceid_list; i; i = next) { next = i->next; if (WStrEqual(i->str, devid)) { if (prev) { prev->next = next; } else { deviceid_list = next; } SDL_RemoveAudioDevice(iscapture, i->str); SDL_free(i->str); SDL_free(i); } prev = i; } } void WASAPI_AddDevice(const SDL_bool iscapture, const char *devname, LPCWSTR devid) { DevIdList *devidlist; /* You can have multiple endpoints on a device that are mutually exclusive ("Speakers" vs "Line Out" or whatever). In a perfect world, things that are unplugged won't be in this collection. The only gotcha is probably for phones and tablets, where you might have an internal speaker and a headphone jack and expect both to be available and switch automatically. (!!! FIXME...?) */ /* see if we already have this one. */ for (devidlist = deviceid_list; devidlist; devidlist = devidlist->next) { if (WStrEqual(devidlist->str, devid)) { return; /* we already have this. */ } } devidlist = (DevIdList *) SDL_malloc(sizeof (*devidlist)); if (!devidlist) { return; /* oh well. */ } devid = WStrDupe(devid); if (!devid) { SDL_free(devidlist); return; /* oh well. */ } devidlist->str = (WCHAR *) devid; devidlist->next = deviceid_list; deviceid_list = devidlist; SDL_AddAudioDevice(iscapture, devname, (void *) devid); } static void WASAPI_DetectDevices(void) { WASAPI_EnumerateEndpoints(); } static SDL_INLINE SDL_bool WasapiFailed(_THIS, const HRESULT err) { if (err == S_OK) { return SDL_FALSE; } if (err == AUDCLNT_E_DEVICE_INVALIDATED) { this->hidden->device_lost = SDL_TRUE; } else if (SDL_AtomicGet(&this->enabled)) { IAudioClient_Stop(this->hidden->client); SDL_OpenedAudioDeviceDisconnected(this); SDL_assert(!SDL_AtomicGet(&this->enabled)); } return SDL_TRUE; } static int UpdateAudioStream(_THIS, const SDL_AudioSpec *oldspec) { /* Since WASAPI requires us to handle all audio conversion, and our device format might have changed, we might have to add/remove/change the audio stream that the higher level uses to convert data, so SDL keeps firing the callback as if nothing happened here. */ if ( (this->callbackspec.channels == this->spec.channels) && (this->callbackspec.format == this->spec.format) && (this->callbackspec.freq == this->spec.freq) && (this->callbackspec.samples == this->spec.samples) ) { /* no need to buffer/convert in an AudioStream! */ SDL_FreeAudioStream(this->stream); this->stream = NULL; } else if ( (oldspec->channels == this->spec.channels) && (oldspec->format == this->spec.format) && (oldspec->freq == this->spec.freq) ) { /* The existing audio stream is okay to keep using. */ } else { /* replace the audiostream for new format */ SDL_FreeAudioStream(this->stream); if (this->iscapture) { this->stream = SDL_NewAudioStream(this->spec.format, this->spec.channels, this->spec.freq, this->callbackspec.format, this->callbackspec.channels, this->callbackspec.freq); } else { this->stream = SDL_NewAudioStream(this->callbackspec.format, this->callbackspec.channels, this->callbackspec.freq, this->spec.format, this->spec.channels, this->spec.freq); } if (!this->stream) { return -1; } } /* make sure our scratch buffer can cover the new device spec. */ if (this->spec.size > this->work_buffer_len) { Uint8 *ptr = (Uint8 *) SDL_realloc(this->work_buffer, this->spec.size); if (ptr == NULL) { return SDL_OutOfMemory(); } this->work_buffer = ptr; this->work_buffer_len = this->spec.size; } return 0; } static void ReleaseWasapiDevice(_THIS); static SDL_bool RecoverWasapiDevice(_THIS) { ReleaseWasapiDevice(this); /* dump the lost device's handles. */ if (this->hidden->default_device_generation) { this->hidden->default_device_generation = SDL_AtomicGet(this->iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration); } /* this can fail for lots of reasons, but the most likely is we had a non-default device that was disconnected, so we can't recover. Default devices try to reinitialize whatever the new default is, so it's more likely to carry on here, but this handles a non-default device that simply had its format changed in the Windows Control Panel. */ if (WASAPI_ActivateDevice(this, SDL_TRUE) == -1) { SDL_OpenedAudioDeviceDisconnected(this); return SDL_FALSE; } this->hidden->device_lost = SDL_FALSE; return SDL_TRUE; /* okay, carry on with new device details! */ } static SDL_bool RecoverWasapiIfLost(_THIS) { const int generation = this->hidden->default_device_generation; SDL_bool lost = this->hidden->device_lost; if (!SDL_AtomicGet(&this->enabled)) { return SDL_FALSE; /* already failed. */ } if (!this->hidden->client) { return SDL_TRUE; /* still waiting for activation. */ } if (!lost && (generation > 0)) { /* is a default device? */ const int newgen = SDL_AtomicGet(this->iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration); if (generation != newgen) { /* the desired default device was changed, jump over to it. */ lost = SDL_TRUE; } } return lost ? RecoverWasapiDevice(this) : SDL_TRUE; } static Uint8 * WASAPI_GetDeviceBuf(_THIS) { /* get an endpoint buffer from WASAPI. */ BYTE *buffer = NULL; while (RecoverWasapiIfLost(this) && this->hidden->render) { if (!WasapiFailed(this, IAudioRenderClient_GetBuffer(this->hidden->render, this->spec.samples, &buffer))) { return (Uint8 *) buffer; } SDL_assert(buffer == NULL); } return (Uint8 *) buffer; } static void WASAPI_PlayDevice(_THIS) { if (this->hidden->render != NULL) { /* definitely activated? */ /* WasapiFailed() will mark the device for reacquisition or removal elsewhere. */ WasapiFailed(this, IAudioRenderClient_ReleaseBuffer(this->hidden->render, this->spec.samples, 0)); } } static void WASAPI_WaitDevice(_THIS) { while (RecoverWasapiIfLost(this) && this->hidden->client && this->hidden->event) { DWORD waitResult = WaitForSingleObjectEx(this->hidden->event, 200, FALSE); if (waitResult == WAIT_OBJECT_0) { const UINT32 maxpadding = this->spec.samples; UINT32 padding = 0; if (!WasapiFailed(this, IAudioClient_GetCurrentPadding(this->hidden->client, &padding))) { /*SDL_Log("WASAPI EVENT! padding=%u maxpadding=%u", (unsigned int)padding, (unsigned int)maxpadding);*/ if (padding <= maxpadding) { break; } } } else if (waitResult != WAIT_TIMEOUT) { /*SDL_Log("WASAPI FAILED EVENT!");*/ IAudioClient_Stop(this->hidden->client); SDL_OpenedAudioDeviceDisconnected(this); } } } static int WASAPI_CaptureFromDevice(_THIS, void *buffer, int buflen) { SDL_AudioStream *stream = this->hidden->capturestream; const int avail = SDL_AudioStreamAvailable(stream); if (avail > 0) { const int cpy = SDL_min(buflen, avail); SDL_AudioStreamGet(stream, buffer, cpy); return cpy; } while (RecoverWasapiIfLost(this)) { HRESULT ret; BYTE *ptr = NULL; UINT32 frames = 0; DWORD flags = 0; /* uhoh, client isn't activated yet, just return silence. */ if (!this->hidden->capture) { /* Delay so we run at about the speed that audio would be arriving. */ SDL_Delay(((this->spec.samples * 1000) / this->spec.freq)); SDL_memset(buffer, this->spec.silence, buflen); return buflen; } ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL); if (ret != AUDCLNT_S_BUFFER_EMPTY) { WasapiFailed(this, ret); /* mark device lost/failed if necessary. */ } if ((ret == AUDCLNT_S_BUFFER_EMPTY) || !frames) { WASAPI_WaitDevice(this); } else if (ret == S_OK) { const int total = ((int) frames) * this->hidden->framesize; const int cpy = SDL_min(buflen, total); const int leftover = total - cpy; const SDL_bool silent = (flags & AUDCLNT_BUFFERFLAGS_SILENT) ? SDL_TRUE : SDL_FALSE; if (silent) { SDL_memset(buffer, this->spec.silence, cpy); } else { SDL_memcpy(buffer, ptr, cpy); } if (leftover > 0) { ptr += cpy; if (silent) { SDL_memset(ptr, this->spec.silence, leftover); /* I guess this is safe? */ } if (SDL_AudioStreamPut(stream, ptr, leftover) == -1) { return -1; /* uhoh, out of memory, etc. Kill device. :( */ } } ret = IAudioCaptureClient_ReleaseBuffer(this->hidden->capture, frames); WasapiFailed(this, ret); /* mark device lost/failed if necessary. */ return cpy; } } return -1; /* unrecoverable error. */ } static void WASAPI_FlushCapture(_THIS) { BYTE *ptr = NULL; UINT32 frames = 0; DWORD flags = 0; if (!this->hidden->capture) { return; /* not activated yet? */ } /* just read until we stop getting packets, throwing them away. */ while (SDL_TRUE) { const HRESULT ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL); if (ret == AUDCLNT_S_BUFFER_EMPTY) { break; /* no more buffered data; we're done. */ } else if (WasapiFailed(this, ret)) { break; /* failed for some other reason, abort. */ } else if (WasapiFailed(this, IAudioCaptureClient_ReleaseBuffer(this->hidden->capture, frames))) { break; /* something broke. */ } } SDL_AudioStreamClear(this->hidden->capturestream); } static void ReleaseWasapiDevice(_THIS) { if (this->hidden->client) { IAudioClient_Stop(this->hidden->client); IAudioClient_SetEventHandle(this->hidden->client, NULL); IAudioClient_Release(this->hidden->client); this->hidden->client = NULL; } if (this->hidden->render) { IAudioRenderClient_Release(this->hidden->render); this->hidden->render = NULL; } if (this->hidden->capture) { IAudioCaptureClient_Release(this->hidden->capture); this->hidden->capture = NULL; } if (this->hidden->waveformat) { CoTaskMemFree(this->hidden->waveformat); this->hidden->waveformat = NULL; } if (this->hidden->capturestream) { SDL_FreeAudioStream(this->hidden->capturestream); this->hidden->capturestream = NULL; } if (this->hidden->activation_handler) { WASAPI_PlatformDeleteActivationHandler(this->hidden->activation_handler); this->hidden->activation_handler = NULL; } if (this->hidden->event) { CloseHandle(this->hidden->event); this->hidden->event = NULL; } } static void WASAPI_CloseDevice(_THIS) { WASAPI_UnrefDevice(this); } void WASAPI_RefDevice(_THIS) { SDL_AtomicIncRef(&this->hidden->refcount); } void WASAPI_UnrefDevice(_THIS) { if (!SDL_AtomicDecRef(&this->hidden->refcount)) { return; } /* actual closing happens here. */ /* don't touch this->hidden->task in here; it has to be reverted from our callback thread. We do that in WASAPI_ThreadDeinit(). (likewise for this->hidden->coinitialized). */ ReleaseWasapiDevice(this); SDL_free(this->hidden->devid); SDL_free(this->hidden); } /* This is called once a device is activated, possibly asynchronously. */ int WASAPI_PrepDevice(_THIS, const SDL_bool updatestream) { /* !!! FIXME: we could request an exclusive mode stream, which is lower latency; !!! it will write into the kernel's audio buffer directly instead of !!! shared memory that a user-mode mixer then writes to the kernel with !!! everything else. Doing this means any other sound using this device will !!! stop playing, including the user's MP3 player and system notification !!! sounds. You'd probably need to release the device when the app isn't in !!! the foreground, to be a good citizen of the system. It's doable, but it's !!! more work and causes some annoyances, and I don't know what the latency !!! wins actually look like. Maybe add a hint to force exclusive mode at !!! some point. To be sure, defaulting to shared mode is the right thing to !!! do in any case. */ const SDL_AudioSpec oldspec = this->spec; const AUDCLNT_SHAREMODE sharemode = AUDCLNT_SHAREMODE_SHARED; UINT32 bufsize = 0; /* this is in sample frames, not samples, not bytes. */ REFERENCE_TIME default_period = 0; IAudioClient *client = this->hidden->client; IAudioRenderClient *render = NULL; IAudioCaptureClient *capture = NULL; WAVEFORMATEX *waveformat = NULL; SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format); SDL_AudioFormat wasapi_format = 0; SDL_bool valid_format = SDL_FALSE; HRESULT ret = S_OK; DWORD streamflags = 0; SDL_assert(client != NULL); #ifdef __WINRT__ /* CreateEventEx() arrived in Vista, so we need an #ifdef for XP. */ this->hidden->event = CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS); #else this->hidden->event = CreateEventW(NULL, 0, 0, NULL); #endif if (this->hidden->event == NULL) { return WIN_SetError("WASAPI can't create an event handle"); } ret = IAudioClient_GetMixFormat(client, &waveformat); if (FAILED(ret)) { return WIN_SetErrorFromHRESULT("WASAPI can't determine mix format", ret); } SDL_assert(waveformat != NULL); this->hidden->waveformat = waveformat; this->spec.channels = (Uint8) waveformat->nChannels; /* Make sure we have a valid format that we can convert to whatever WASAPI wants. */ if ((waveformat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) && (waveformat->wBitsPerSample == 32)) { wasapi_format = AUDIO_F32SYS; } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 16)) { wasapi_format = AUDIO_S16SYS; } else if ((waveformat->wFormatTag == WAVE_FORMAT_PCM) && (waveformat->wBitsPerSample == 32)) { wasapi_format = AUDIO_S32SYS; } else if (waveformat->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { const WAVEFORMATEXTENSIBLE *ext = (const WAVEFORMATEXTENSIBLE *) waveformat; if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 32)) { wasapi_format = AUDIO_F32SYS; } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 16)) { wasapi_format = AUDIO_S16SYS; } else if ((SDL_memcmp(&ext->SubFormat, &SDL_KSDATAFORMAT_SUBTYPE_PCM, sizeof (GUID)) == 0) && (waveformat->wBitsPerSample == 32)) { wasapi_format = AUDIO_S32SYS; } } while ((!valid_format) && (test_format)) { if (test_format == wasapi_format) { this->spec.format = test_format; valid_format = SDL_TRUE; break; } test_format = SDL_NextAudioFormat(); } if (!valid_format) { return SDL_SetError("WASAPI: Unsupported audio format"); } ret = IAudioClient_GetDevicePeriod(client, &default_period, NULL); if (FAILED(ret)) { return WIN_SetErrorFromHRESULT("WASAPI can't determine minimum device period", ret); } /* favor WASAPI's resampler over our own, in Win7+. */ if (this->spec.freq != waveformat->nSamplesPerSec) { /* RATEADJUST only works with output devices in share mode, and is available in Win7 and later.*/ if (WIN_IsWindows7OrGreater() && !this->iscapture && (sharemode == AUDCLNT_SHAREMODE_SHARED)) { streamflags |= AUDCLNT_STREAMFLAGS_RATEADJUST; waveformat->nSamplesPerSec = this->spec.freq; waveformat->nAvgBytesPerSec = waveformat->nSamplesPerSec * waveformat->nChannels * (waveformat->wBitsPerSample / 8); } else { this->spec.freq = waveformat->nSamplesPerSec; /* force sampling rate so our resampler kicks in. */ } } streamflags |= AUDCLNT_STREAMFLAGS_EVENTCALLBACK; ret = IAudioClient_Initialize(client, sharemode, streamflags, 0, 0, waveformat, NULL); if (FAILED(ret)) { return WIN_SetErrorFromHRESULT("WASAPI can't initialize audio client", ret); } ret = IAudioClient_SetEventHandle(client, this->hidden->event); if (FAILED(ret)) { return WIN_SetErrorFromHRESULT("WASAPI can't set event handle", ret); } ret = IAudioClient_GetBufferSize(client, &bufsize); if (FAILED(ret)) { return WIN_SetErrorFromHRESULT("WASAPI can't determine buffer size", ret); } /* Match the callback size to the period size to cut down on the number of interrupts waited for in each call to WaitDevice */ { const float period_millis = default_period / 10000.0f; const float period_frames = period_millis * this->spec.freq / 1000.0f; this->spec.samples = (Uint16)SDL_ceilf(period_frames); } /* Update the fragment size as size in bytes */ SDL_CalculateAudioSpec(&this->spec); this->hidden->framesize = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels; if (this->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 */ } ret = IAudioClient_GetService(client, &SDL_IID_IAudioCaptureClient, (void**) &capture); if (FAILED(ret)) { return WIN_SetErrorFromHRESULT("WASAPI can't get capture client service", ret); } SDL_assert(capture != NULL); this->hidden->capture = capture; ret = IAudioClient_Start(client); if (FAILED(ret)) { return WIN_SetErrorFromHRESULT("WASAPI can't start capture", ret); } WASAPI_FlushCapture(this); /* MSDN says you should flush capture endpoint right after startup. */ } else { ret = IAudioClient_GetService(client, &SDL_IID_IAudioRenderClient, (void**) &render); if (FAILED(ret)) { return WIN_SetErrorFromHRESULT("WASAPI can't get render client service", ret); } SDL_assert(render != NULL); this->hidden->render = render; ret = IAudioClient_Start(client); if (FAILED(ret)) { return WIN_SetErrorFromHRESULT("WASAPI can't start playback", ret); } } if (updatestream) { if (UpdateAudioStream(this, &oldspec) == -1) { return -1; } } return 0; /* good to go. */ } static int WASAPI_OpenDevice(_THIS, void *handle, const char *devname, int iscapture) { LPCWSTR devid = (LPCWSTR) handle; /* Initialize all variables that we clean on shutdown */ this->hidden = (struct SDL_PrivateAudioData *) SDL_malloc((sizeof *this->hidden)); if (this->hidden == NULL) { return SDL_OutOfMemory(); } SDL_zerop(this->hidden); WASAPI_RefDevice(this); /* so CloseDevice() will unref to zero. */ if (!devid) { /* is default device? */ this->hidden->default_device_generation = SDL_AtomicGet(iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration); } else { this->hidden->devid = WStrDupe(devid); if (!this->hidden->devid) { return SDL_OutOfMemory(); } } if (WASAPI_ActivateDevice(this, SDL_FALSE) == -1) { return -1; /* already set error. */ } /* Ready, but waiting for async device activation. Until activation is successful, we will report silence from capture devices and ignore data on playback devices. Also, since we don't know the _actual_ device format until after activation, we let the app have whatever it asks for. We set up an SDL_AudioStream to convert, if necessary, once the activation completes. */ return 0; } static void WASAPI_ThreadInit(_THIS) { WASAPI_PlatformThreadInit(this); } static void WASAPI_ThreadDeinit(_THIS) { WASAPI_PlatformThreadDeinit(this); } void WASAPI_BeginLoopIteration(_THIS) { /* no-op. */ } static void WASAPI_Deinitialize(void) { DevIdList *devidlist; DevIdList *next; WASAPI_PlatformDeinit(); for (devidlist = deviceid_list; devidlist; devidlist = next) { next = devidlist->next; SDL_free(devidlist->str); SDL_free(devidlist); } deviceid_list = NULL; } static int WASAPI_Init(SDL_AudioDriverImpl * impl) { SDL_AtomicSet(&WASAPI_DefaultPlaybackGeneration, 1); SDL_AtomicSet(&WASAPI_DefaultCaptureGeneration, 1); if (WASAPI_PlatformInit() == -1) { return 0; } /* Set the function pointers */ impl->DetectDevices = WASAPI_DetectDevices; impl->ThreadInit = WASAPI_ThreadInit; impl->ThreadDeinit = WASAPI_ThreadDeinit; impl->BeginLoopIteration = WASAPI_BeginLoopIteration; impl->OpenDevice = WASAPI_OpenDevice; impl->PlayDevice = WASAPI_PlayDevice; impl->WaitDevice = WASAPI_WaitDevice; impl->GetDeviceBuf = WASAPI_GetDeviceBuf; impl->CaptureFromDevice = WASAPI_CaptureFromDevice; impl->FlushCapture = WASAPI_FlushCapture; impl->CloseDevice = WASAPI_CloseDevice; impl->Deinitialize = WASAPI_Deinitialize; impl->HasCaptureSupport = 1; return 1; /* this audio target is available. */ } AudioBootStrap WASAPI_bootstrap = { "wasapi", "WASAPI", WASAPI_Init, 0 }; #endif /* SDL_AUDIO_DRIVER_WASAPI */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/wasapi/SDL_wasapi.c
C
apache-2.0
26,094
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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_wasapi_h_ #define SDL_wasapi_h_ #ifdef __cplusplus extern "C" { #endif #include "../SDL_sysaudio.h" /* Hidden "this" pointer for the audio functions */ #ifdef __cplusplus #define _THIS SDL_AudioDevice *_this #else #define _THIS SDL_AudioDevice *this #endif struct SDL_PrivateAudioData { SDL_atomic_t refcount; WCHAR *devid; WAVEFORMATEX *waveformat; IAudioClient *client; IAudioRenderClient *render; IAudioCaptureClient *capture; SDL_AudioStream *capturestream; HANDLE event; HANDLE task; SDL_bool coinitialized; int framesize; int default_device_generation; SDL_bool device_lost; void *activation_handler; SDL_atomic_t just_activated; }; /* these increment as default devices change. Opened default devices pick up changes in their threads. */ extern SDL_atomic_t WASAPI_DefaultPlaybackGeneration; extern SDL_atomic_t WASAPI_DefaultCaptureGeneration; /* win32 and winrt implementations call into these. */ int WASAPI_PrepDevice(_THIS, const SDL_bool updatestream); void WASAPI_RefDevice(_THIS); void WASAPI_UnrefDevice(_THIS); void WASAPI_AddDevice(const SDL_bool iscapture, const char *devname, LPCWSTR devid); void WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid); /* These are functions that are implemented differently for Windows vs WinRT. */ int WASAPI_PlatformInit(void); void WASAPI_PlatformDeinit(void); void WASAPI_EnumerateEndpoints(void); int WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery); void WASAPI_PlatformThreadInit(_THIS); void WASAPI_PlatformThreadDeinit(_THIS); void WASAPI_PlatformDeleteActivationHandler(void *handler); void WASAPI_BeginLoopIteration(_THIS); #ifdef __cplusplus } #endif #endif /* SDL_wasapi_h_ */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/wasapi/SDL_wasapi.h
C
apache-2.0
2,748
/* Simple DirectMedia Layer Copyright (C) 1997-2020 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" /* This is code that Windows uses to talk to WASAPI-related system APIs. This is for non-WinRT desktop apps. The C++/CX implementation of these functions, exclusive to WinRT, are in SDL_wasapi_winrt.cpp. The code in SDL_wasapi.c is used by both standard Windows and WinRT builds to deal with audio and calls into these functions. */ #if SDL_AUDIO_DRIVER_WASAPI && !defined(__WINRT__) #include "../../core/windows/SDL_windows.h" #include "SDL_audio.h" #include "SDL_timer.h" #include "../SDL_audio_c.h" #include "../SDL_sysaudio.h" #include "SDL_assert.h" #define COBJMACROS #include <mmdeviceapi.h> #include <audioclient.h> #include "SDL_wasapi.h" static const ERole SDL_WASAPI_role = eConsole; /* !!! FIXME: should this be eMultimedia? Should be a hint? */ /* This is global to the WASAPI target, to handle hotplug and default device lookup. */ static IMMDeviceEnumerator *enumerator = NULL; /* PropVariantInit() is an inline function/macro in PropIdl.h that calls the C runtime's memset() directly. Use ours instead, to avoid dependency. */ #ifdef PropVariantInit #undef PropVariantInit #endif #define PropVariantInit(p) SDL_zerop(p) /* handle to Avrt.dll--Vista and later!--for flagging the callback thread as "Pro Audio" (low latency). */ static HMODULE libavrt = NULL; typedef HANDLE(WINAPI *pfnAvSetMmThreadCharacteristicsW)(LPWSTR, LPDWORD); typedef BOOL(WINAPI *pfnAvRevertMmThreadCharacteristics)(HANDLE); static pfnAvSetMmThreadCharacteristicsW pAvSetMmThreadCharacteristicsW = NULL; static pfnAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL; /* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */ static const CLSID SDL_CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c,{ 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } }; static const IID SDL_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35,{ 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } }; static const IID SDL_IID_IMMNotificationClient = { 0x7991eec9, 0x7e89, 0x4d85,{ 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0 } }; static const IID SDL_IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089,{ 0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5 } }; static const IID SDL_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32,{ 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2 } }; static const PROPERTYKEY SDL_PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd,{ 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, } }, 14 }; static char * GetWasapiDeviceName(IMMDevice *device) { /* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be "SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in its own UIs, like Volume Control, etc. */ char *utf8dev = NULL; IPropertyStore *props = NULL; if (SUCCEEDED(IMMDevice_OpenPropertyStore(device, STGM_READ, &props))) { PROPVARIANT var; PropVariantInit(&var); if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_Device_FriendlyName, &var))) { utf8dev = WIN_StringToUTF8(var.pwszVal); } PropVariantClear(&var); IPropertyStore_Release(props); } return utf8dev; } /* We need a COM subclass of IMMNotificationClient for hotplug support, which is easy in C++, but we have to tapdance more to make work in C. Thanks to this page for coaching on how to make this work: https://www.codeproject.com/Articles/13601/COM-in-plain-C */ typedef struct SDLMMNotificationClient { const IMMNotificationClientVtbl *lpVtbl; SDL_atomic_t refcount; } SDLMMNotificationClient; static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_QueryInterface(IMMNotificationClient *this, REFIID iid, void **ppv) { if ((WIN_IsEqualIID(iid, &IID_IUnknown)) || (WIN_IsEqualIID(iid, &SDL_IID_IMMNotificationClient))) { *ppv = this; this->lpVtbl->AddRef(this); return S_OK; } *ppv = NULL; return E_NOINTERFACE; } static ULONG STDMETHODCALLTYPE SDLMMNotificationClient_AddRef(IMMNotificationClient *ithis) { SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis; return (ULONG) (SDL_AtomicIncRef(&this->refcount) + 1); } static ULONG STDMETHODCALLTYPE SDLMMNotificationClient_Release(IMMNotificationClient *ithis) { /* this is a static object; we don't ever free it. */ SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis; const ULONG retval = SDL_AtomicDecRef(&this->refcount); if (retval == 0) { SDL_AtomicSet(&this->refcount, 0); /* uhh... */ return 0; } return retval - 1; } /* These are the entry points called when WASAPI device endpoints change. */ static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *ithis, EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId) { if (role != SDL_WASAPI_role) { return S_OK; /* ignore it. */ } /* Increment the "generation," so opened devices will pick this up in their threads. */ switch (flow) { case eRender: SDL_AtomicAdd(&WASAPI_DefaultPlaybackGeneration, 1); break; case eCapture: SDL_AtomicAdd(&WASAPI_DefaultCaptureGeneration, 1); break; case eAll: SDL_AtomicAdd(&WASAPI_DefaultPlaybackGeneration, 1); SDL_AtomicAdd(&WASAPI_DefaultCaptureGeneration, 1); break; default: SDL_assert(!"uhoh, unexpected OnDefaultDeviceChange flow!"); break; } return S_OK; } static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId) { /* we ignore this; devices added here then progress to ACTIVE, if appropriate, in OnDeviceStateChange, making that a better place to deal with device adds. More importantly: the first time you plug in a USB audio device, this callback will fire, but when you unplug it, it isn't removed (it's state changes to NOTPRESENT). Plugging it back in won't fire this callback again. */ return S_OK; } static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceRemoved(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId) { /* See notes in OnDeviceAdded handler about why we ignore this. */ return S_OK; } static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId, DWORD dwNewState) { IMMDevice *device = NULL; if (SUCCEEDED(IMMDeviceEnumerator_GetDevice(enumerator, pwstrDeviceId, &device))) { IMMEndpoint *endpoint = NULL; if (SUCCEEDED(IMMDevice_QueryInterface(device, &SDL_IID_IMMEndpoint, (void **) &endpoint))) { EDataFlow flow; if (SUCCEEDED(IMMEndpoint_GetDataFlow(endpoint, &flow))) { const SDL_bool iscapture = (flow == eCapture); if (dwNewState == DEVICE_STATE_ACTIVE) { char *utf8dev = GetWasapiDeviceName(device); if (utf8dev) { WASAPI_AddDevice(iscapture, utf8dev, pwstrDeviceId); SDL_free(utf8dev); } } else { WASAPI_RemoveDevice(iscapture, pwstrDeviceId); } } IMMEndpoint_Release(endpoint); } IMMDevice_Release(device); } return S_OK; } static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnPropertyValueChanged(IMMNotificationClient *this, LPCWSTR pwstrDeviceId, const PROPERTYKEY key) { return S_OK; /* we don't care about these. */ } static const IMMNotificationClientVtbl notification_client_vtbl = { SDLMMNotificationClient_QueryInterface, SDLMMNotificationClient_AddRef, SDLMMNotificationClient_Release, SDLMMNotificationClient_OnDeviceStateChanged, SDLMMNotificationClient_OnDeviceAdded, SDLMMNotificationClient_OnDeviceRemoved, SDLMMNotificationClient_OnDefaultDeviceChanged, SDLMMNotificationClient_OnPropertyValueChanged }; static SDLMMNotificationClient notification_client = { &notification_client_vtbl, { 1 } }; int WASAPI_PlatformInit(void) { HRESULT ret; /* just skip the discussion with COM here. */ if (!WIN_IsWindowsVistaOrGreater()) { return SDL_SetError("WASAPI support requires Windows Vista or later"); } if (FAILED(WIN_CoInitialize())) { return SDL_SetError("WASAPI: CoInitialize() failed"); } ret = CoCreateInstance(&SDL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &SDL_IID_IMMDeviceEnumerator, (LPVOID *) &enumerator); if (FAILED(ret)) { WIN_CoUninitialize(); return WIN_SetErrorFromHRESULT("WASAPI CoCreateInstance(MMDeviceEnumerator)", ret); } libavrt = LoadLibraryW(L"avrt.dll"); /* this library is available in Vista and later. No WinXP, so have to LoadLibrary to use it for now! */ if (libavrt) { pAvSetMmThreadCharacteristicsW = (pfnAvSetMmThreadCharacteristicsW) GetProcAddress(libavrt, "AvSetMmThreadCharacteristicsW"); pAvRevertMmThreadCharacteristics = (pfnAvRevertMmThreadCharacteristics) GetProcAddress(libavrt, "AvRevertMmThreadCharacteristics"); } return 0; } void WASAPI_PlatformDeinit(void) { if (enumerator) { IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *) &notification_client); IMMDeviceEnumerator_Release(enumerator); enumerator = NULL; } if (libavrt) { FreeLibrary(libavrt); libavrt = NULL; } pAvSetMmThreadCharacteristicsW = NULL; pAvRevertMmThreadCharacteristics = NULL; WIN_CoUninitialize(); } void WASAPI_PlatformThreadInit(_THIS) { /* this thread uses COM. */ if (SUCCEEDED(WIN_CoInitialize())) { /* can't report errors, hope it worked! */ this->hidden->coinitialized = SDL_TRUE; } /* Set this thread to very high "Pro Audio" priority. */ if (pAvSetMmThreadCharacteristicsW) { DWORD idx = 0; this->hidden->task = pAvSetMmThreadCharacteristicsW(TEXT("Pro Audio"), &idx); } } void WASAPI_PlatformThreadDeinit(_THIS) { /* Set this thread back to normal priority. */ if (this->hidden->task && pAvRevertMmThreadCharacteristics) { pAvRevertMmThreadCharacteristics(this->hidden->task); this->hidden->task = NULL; } if (this->hidden->coinitialized) { WIN_CoUninitialize(); this->hidden->coinitialized = SDL_FALSE; } } int WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery) { LPCWSTR devid = this->hidden->devid; IMMDevice *device = NULL; HRESULT ret; if (devid == NULL) { const EDataFlow dataflow = this->iscapture ? eCapture : eRender; ret = IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_WASAPI_role, &device); } else { ret = IMMDeviceEnumerator_GetDevice(enumerator, devid, &device); } if (FAILED(ret)) { SDL_assert(device == NULL); this->hidden->client = NULL; return WIN_SetErrorFromHRESULT("WASAPI can't find requested audio endpoint", ret); } /* this is not async in standard win32, yay! */ ret = IMMDevice_Activate(device, &SDL_IID_IAudioClient, CLSCTX_ALL, NULL, (void **) &this->hidden->client); IMMDevice_Release(device); if (FAILED(ret)) { SDL_assert(this->hidden->client == NULL); return WIN_SetErrorFromHRESULT("WASAPI can't activate audio endpoint", ret); } SDL_assert(this->hidden->client != NULL); if (WASAPI_PrepDevice(this, isrecovery) == -1) { /* not async, fire it right away. */ return -1; } return 0; /* good to go. */ } 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" ...one adapter device ("SoundBlaster Pro") might have multiple endpoint devices ("Speakers", "Line-Out"). */ if (FAILED(IMMDeviceEnumerator_EnumAudioEndpoints(enumerator, iscapture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &collection))) { return; } if (FAILED(IMMDeviceCollection_GetCount(collection, &total))) { IMMDeviceCollection_Release(collection); 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); } 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); } void WASAPI_EnumerateEndpoints(void) { WASAPI_EnumerateEndpointsForFlow(SDL_FALSE); /* playback */ WASAPI_EnumerateEndpointsForFlow(SDL_TRUE); /* capture */ /* if this fails, we just won't get hotplug events. Carry on anyhow. */ IMMDeviceEnumerator_RegisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *) &notification_client); } void WASAPI_PlatformDeleteActivationHandler(void *handler) { /* not asynchronous. */ SDL_assert(!"This function should have only been called on WinRT."); } #endif /* SDL_AUDIO_DRIVER_WASAPI && !defined(__WINRT__) */ /* vi: set ts=4 sw=4 expandtab: */
YifuLiu/AliOS-Things
components/SDL2/src/audio/wasapi/SDL_wasapi_win32.c
C
apache-2.0
15,728