From 08226bc6b0147b69a1afb74d83c6a8821e93601b Mon Sep 17 00:00:00 2001 From: Filip Gawin Date: Mon, 29 Oct 2018 02:05:45 +0100 Subject: Simplify some statements --- examples/alrecord.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'examples') diff --git a/examples/alrecord.c b/examples/alrecord.c index 43b26d35..f60a3055 100644 --- a/examples/alrecord.c +++ b/examples/alrecord.c @@ -133,7 +133,7 @@ int main(int argc, char **argv) break; else if(strcmp(argv[0], "--channels") == 0 || strcmp(argv[0], "-c") == 0) { - if(!(argc > 1)) + if(argc < 2) { fprintf(stderr, "Missing argument for option: %s\n", argv[0]); return 1; @@ -150,7 +150,7 @@ int main(int argc, char **argv) } else if(strcmp(argv[0], "--bits") == 0 || strcmp(argv[0], "-b") == 0) { - if(!(argc > 1)) + if(argc < 2) { fprintf(stderr, "Missing argument for option: %s\n", argv[0]); return 1; @@ -168,7 +168,7 @@ int main(int argc, char **argv) } else if(strcmp(argv[0], "--rate") == 0 || strcmp(argv[0], "-r") == 0) { - if(!(argc > 1)) + if(argc < 2) { fprintf(stderr, "Missing argument for option: %s\n", argv[0]); return 1; @@ -185,7 +185,7 @@ int main(int argc, char **argv) } else if(strcmp(argv[0], "--time") == 0 || strcmp(argv[0], "-t") == 0) { - if(!(argc > 1)) + if(argc < 2) { fprintf(stderr, "Missing argument for option: %s\n", argv[0]); return 1; @@ -202,7 +202,7 @@ int main(int argc, char **argv) } else if(strcmp(argv[0], "--outfile") == 0 || strcmp(argv[0], "-o") == 0) { - if(!(argc > 1)) + if(argc < 2) { fprintf(stderr, "Missing argument for option: %s\n", argv[0]); return 1; -- cgit v1.2.3 From f3ce7bc7dcf20275d93974755c42486d812d771f Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 10 Nov 2018 21:09:54 -0800 Subject: Move altimespec_get and al_nssleep to examples' common code --- CMakeLists.txt | 2 +- common/threads.c | 72 --------------------------------------------- common/threads.h | 26 ---------------- examples/common/alhelpers.c | 69 +++++++++++++++++++++++++++++++++++++++++++ examples/common/alhelpers.h | 11 +++++++ 5 files changed, 81 insertions(+), 99 deletions(-) (limited to 'examples') diff --git a/CMakeLists.txt b/CMakeLists.txt index 6079c25b..dc3bad12 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1675,7 +1675,7 @@ IF(ALSOFT_EXAMPLES) ADD_EXECUTABLE(alrecord examples/alrecord.c) TARGET_COMPILE_DEFINITIONS(alrecord PRIVATE ${CPP_DEFS}) TARGET_COMPILE_OPTIONS(alrecord PRIVATE ${C_FLAGS}) - TARGET_LINK_LIBRARIES(alrecord PRIVATE ${LINKER_FLAGS} common OpenAL) + TARGET_LINK_LIBRARIES(alrecord PRIVATE ${LINKER_FLAGS} ex-common common OpenAL) IF(ALSOFT_INSTALL) INSTALL(TARGETS alrecord diff --git a/common/threads.c b/common/threads.c index e8301297..de9fc452 100644 --- a/common/threads.c +++ b/common/threads.c @@ -174,21 +174,6 @@ int althrd_join(althrd_t thr, int *res) return althrd_success; } -int althrd_sleep(const struct timespec *ts, struct timespec* UNUSED(rem)) -{ - DWORD msec; - - if(ts->tv_sec < 0 || ts->tv_sec >= (0x7fffffff / 1000) || - ts->tv_nsec < 0 || ts->tv_nsec >= 1000000000) - return -2; - - msec = (DWORD)(ts->tv_sec * 1000); - msec += (DWORD)((ts->tv_nsec+999999) / 1000000); - Sleep(msec); - - return 0; -} - int almtx_init(almtx_t *mtx, int type) { @@ -381,27 +366,6 @@ void altss_delete(altss_t tss_id) } -int altimespec_get(struct timespec *ts, int base) -{ - static_assert(sizeof(FILETIME) == sizeof(ULARGE_INTEGER), - "Size of FILETIME does not match ULARGE_INTEGER"); - if(base == AL_TIME_UTC) - { - union { - FILETIME ftime; - ULARGE_INTEGER ulint; - } systime; - GetSystemTimeAsFileTime(&systime.ftime); - /* FILETIME is in 100-nanosecond units, or 1/10th of a microsecond. */ - ts->tv_sec = systime.ulint.QuadPart/10000000; - ts->tv_nsec = (systime.ulint.QuadPart%10000000) * 100; - return base; - } - - return 0; -} - - void alcall_once(alonce_flag *once, void (*callback)(void)) { LONG ret; @@ -447,7 +411,6 @@ void althrd_thread_detach(void) #endif -extern inline int althrd_sleep(const struct timespec *ts, struct timespec *rem); extern inline void alcall_once(alonce_flag *once, void (*callback)(void)); extern inline void althrd_deinit(void); @@ -713,39 +676,4 @@ void altss_delete(altss_t tss_id) pthread_key_delete(tss_id); } - -int altimespec_get(struct timespec *ts, int base) -{ - if(base == AL_TIME_UTC) - { - int ret; -#if _POSIX_TIMERS > 0 - ret = clock_gettime(CLOCK_REALTIME, ts); - if(ret == 0) return base; -#else /* _POSIX_TIMERS > 0 */ - struct timeval tv; - ret = gettimeofday(&tv, NULL); - if(ret == 0) - { - ts->tv_sec = tv.tv_sec; - ts->tv_nsec = tv.tv_usec * 1000; - return base; - } -#endif - } - - return 0; -} - #endif - - -void al_nssleep(unsigned long nsec) -{ - struct timespec ts, rem; - ts.tv_sec = nsec / 1000000000ul; - ts.tv_nsec = nsec % 1000000000ul; - - while(althrd_sleep(&ts, &rem) == -1) - ts = rem; -} diff --git a/common/threads.h b/common/threads.h index 7fbe20cd..c2168cdf 100644 --- a/common/threads.h +++ b/common/threads.h @@ -34,21 +34,11 @@ typedef int (*althrd_start_t)(void*); typedef void (*altss_dtor_t)(void*); -#define AL_TIME_UTC 1 - - #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include -#ifndef HAVE_STRUCT_TIMESPEC -struct timespec { - time_t tv_sec; - long tv_nsec; -}; -#endif - typedef DWORD althrd_t; typedef CRITICAL_SECTION almtx_t; #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0600 @@ -62,7 +52,6 @@ typedef LONG alonce_flag; #define AL_ONCE_FLAG_INIT 0 -int althrd_sleep(const struct timespec *ts, struct timespec *rem); void alcall_once(alonce_flag *once, void (*callback)(void)); void althrd_deinit(void); @@ -171,17 +160,6 @@ inline void althrd_yield(void) sched_yield(); } -inline int althrd_sleep(const struct timespec *ts, struct timespec *rem) -{ - int ret = nanosleep(ts, rem); - if(ret != 0) - { - ret = ((errno==EINTR) ? -1 : -2); - errno = 0; - } - return ret; -} - inline int almtx_lock(almtx_t *mtx) { @@ -257,10 +235,6 @@ int alsem_trywait(alsem_t *sem); int altss_create(altss_t *tss_id, altss_dtor_t callback); void altss_delete(altss_t tss_id); -int altimespec_get(struct timespec *ts, int base); - -void al_nssleep(unsigned long nsec); - #ifdef __cplusplus } // extern "C" diff --git a/examples/common/alhelpers.c b/examples/common/alhelpers.c index fab039e9..657c10d3 100644 --- a/examples/common/alhelpers.c +++ b/examples/common/alhelpers.c @@ -114,3 +114,72 @@ const char *FormatName(ALenum format) } return "Unknown Format"; } + + +#ifdef _WIN32 + +#define WIN32_LEAN_AND_MEAN +#include +#include + +int altimespec_get(struct timespec *ts, int base) +{ + if(base == AL_TIME_UTC) + { + union { + FILETIME ftime; + ULARGE_INTEGER ulint; + } systime; + GetSystemTimeAsFileTime(&systime.ftime); + /* FILETIME is in 100-nanosecond units, or 1/10th of a microsecond. */ + ts->tv_sec = systime.ulint.QuadPart/10000000; + ts->tv_nsec = (systime.ulint.QuadPart%10000000) * 100; + return base; + } + + return 0; +} + +void al_nssleep(unsigned long nsec) +{ + Sleep(nsec / 1000000); +} + +#else + +#include +#include + +int altimespec_get(struct timespec *ts, int base) +{ + if(base == AL_TIME_UTC) + { + int ret; +#if _POSIX_TIMERS > 0 + ret = clock_gettime(CLOCK_REALTIME, ts); + if(ret == 0) return base; +#else /* _POSIX_TIMERS > 0 */ + struct timeval tv; + ret = gettimeofday(&tv, NULL); + if(ret == 0) + { + ts->tv_sec = tv.tv_sec; + ts->tv_nsec = tv.tv_usec * 1000; + return base; + } +#endif + } + + return 0; +} + +void al_nssleep(unsigned long nsec) +{ + struct timespec ts, rem; + ts.tv_sec = nsec / 1000000000ul; + ts.tv_nsec = nsec % 1000000000ul; + while(nanosleep(&ts, &rem) == -1 && errno == EINTR) + ts = rem; +} + +#endif diff --git a/examples/common/alhelpers.h b/examples/common/alhelpers.h index 41a7ce58..e3e638ac 100644 --- a/examples/common/alhelpers.h +++ b/examples/common/alhelpers.h @@ -18,6 +18,17 @@ const char *FormatName(ALenum type); int InitAL(char ***argv, int *argc); void CloseAL(void); +/* Cross-platform timeget and sleep functions. */ +#ifndef HAVE_STRUCT_TIMESPEC +struct timespec { + time_t tv_sec; + long tv_nsec; +}; +#endif +#define AL_TIME_UTC 1 +int altimespec_get(struct timespec *ts, int base); +void al_nssleep(unsigned long nsec); + #ifdef __cplusplus } #endif /* __cplusplus */ -- cgit v1.2.3 From de13f30e286358d8e4f41e457421e4ec9776e3f5 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 18 Nov 2018 05:38:03 -0800 Subject: Improve audio underrun recordery in alffplay Now it has a better idea to skip samples during refill instead of after restarting. --- examples/alffplay.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 27520a6d..f02fb16b 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -992,6 +992,18 @@ int AudioState::handler() */ alSourceRewind(mSource); alSourcei(mSource, AL_BUFFER, 0); + if(alcGetInteger64vSOFT) + { + /* Also update the device start time with the current device + * clock, so the decoder knows we're running behind. + */ + int64_t devtime{}; + alcGetInteger64vSOFT(alcGetContextsDevice(alcGetCurrentContext()), + ALC_DEVICE_CLOCK_SOFT, 1, &devtime); + auto device_time = nanoseconds{devtime}; + + mDeviceStartTime = device_time - mCurrentPts; + } continue; } -- cgit v1.2.3 From dc8ef8264a458282ebad15a6a1b4027cc139cc59 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 20 Nov 2018 12:32:42 -0800 Subject: Try to improve alffplay underrun device time adjustment --- examples/alffplay.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index f02fb16b..771e5ded 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -1002,7 +1002,7 @@ int AudioState::handler() ALC_DEVICE_CLOCK_SOFT, 1, &devtime); auto device_time = nanoseconds{devtime}; - mDeviceStartTime = device_time - mCurrentPts; + mDeviceStartTime = device_time - mCurrentPts + AudioBufferTotalTime; } continue; } -- cgit v1.2.3 From d7d99adc915583416dd8c70491ec7fc4ac71a543 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Mon, 26 Nov 2018 23:18:51 -0800 Subject: Avoid including threads.h in the example helpers --- examples/alrecord.c | 1 + examples/common/alhelpers.c | 1 + examples/common/alhelpers.h | 10 +++++----- 3 files changed, 7 insertions(+), 5 deletions(-) (limited to 'examples') diff --git a/examples/alrecord.c b/examples/alrecord.c index f60a3055..30f5f792 100644 --- a/examples/alrecord.c +++ b/examples/alrecord.c @@ -27,6 +27,7 @@ #include #include #include +#include #include #include "AL/al.h" diff --git a/examples/common/alhelpers.c b/examples/common/alhelpers.c index 657c10d3..6a583497 100644 --- a/examples/common/alhelpers.c +++ b/examples/common/alhelpers.c @@ -29,6 +29,7 @@ * channel configs and sample types. */ #include +#include #include #include "AL/al.h" diff --git a/examples/common/alhelpers.h b/examples/common/alhelpers.h index e3e638ac..14edf5d9 100644 --- a/examples/common/alhelpers.h +++ b/examples/common/alhelpers.h @@ -1,15 +1,15 @@ #ifndef ALHELPERS_H #define ALHELPERS_H +#include + #include "AL/alc.h" #include "AL/al.h" #include "AL/alext.h" -#include "threads.h" - #ifdef __cplusplus extern "C" { -#endif /* __cplusplus */ +#endif /* Some helper functions to get the name from the format enums. */ const char *FormatName(ALenum type); @@ -30,7 +30,7 @@ int altimespec_get(struct timespec *ts, int base); void al_nssleep(unsigned long nsec); #ifdef __cplusplus -} -#endif /* __cplusplus */ +} // extern "C" +#endif #endif /* ALHELPERS_H */ -- cgit v1.2.3 From 2530370ff29009fccad472c9e9194ebdd561a398 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Mon, 26 Nov 2018 23:45:04 -0800 Subject: Avoid relying on struct timespec --- CMakeLists.txt | 7 ------ examples/almultireverb.c | 13 +++++----- examples/common/alhelpers.c | 61 ++++++++++++++++++++++----------------------- examples/common/alhelpers.h | 11 +------- 4 files changed, 37 insertions(+), 55 deletions(-) (limited to 'examples') diff --git a/CMakeLists.txt b/CMakeLists.txt index 26476a67..c9f2e336 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -204,13 +204,6 @@ IF(CMAKE_COMPILER_IS_GNUCC) SET(CMAKE_REQUIRED_FLAGS "${OLD_REQUIRED_FLAGS}") ENDIF() -# Check if we have a proper timespec declaration -CHECK_STRUCT_HAS_MEMBER("struct timespec" tv_sec time.h HAVE_STRUCT_TIMESPEC) -IF(HAVE_STRUCT_TIMESPEC) - # Define it here so we don't have to include config.h for it - SET(CPP_DEFS ${CPP_DEFS} HAVE_STRUCT_TIMESPEC) -ENDIF() - # Some systems may need libatomic for C11 atomic functions to work SET(OLD_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES}) SET(CMAKE_REQUIRED_LIBRARIES ${OLD_REQUIRED_LIBRARIES} atomic) diff --git a/examples/almultireverb.c b/examples/almultireverb.c index a2587585..e512d399 100644 --- a/examples/almultireverb.c +++ b/examples/almultireverb.c @@ -452,7 +452,7 @@ int main(int argc, char **argv) EFX_REVERB_PRESET_CARPETEDHALLWAY, EFX_REVERB_PRESET_BATHROOM }; - struct timespec basetime; + unsigned int basetime; ALCdevice *device = NULL; ALCcontext *context = NULL; ALuint effects[2] = { 0, 0 }; @@ -633,14 +633,14 @@ int main(int argc, char **argv) assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); /* Get the current time as the base for timing in the main loop. */ - altimespec_get(&basetime, AL_TIME_UTC); + basetime = altime_get(); loops = 0; printf("Transition %d of %d...\n", loops+1, MaxTransitions); /* Play the sound for a while. */ alSourcePlay(source); do { - struct timespec curtime; + unsigned int curtime; ALfloat timediff; /* Start a batch update, to ensure all changes apply simultaneously. */ @@ -649,9 +649,8 @@ int main(int argc, char **argv) /* Get the current time to track the amount of time that passed. * Convert the difference to seconds. */ - altimespec_get(&curtime, AL_TIME_UTC); - timediff = (ALfloat)(curtime.tv_sec - basetime.tv_sec); - timediff += (ALfloat)(curtime.tv_nsec - basetime.tv_nsec) / 1000000000.0f; + curtime = altime_get(); + timediff = (ALfloat)(curtime - basetime) / 1000.0f; /* Avoid negative time deltas, in case of non-monotonic clocks. */ if(timediff < 0.0f) @@ -669,7 +668,7 @@ int main(int argc, char **argv) * time to start a new cycle. */ timediff -= 8.0f; - basetime.tv_sec += 8; + basetime += 8000; } } diff --git a/examples/common/alhelpers.c b/examples/common/alhelpers.c index 6a583497..fec51e6b 100644 --- a/examples/common/alhelpers.c +++ b/examples/common/alhelpers.c @@ -28,6 +28,7 @@ * finding an appropriate buffer format, and getting readable strings for * channel configs and sample types. */ +#include #include #include #include @@ -123,22 +124,21 @@ const char *FormatName(ALenum format) #include #include -int altimespec_get(struct timespec *ts, int base) +unsigned int altime_get(void) { - if(base == AL_TIME_UTC) - { - union { - FILETIME ftime; - ULARGE_INTEGER ulint; - } systime; - GetSystemTimeAsFileTime(&systime.ftime); - /* FILETIME is in 100-nanosecond units, or 1/10th of a microsecond. */ - ts->tv_sec = systime.ulint.QuadPart/10000000; - ts->tv_nsec = (systime.ulint.QuadPart%10000000) * 100; - return base; - } - - return 0; + static unsigned int start_time = 0; + unsigned int cur_time; + union { + FILETIME ftime; + ULARGE_INTEGER ulint; + } systime; + GetSystemTimeAsFileTime(&systime.ftime); + /* FILETIME is in 100-nanosecond units, or 1/10th of a microsecond. */ + cur_time = (unsigned int)(systime.ulint.QuadPart/10000); + + if(!start_time) + start_time = cur_time; + return cur_time - start_time; } void al_nssleep(unsigned long nsec) @@ -151,27 +151,26 @@ void al_nssleep(unsigned long nsec) #include #include -int altimespec_get(struct timespec *ts, int base) +unsigned int altime_get(void) { - if(base == AL_TIME_UTC) - { - int ret; + static unsigned int start_time = 0u; + unsigned int cur_time; + #if _POSIX_TIMERS > 0 - ret = clock_gettime(CLOCK_REALTIME, ts); - if(ret == 0) return base; + struct timespec ts; + int ret = clock_gettime(CLOCK_REALTIME, ts); + if(ret != 0) return 0; + cur_time = ts.ts_sec*1000 + ts.ts_nsec/1000000; #else /* _POSIX_TIMERS > 0 */ - struct timeval tv; - ret = gettimeofday(&tv, NULL); - if(ret == 0) - { - ts->tv_sec = tv.tv_sec; - ts->tv_nsec = tv.tv_usec * 1000; - return base; - } + struct timeval tv; + int ret = gettimeofday(&tv, NULL); + if(ret != 0) return 0; + cur_time = tv.tv_sec*1000 + tv.tv_usec/1000; #endif - } - return 0; + if(!start_time) + start_time = cur_time; + return cur_time - start_time; } void al_nssleep(unsigned long nsec) diff --git a/examples/common/alhelpers.h b/examples/common/alhelpers.h index 14edf5d9..4193e86f 100644 --- a/examples/common/alhelpers.h +++ b/examples/common/alhelpers.h @@ -1,8 +1,6 @@ #ifndef ALHELPERS_H #define ALHELPERS_H -#include - #include "AL/alc.h" #include "AL/al.h" #include "AL/alext.h" @@ -19,14 +17,7 @@ int InitAL(char ***argv, int *argc); void CloseAL(void); /* Cross-platform timeget and sleep functions. */ -#ifndef HAVE_STRUCT_TIMESPEC -struct timespec { - time_t tv_sec; - long tv_nsec; -}; -#endif -#define AL_TIME_UTC 1 -int altimespec_get(struct timespec *ts, int base); +unsigned int altime_get(void); void al_nssleep(unsigned long nsec); #ifdef __cplusplus -- cgit v1.2.3 From 9b2b83f99c1349d68f15e36efe36566e9cbe582a Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 27 Nov 2018 00:02:31 -0800 Subject: Fix use of clock_gettime --- examples/common/alhelpers.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/common/alhelpers.c b/examples/common/alhelpers.c index fec51e6b..5d2c6536 100644 --- a/examples/common/alhelpers.c +++ b/examples/common/alhelpers.c @@ -158,9 +158,9 @@ unsigned int altime_get(void) #if _POSIX_TIMERS > 0 struct timespec ts; - int ret = clock_gettime(CLOCK_REALTIME, ts); + int ret = clock_gettime(CLOCK_REALTIME, &ts); if(ret != 0) return 0; - cur_time = ts.ts_sec*1000 + ts.ts_nsec/1000000; + cur_time = ts.tv_sec*1000 + ts.tv_nsec/1000000; #else /* _POSIX_TIMERS > 0 */ struct timeval tv; int ret = gettimeofday(&tv, NULL); -- cgit v1.2.3 From ff6dda06ad66d71d4178bfa2aee282abe6c3ec23 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 27 Nov 2018 10:35:00 -0800 Subject: Add the appropriate include for the _POSIX_TIMERS macro --- examples/common/alhelpers.c | 1 + 1 file changed, 1 insertion(+) (limited to 'examples') diff --git a/examples/common/alhelpers.c b/examples/common/alhelpers.c index 5d2c6536..c8f0bb37 100644 --- a/examples/common/alhelpers.c +++ b/examples/common/alhelpers.c @@ -149,6 +149,7 @@ void al_nssleep(unsigned long nsec) #else #include +#include #include unsigned int altime_get(void) -- cgit v1.2.3 From 3f745be1dc4df7ffeec89f1d90af41e139fb49db Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 27 Nov 2018 10:41:07 -0800 Subject: Return a signed integer from altime_get --- examples/almultireverb.c | 4 ++-- examples/common/alhelpers.c | 14 +++++++------- examples/common/alhelpers.h | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) (limited to 'examples') diff --git a/examples/almultireverb.c b/examples/almultireverb.c index e512d399..f1b1872f 100644 --- a/examples/almultireverb.c +++ b/examples/almultireverb.c @@ -452,7 +452,6 @@ int main(int argc, char **argv) EFX_REVERB_PRESET_CARPETEDHALLWAY, EFX_REVERB_PRESET_BATHROOM }; - unsigned int basetime; ALCdevice *device = NULL; ALCcontext *context = NULL; ALuint effects[2] = { 0, 0 }; @@ -463,6 +462,7 @@ int main(int argc, char **argv) ALCint num_sends = 0; ALenum state = AL_INITIAL; ALfloat direct_gain = 1.0f; + int basetime = 0; int loops = 0; /* Print out usage if no arguments were specified */ @@ -640,7 +640,7 @@ int main(int argc, char **argv) /* Play the sound for a while. */ alSourcePlay(source); do { - unsigned int curtime; + int curtime; ALfloat timediff; /* Start a batch update, to ensure all changes apply simultaneously. */ diff --git a/examples/common/alhelpers.c b/examples/common/alhelpers.c index c8f0bb37..3077d0b7 100644 --- a/examples/common/alhelpers.c +++ b/examples/common/alhelpers.c @@ -124,17 +124,17 @@ const char *FormatName(ALenum format) #include #include -unsigned int altime_get(void) +int altime_get(void) { - static unsigned int start_time = 0; - unsigned int cur_time; + static int start_time = 0; + int cur_time; union { FILETIME ftime; ULARGE_INTEGER ulint; } systime; GetSystemTimeAsFileTime(&systime.ftime); /* FILETIME is in 100-nanosecond units, or 1/10th of a microsecond. */ - cur_time = (unsigned int)(systime.ulint.QuadPart/10000); + cur_time = (int)(systime.ulint.QuadPart/10000); if(!start_time) start_time = cur_time; @@ -152,10 +152,10 @@ void al_nssleep(unsigned long nsec) #include #include -unsigned int altime_get(void) +int altime_get(void) { - static unsigned int start_time = 0u; - unsigned int cur_time; + static int start_time = 0u; + int cur_time; #if _POSIX_TIMERS > 0 struct timespec ts; diff --git a/examples/common/alhelpers.h b/examples/common/alhelpers.h index 4193e86f..5caeda38 100644 --- a/examples/common/alhelpers.h +++ b/examples/common/alhelpers.h @@ -17,7 +17,7 @@ int InitAL(char ***argv, int *argc); void CloseAL(void); /* Cross-platform timeget and sleep functions. */ -unsigned int altime_get(void); +int altime_get(void); void al_nssleep(unsigned long nsec); #ifdef __cplusplus -- cgit v1.2.3 From 0537414bafe80e5e32486672ddce82581fb5e1c3 Mon Sep 17 00:00:00 2001 From: Filip Gawin Date: Mon, 7 Jan 2019 12:37:13 +0100 Subject: Use nullptr in cpp files --- Alc/alu.cpp | 4 ++-- Alc/mixvoice.cpp | 4 ++-- OpenAL32/alEffect.cpp | 4 ++-- OpenAL32/alExtension.cpp | 2 +- OpenAL32/alFilter.cpp | 4 ++-- common/almalloc.cpp | 6 +++--- examples/alffplay.cpp | 2 +- utils/alsoft-config/mainwindow.cpp | 18 +++++++++--------- utils/makehrtf.cpp | 32 ++++++++++++++++---------------- 9 files changed, 38 insertions(+), 38 deletions(-) (limited to 'examples') diff --git a/Alc/alu.cpp b/Alc/alu.cpp index 7d2709ea..77505a0c 100644 --- a/Alc/alu.cpp +++ b/Alc/alu.cpp @@ -1012,8 +1012,8 @@ void CalcNonAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, cons SendSlots[i] = ALContext->DefaultSlot.get(); if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL) { - SendSlots[i] = NULL; - voice->Send[i].Buffer = NULL; + SendSlots[i] = nullptr; + voice->Send[i].Buffer = nullptr; voice->Send[i].Channels = 0; } else diff --git a/Alc/mixvoice.cpp b/Alc/mixvoice.cpp index 53721201..eb219bad 100644 --- a/Alc/mixvoice.cpp +++ b/Alc/mixvoice.cpp @@ -156,7 +156,7 @@ void aluInitMixer(void) { const char *str; - if(ConfigValueStr(NULL, NULL, "resampler", &str)) + if(ConfigValueStr(nullptr, nullptr, "resampler", &str)) { if(strcasecmp(str, "point") == 0 || strcasecmp(str, "none") == 0) ResamplerDefault = PointResampler; @@ -698,7 +698,7 @@ ALboolean MixSource(ALvoice *voice, const ALuint SourceID, ALCcontext *Context, if(DataPosInt >= BufferListItem->max_samples) { isplaying = false; - BufferListItem = NULL; + BufferListItem = nullptr; DataPosInt = 0; DataPosFrac = 0; break; diff --git a/OpenAL32/alEffect.cpp b/OpenAL32/alEffect.cpp index 6a91c852..884b0acd 100644 --- a/OpenAL32/alEffect.cpp +++ b/OpenAL32/alEffect.cpp @@ -232,7 +232,7 @@ ALeffect *AllocEffect(ALCcontext *context) if(UNLIKELY(device->EffectList.size() >= 1<<25)) { alSetError(context, AL_OUT_OF_MEMORY, "Too many effects allocated"); - return NULL; + return nullptr; } device->EffectList.emplace_back(); sublist = device->EffectList.end() - 1; @@ -242,7 +242,7 @@ ALeffect *AllocEffect(ALCcontext *context) { device->EffectList.pop_back(); alSetError(context, AL_OUT_OF_MEMORY, "Failed to allocate effect batch"); - return NULL; + return nullptr; } slidx = 0; diff --git a/OpenAL32/alExtension.cpp b/OpenAL32/alExtension.cpp index fff12e01..aef6f7a4 100644 --- a/OpenAL32/alExtension.cpp +++ b/OpenAL32/alExtension.cpp @@ -47,7 +47,7 @@ AL_API ALboolean AL_APIENTRY alIsExtensionPresent(const ALchar *extName) (ptr[len] == '\0' || isspace(ptr[len]))) return AL_TRUE; - if((ptr=strchr(ptr, ' ')) != NULL) + if((ptr=strchr(ptr, ' ')) != nullptr) { do { ++ptr; diff --git a/OpenAL32/alFilter.cpp b/OpenAL32/alFilter.cpp index c4416a38..69a148b6 100644 --- a/OpenAL32/alFilter.cpp +++ b/OpenAL32/alFilter.cpp @@ -292,7 +292,7 @@ ALfilter *AllocFilter(ALCcontext *context) if(UNLIKELY(device->FilterList.size() >= 1<<25)) { alSetError(context, AL_OUT_OF_MEMORY, "Too many filters allocated"); - return NULL; + return nullptr; } device->FilterList.emplace_back(); sublist = device->FilterList.end() - 1; @@ -302,7 +302,7 @@ ALfilter *AllocFilter(ALCcontext *context) { device->FilterList.pop_back(); alSetError(context, AL_OUT_OF_MEMORY, "Failed to allocate filter batch"); - return NULL; + return nullptr; } slidx = 0; diff --git a/common/almalloc.cpp b/common/almalloc.cpp index 7e83672b..da0a1d37 100644 --- a/common/almalloc.cpp +++ b/common/almalloc.cpp @@ -33,12 +33,12 @@ void *al_malloc(size_t alignment, size_t size) void *ret; if(posix_memalign(&ret, alignment, size) == 0) return ret; - return NULL; + return nullptr; #elif defined(HAVE__ALIGNED_MALLOC) return _aligned_malloc(size, alignment); #else char *ret = static_cast(malloc(size+alignment)); - if(ret != NULL) + if(ret != nullptr) { *(ret++) = 0x00; while(((ptrdiff_t)ret&(alignment-1)) != 0) @@ -62,7 +62,7 @@ void al_free(void *ptr) noexcept #elif defined(HAVE__ALIGNED_MALLOC) _aligned_free(ptr); #else - if(ptr != NULL) + if(ptr != nullptr) { char *finder = static_cast(ptr); do { diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 771e5ded..f9ced483 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -879,7 +879,7 @@ int AudioState::handler() ALsizei buffer_len = std::chrono::duration_cast>( mCodecCtx->sample_rate * AudioBufferTime).count() * mFrameSize; - mSamples = NULL; + mSamples = nullptr; mSamplesMax = 0; mSamplesPos = 0; mSamplesLen = 0; diff --git a/utils/alsoft-config/mainwindow.cpp b/utils/alsoft-config/mainwindow.cpp index 449c91e5..ce319637 100644 --- a/utils/alsoft-config/mainwindow.cpp +++ b/utils/alsoft-config/mainwindow.cpp @@ -215,13 +215,13 @@ static QString getNameFromValue(const NameValuePair (&list)[N], const QString &s MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), - mPeriodSizeValidator(NULL), - mPeriodCountValidator(NULL), - mSourceCountValidator(NULL), - mEffectSlotValidator(NULL), - mSourceSendValidator(NULL), - mSampleRateValidator(NULL), - mJackBufferValidator(NULL), + mPeriodSizeValidator(nullptr), + mPeriodCountValidator(nullptr), + mSourceCountValidator(nullptr), + mEffectSlotValidator(nullptr), + mSourceSendValidator(nullptr), + mSampleRateValidator(nullptr), + mJackBufferValidator(nullptr), mNeedsSave(false) { ui->setupUi(this); @@ -1290,7 +1290,7 @@ void MainWindow::showEnabledBackendMenu(QPoint pt) delete item; enableApplyButton(); } - else if(gotAction != NULL) + else if(gotAction != nullptr) { QMap::const_iterator iter = actionMap.find(gotAction); if(iter != actionMap.end()) @@ -1328,7 +1328,7 @@ void MainWindow::showDisabledBackendMenu(QPoint pt) delete item; enableApplyButton(); } - else if(gotAction != NULL) + else if(gotAction != nullptr) { QMap::const_iterator iter = actionMap.find(gotAction); if(iter != actionMap.end()) diff --git a/utils/makehrtf.cpp b/utils/makehrtf.cpp index 1e58ce28..30440838 100644 --- a/utils/makehrtf.cpp +++ b/utils/makehrtf.cpp @@ -344,7 +344,7 @@ struct ResamplerT { // output is desired. static void TrSetup(FILE *fp, const char *filename, TokenReaderT *tr) { - const char *name = NULL; + const char *name = nullptr; if(filename) { @@ -599,7 +599,7 @@ static int TrReadInt(TokenReaderT *tr, const int loBound, const int hiBound, int return 0; } temp[len] = '\0'; - *value = strtol(temp, NULL, 10); + *value = strtol(temp, nullptr, 10); if(*value < loBound || *value > hiBound) { TrErrorAt(tr, tr->mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound); @@ -695,7 +695,7 @@ static int TrReadFloat(TokenReaderT *tr, const double loBound, const double hiBo return 0; } temp[len] = '\0'; - *value = strtod(temp, NULL); + *value = strtod(temp, nullptr); if(*value < loBound || *value > hiBound) { TrErrorAt(tr, tr->mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound); @@ -1696,7 +1696,7 @@ static int LoadAsciiSource(FILE *fp, const SourceRefT *src, const uint n, double uint i, j; double dummy; - TrSetup(fp, NULL, &tr); + TrSetup(fp, nullptr, &tr); for(i = 0;i < src->mOffset;i++) { if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy)) @@ -1725,7 +1725,7 @@ static int LoadSource(SourceRefT *src, const uint hrirRate, const uint n, double fp = fopen(src->mPath, "r"); else fp = fopen(src->mPath, "rb"); - if(fp == NULL) + if(fp == nullptr) { fprintf(stderr, "Error: Could not open source file '%s'.\n", src->mPath); return 0; @@ -1799,7 +1799,7 @@ static int StoreMhr(const HrirDataT *hData, const char *filename) uint fi, ei, ai, i; uint dither_seed = 22222; - if((fp=fopen(filename, "wb")) == NULL) + if((fp=fopen(filename, "wb")) == nullptr) { fprintf(stderr, "Error: Could not open MHR file '%s'.\n", filename); return 0; @@ -2878,7 +2878,7 @@ static int ProcessSources(const HeadModelT model, TokenReaderT *tr, HrirDataT *h return 0; HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai]; - if(azd->mIrs[0] != NULL) + if(azd->mIrs[0] != nullptr) { TrErrorAt(tr, line, col, "Redefinition of source.\n"); return 0; @@ -2928,12 +2928,12 @@ static int ProcessSources(const HeadModelT model, TokenReaderT *tr, HrirDataT *h } if(hData->mChannelType == CT_STEREO) { - if(azd->mIrs[0] == NULL) + if(azd->mIrs[0] == nullptr) { TrErrorAt(tr, line, col, "Missing left ear source reference(s).\n"); return 0; } - else if(azd->mIrs[1] == NULL) + else if(azd->mIrs[1] == nullptr) { TrErrorAt(tr, line, col, "Missing right ear source reference(s).\n"); return 0; @@ -2948,7 +2948,7 @@ static int ProcessSources(const HeadModelT model, TokenReaderT *tr, HrirDataT *h for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++) { HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai]; - if(azd->mIrs[0] != NULL) + if(azd->mIrs[0] != nullptr) break; } if(ai < hData->mFds[fi].mEvs[ei].mAzCount) @@ -2966,7 +2966,7 @@ static int ProcessSources(const HeadModelT model, TokenReaderT *tr, HrirDataT *h { HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai]; - if(azd->mIrs[0] == NULL) + if(azd->mIrs[0] == nullptr) { TrError(tr, "Missing source reference [ %d, %d, %d ].\n", fi, ei, ai); return 0; @@ -3009,10 +3009,10 @@ static int ProcessDefinition(const char *inName, const uint outRate, const uint int ret; fprintf(stdout, "Reading HRIR definition from %s...\n", inName?inName:"stdin"); - if(inName != NULL) + if(inName != nullptr) { fp = fopen(inName, "r"); - if(fp == NULL) + if(fp == nullptr) { fprintf(stderr, "Error: Could not open definition file '%s'\n", inName); return 0; @@ -3026,7 +3026,7 @@ static int ProcessDefinition(const char *inName, const uint outRate, const uint } if(!ProcessMetrics(&tr, fftSize, truncSize, &hData)) { - if(inName != NULL) + if(inName != nullptr) fclose(fp); return 0; } @@ -3099,10 +3099,10 @@ static void PrintHelp(const char *argv0, FILE *ofile) // Standard command line dispatch. int main(int argc, char *argv[]) { - const char *inName = NULL, *outName = NULL; + const char *inName = nullptr, *outName = nullptr; uint outRate, fftSize; int equalize, surface; - char *end = NULL; + char *end = nullptr; HeadModelT model; uint truncSize; double radius; -- cgit v1.2.3 From 0d3a0635d946ab1f43fd98cec4882248bc990846 Mon Sep 17 00:00:00 2001 From: Filip Gawin Date: Tue, 8 Jan 2019 19:42:44 +0100 Subject: Avoid using old style casts To think about: examples/alffplay.cpp:600 OpenAL32/Include/alMain.h:295 --- Alc/alc.cpp | 22 ++--- Alc/alconfig.cpp | 4 +- Alc/alu.cpp | 18 ++-- Alc/backends/alsa.cpp | 16 ++-- Alc/backends/portaudio.cpp | 2 +- Alc/backends/pulseaudio.cpp | 6 +- Alc/bformatdec.cpp | 2 +- Alc/converter.cpp | 8 +- Alc/effects/chorus.cpp | 6 +- Alc/effects/compressor.cpp | 4 +- Alc/effects/equalizer.cpp | 2 +- Alc/effects/fshifter.cpp | 4 +- Alc/effects/modulator.cpp | 16 ++-- Alc/effects/pshifter.cpp | 12 +-- Alc/effects/reverb.cpp | 6 +- Alc/helpers.cpp | 2 +- Alc/hrtf.cpp | 10 +-- Alc/mastering.cpp | 6 +- Alc/mixer/mixer_c.cpp | 4 +- Alc/mixer/mixer_sse.cpp | 18 ++-- Alc/mixvoice.cpp | 12 +-- Alc/panning.cpp | 8 +- OpenAL32/alBuffer.cpp | 27 +++--- OpenAL32/alError.cpp | 6 +- OpenAL32/alExtension.cpp | 2 +- OpenAL32/alListener.cpp | 40 ++++----- OpenAL32/alSource.cpp | 173 +++++++++++++++++++------------------ OpenAL32/alState.cpp | 40 ++++----- common/alcomplex.cpp | 2 +- examples/alffplay.cpp | 28 +++--- utils/alsoft-config/mainwindow.cpp | 2 +- utils/makehrtf.cpp | 124 +++++++++++++------------- 32 files changed, 319 insertions(+), 313 deletions(-) (limited to 'examples') diff --git a/Alc/alc.cpp b/Alc/alc.cpp index e44b42c8..9b56ea8d 100644 --- a/Alc/alc.cpp +++ b/Alc/alc.cpp @@ -985,7 +985,7 @@ static void alc_initconfig(void) if(!str[0] || str[0] == ',') continue; - size_t len{next ? (size_t)(next-str) : strlen(str)}; + size_t len{next ? static_cast(next-str) : strlen(str)}; while(len > 0 && isspace(str[len-1])) len--; if(len == 3 && strncasecmp(str, "sse", len) == 0) @@ -1062,7 +1062,7 @@ static void alc_initconfig(void) } endlist = 1; - len = (next ? ((size_t)(next-devs)) : strlen(devs)); + len = (next ? (static_cast(next-devs)) : strlen(devs)); while(len > 0 && isspace(devs[len-1])) len--; #ifdef HAVE_WASAPI @@ -1147,7 +1147,7 @@ static void alc_initconfig(void) if(!str[0] || next == str) continue; - size_t len{next ? (size_t)(next-str) : strlen(str)}; + size_t len{next ? static_cast(next-str) : strlen(str)}; for(size_t n{0u};n < countof(gEffectList);n++) { if(len == strlen(gEffectList[n].name) && @@ -1858,7 +1858,7 @@ static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList) device->HrtfList = EnumerateHrtf(device->DeviceName.c_str()); if(!device->HrtfList.empty()) { - if(hrtf_id >= 0 && (size_t)hrtf_id < device->HrtfList.size()) + if(hrtf_id >= 0 && static_cast(hrtf_id) < device->HrtfList.size()) hrtf = GetLoadedHrtf(device->HrtfList[hrtf_id].hrtf); else hrtf = GetLoadedHrtf(device->HrtfList.front().hrtf); @@ -1989,7 +1989,7 @@ static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList) if(depth > 0) { depth = clampi(depth, 2, 24); - device->DitherDepth = std::pow(2.0f, (ALfloat)(depth-1)); + device->DitherDepth = std::pow(2.0f, static_cast(depth-1)); } } if(!(device->DitherDepth > 0.0f)) @@ -2608,7 +2608,7 @@ void AllocateVoices(ALCcontext *context, ALsizei num_voices, ALsizei old_sends) const size_t size{sizeof(ALvoice*) + sizeof_voice}; auto voices = static_cast(al_calloc(16, RoundUp(size*num_voices, 16))); - auto voice = reinterpret_cast((char*)voices + RoundUp(num_voices*sizeof(ALvoice*), 16)); + auto voice = reinterpret_cast(reinterpret_cast(voices) + RoundUp(num_voices*sizeof(ALvoice*), 16)); auto viter = voices; if(context->Voices) @@ -2670,7 +2670,7 @@ void AllocateVoices(ALCcontext *context, ALsizei num_voices, ALsizei old_sends) /* Set this voice's reference. */ ALvoice *ret = voice; /* Increment pointer to the next storage space. */ - voice = reinterpret_cast((char*)voice + sizeof_voice); + voice = reinterpret_cast(reinterpret_cast(voice) + sizeof_voice); return ret; }; viter = std::transform(context->Voices, context->Voices+v_count, viter, copy_voice); @@ -2683,7 +2683,7 @@ void AllocateVoices(ALCcontext *context, ALsizei num_voices, ALsizei old_sends) auto init_voice = [&voice,sizeof_voice]() -> ALvoice* { ALvoice *ret = new (voice) ALvoice{}; - voice = reinterpret_cast((char*)voice + sizeof_voice); + voice = reinterpret_cast(reinterpret_cast(voice) + sizeof_voice); return ret; }; std::generate(viter, voices+num_voices, init_voice); @@ -3156,7 +3156,7 @@ static ALCsizei GetIntegerv(ALCdevice *device, ALCenum param, ALCsizei size, ALC { std::lock_guard _{device->StateLock}; device->HrtfList.clear(); device->HrtfList = EnumerateHrtf(device->DeviceName.c_str()); - values[0] = (ALCint)device->HrtfList.size(); + values[0] = static_cast(device->HrtfList.size()); } return 1; @@ -4022,7 +4022,7 @@ ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCenum err{ALC_INVALID_VALUE}; { std::lock_guard _{dev->StateLock}; BackendBase *backend{dev->Backend.get()}; - if(samples >= 0 && backend->availableSamples() >= (ALCuint)samples) + if(samples >= 0 && backend->availableSamples() >= static_cast(samples)) err = backend->captureSamples(buffer, samples); } if(err != ALC_NO_ERROR) @@ -4210,7 +4210,7 @@ ALC_API const ALCchar* ALC_APIENTRY alcGetStringiSOFT(ALCdevice *device, ALCenum else switch(paramName) { case ALC_HRTF_SPECIFIER_SOFT: - if(index >= 0 && (size_t)index < dev->HrtfList.size()) + if(index >= 0 && static_cast(index) < dev->HrtfList.size()) return dev->HrtfList[index].name.c_str(); alcSetError(dev.get(), ALC_INVALID_VALUE); break; diff --git a/Alc/alconfig.cpp b/Alc/alconfig.cpp index eecaf6fc..c4fde638 100644 --- a/Alc/alconfig.cpp +++ b/Alc/alconfig.cpp @@ -93,7 +93,7 @@ std:: string expdup(const char *str) { const char *next = std::strchr(str, '$'); addstr = str; - addstrlen = next ? (size_t)(next-str) : std::strlen(str); + addstrlen = next ? static_cast(next-str) : std::strlen(str); str += addstrlen; } @@ -104,7 +104,7 @@ std:: string expdup(const char *str) { const char *next = std::strchr(str+1, '$'); addstr = str; - addstrlen = next ? (size_t)(next-str) : std::strlen(str); + addstrlen = next ? static_cast(next-str) : std::strlen(str); str += addstrlen; } diff --git a/Alc/alu.cpp b/Alc/alu.cpp index 77505a0c..42e31b88 100644 --- a/Alc/alu.cpp +++ b/Alc/alu.cpp @@ -227,7 +227,7 @@ void BsincPrepare(const ALuint increment, BsincState *state, const BSincTable *t if(increment > FRACTIONONE) { - sf = (ALfloat)FRACTIONONE / increment; + sf = static_castFRACTIONONE / increment; sf = maxf(0.0f, (BSINC_SCALE_COUNT-1) * (sf-table->scaleBase) * table->scaleRange); si = float2int(sf); /* The interpolation factor is fit to this diagonally-symmetric curve @@ -620,7 +620,7 @@ void CalcPanningAndFilters(ALvoice *voice, const ALfloat Azi, const ALfloat Elev const ALfloat mdist{maxf(Distance*Listener.Params.MetersPerUnit, Device->AvgSpeakerDist/4.0f)}; const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / - (mdist * (ALfloat)Device->Frequency)}; + (mdist * static_cast(Device->Frequency))}; /* Only need to adjust the first channel of a B-Format source. */ voice->Direct.Params[0].NFCtrlFilter.adjust(w0); @@ -849,7 +849,7 @@ void CalcPanningAndFilters(ALvoice *voice, const ALfloat Azi, const ALfloat Elev const ALfloat mdist{maxf(Distance*Listener.Params.MetersPerUnit, Device->AvgSpeakerDist/4.0f)}; const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / - (mdist * (ALfloat)Device->Frequency)}; + (mdist * static_cast(Device->Frequency))}; /* Adjust NFC filters. */ for(ALsizei c{0};c < num_channels;c++) @@ -908,7 +908,7 @@ void CalcPanningAndFilters(ALvoice *voice, const ALfloat Azi, const ALfloat Elev * source moves away from the listener. */ const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / - (Device->AvgSpeakerDist * (ALfloat)Device->Frequency)}; + (Device->AvgSpeakerDist * static_cast(Device->Frequency))}; for(ALsizei c{0};c < num_channels;c++) voice->Direct.Params[c].NFCtrlFilter.adjust(w0); @@ -1026,7 +1026,7 @@ void CalcNonAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, cons /* Calculate the stepping value */ const auto Pitch = static_cast(ALBuffer->Frequency) / static_cast(Device->Frequency) * props->Pitch; - if(Pitch > (ALfloat)MAX_PITCH) + if(Pitch > static_cast(MAX_PITCH)) voice->Step = MAX_PITCH<Step = maxi(fastf2i(Pitch * FRACTIONONE), 1); @@ -1363,8 +1363,8 @@ void CalcAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, const A /* Adjust pitch based on the buffer and output frequencies, and calculate * fixed-point stepping value. */ - Pitch *= (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency; - if(Pitch > (ALfloat)MAX_PITCH) + Pitch *= static_cast(ALBuffer->Frequency)/static_cast(Device->Frequency); + if(Pitch > static_cast(MAX_PITCH)) voice->Step = MAX_PITCH<Step = maxi(fastf2i(Pitch * FRACTIONONE), 1); @@ -1648,7 +1648,7 @@ void ApplyDither(ALfloat (*Samples)[BUFFERSIZE], ALuint *dither_seed, const ALfl ALfloat val = sample * quant_scale; ALuint rng0 = dither_rng(&seed); ALuint rng1 = dither_rng(&seed); - val += (ALfloat)(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX)); + val += static_cast(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX)); return fast_roundf(val) * invscale; } ); @@ -1828,7 +1828,7 @@ void aluHandleDisconnect(ALCdevice *device, const char *msg, ...) int msglen{vsnprintf(evt.u.user.msg, sizeof(evt.u.user.msg), msg, args)}; va_end(args); - if(msglen < 0 || (size_t)msglen >= sizeof(evt.u.user.msg)) + if(msglen < 0 || static_cast(msglen) >= sizeof(evt.u.user.msg)) evt.u.user.msg[sizeof(evt.u.user.msg)-1] = 0; ALCcontext *ctx{device->ContextList.load()}; diff --git a/Alc/backends/alsa.cpp b/Alc/backends/alsa.cpp index 33b3ae49..5fe8ef96 100644 --- a/Alc/backends/alsa.cpp +++ b/Alc/backends/alsa.cpp @@ -480,7 +480,7 @@ int AlsaPlayback::mixerProc() continue; } - if((snd_pcm_uframes_t)avail > update_size*(num_updates+1)) + if(static_cast(avail) > update_size*(num_updates+1)) { WARN("available samples exceeds the buffer size\n"); snd_pcm_reset(mPcmHandle); @@ -488,7 +488,7 @@ int AlsaPlayback::mixerProc() } // make sure there's frames to process - if((snd_pcm_uframes_t)avail < update_size) + if(static_cast(avail) < update_size) { if(state != SND_PCM_STATE_RUNNING) { @@ -520,7 +520,7 @@ int AlsaPlayback::mixerProc() break; } - char *WritePtr{(char*)areas->addr + (offset * areas->step / 8)}; + char *WritePtr{static_cast(areas->addr) + (offset * areas->step / 8)}; aluMixData(mDevice, WritePtr, frames); snd_pcm_sframes_t commitres{snd_pcm_mmap_commit(mPcmHandle, offset, frames)}; @@ -563,14 +563,14 @@ int AlsaPlayback::mixerNoMMapProc() continue; } - if((snd_pcm_uframes_t)avail > update_size*num_updates) + if(static_cast(avail) > update_size*num_updates) { WARN("available samples exceeds the buffer size\n"); snd_pcm_reset(mPcmHandle); continue; } - if((snd_pcm_uframes_t)avail < update_size) + if(static_cast(avail) < update_size) { if(state != SND_PCM_STATE_RUNNING) { @@ -1112,7 +1112,7 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) { /* First get any data stored from the last stop */ amt = snd_pcm_bytes_to_frames(mPcmHandle, mBuffer.size()); - if((snd_pcm_uframes_t)amt > samples) amt = samples; + if(static_cast(amt) > samples) amt = samples; amt = snd_pcm_frames_to_bytes(mPcmHandle, amt); memcpy(buffer, mBuffer.data(), amt); @@ -1142,12 +1142,12 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) } /* If the amount available is less than what's asked, we lost it * during recovery. So just give silence instead. */ - if((snd_pcm_uframes_t)amt < samples) + if(static_cast(amt) < samples) break; continue; } - buffer = (ALbyte*)buffer + amt; + buffer = static_cast(buffer) + amt; samples -= amt; } if(samples > 0) diff --git a/Alc/backends/portaudio.cpp b/Alc/backends/portaudio.cpp index 258f981e..074508b2 100644 --- a/Alc/backends/portaudio.cpp +++ b/Alc/backends/portaudio.cpp @@ -194,7 +194,7 @@ ALCenum PortPlayback::open(const ALCchar *name) if(!ConfigValueInt(nullptr, "port", "device", &mParams.device) || mParams.device < 0) mParams.device = Pa_GetDefaultOutputDevice(); mParams.suggestedLatency = (mDevice->UpdateSize*mDevice->NumUpdates) / - (float)mDevice->Frequency; + static_cast(mDevice->Frequency); mParams.hostApiSpecificStreamInfo = nullptr; mParams.channelCount = ((mDevice->FmtChans == DevFmtMono) ? 1 : 2); diff --git a/Alc/backends/pulseaudio.cpp b/Alc/backends/pulseaudio.cpp index 34c5fbfe..b717d67a 100644 --- a/Alc/backends/pulseaudio.cpp +++ b/Alc/backends/pulseaudio.cpp @@ -1131,7 +1131,7 @@ ALCboolean PulsePlayback::reset() /* Server updated our playback rate, so modify the buffer attribs * accordingly. */ mDevice->NumUpdates = static_cast(clampd( - (ALdouble)mSpec.rate/mDevice->Frequency*mDevice->NumUpdates + 0.5, 2.0, 16.0)); + static_cast(mSpec.rate)/mDevice->Frequency*mDevice->NumUpdates + 0.5, 2.0, 16.0)); period_size = mDevice->UpdateSize * mFrameSize; mAttr.maxlength = -1; @@ -1511,10 +1511,10 @@ ALCenum PulseCapture::captureSamples(ALCvoid *buffer, ALCuint samples) memcpy(buffer, mCapStore, rem); - buffer = (ALbyte*)buffer + rem; + buffer = static_cast(buffer) + rem; todo -= rem; - mCapStore = (ALbyte*)mCapStore + rem; + mCapStore = reinterpret_cast(mCapStore) + rem; mCapRemain -= rem; if(mCapRemain == 0) { diff --git a/Alc/bformatdec.cpp b/Alc/bformatdec.cpp index b5dcfd89..a80ded30 100644 --- a/Alc/bformatdec.cpp +++ b/Alc/bformatdec.cpp @@ -75,7 +75,7 @@ void BFormatDec::reset(const AmbDecConf *conf, bool allow_2band, ALsizei inchans { return mask | (1 << chan); } ); - const ALfloat xover_norm{conf->XOverFreq / (float)srate}; + const ALfloat xover_norm{conf->XOverFreq / static_cast(srate)}; const ALsizei out_order{ (conf->ChanMask > AMBI_3ORDER_MASK) ? 4 : diff --git a/Alc/converter.cpp b/Alc/converter.cpp index 22a01552..49c5cb3b 100644 --- a/Alc/converter.cpp +++ b/Alc/converter.cpp @@ -155,7 +155,7 @@ SampleConverterPtr CreateSampleConverter(DevFmtType srcType, DevFmtType dstType, /* Have to set the mixer FPU mode since that's what the resampler code expects. */ FPUCtl mixer_mode{}; auto step = static_cast( - mind((ALdouble)srcRate/dstRate*FRACTIONONE + 0.5, MAX_PITCH*FRACTIONONE)); + mind(static_cast(srcRate)/dstRate*FRACTIONONE + 0.5, MAX_PITCH*FRACTIONONE)); converter->mIncrement = maxi(step, 1); if(converter->mIncrement == FRACTIONONE) converter->mResample = Resample_copy_C; @@ -203,7 +203,7 @@ ALsizei SampleConverter::availableOut(ALsizei srcframes) const DataSize64 -= mFracOffset; /* If we have a full prep, we can generate at least one sample. */ - return (ALsizei)clampu64((DataSize64 + mIncrement-1)/mIncrement, 1, BUFFERSIZE); + return static_cast(clampu64((DataSize64 + mIncrement-1)/mIncrement, 1, BUFFERSIZE)); } ALsizei SampleConverter::convert(const ALvoid **src, ALsizei *srcframes, ALvoid *dst, ALsizei dstframes) @@ -267,7 +267,7 @@ ALsizei SampleConverter::convert(const ALvoid **src, ALsizei *srcframes, ALvoid for(ALsizei chan{0};chan < mNumChannels;chan++) { const ALbyte *SrcSamples = SamplesIn + mSrcTypeSize*chan; - ALbyte *DstSamples = (ALbyte*)dst + mDstTypeSize*chan; + ALbyte *DstSamples = static_cast(dst) + mDstTypeSize*chan; /* Load the previous samples into the source data first, then the * new samples from the input buffer. @@ -309,7 +309,7 @@ ALsizei SampleConverter::convert(const ALvoid **src, ALsizei *srcframes, ALvoid SamplesIn += SrcFrameSize*(DataPosFrac>>FRACTIONBITS); NumSrcSamples -= mini(NumSrcSamples, (DataPosFrac>>FRACTIONBITS)); - dst = (ALbyte*)dst + DstFrameSize*DstSize; + dst = static_cast(dst) + DstFrameSize*DstSize; pos += DstSize; } diff --git a/Alc/effects/chorus.cpp b/Alc/effects/chorus.cpp index 1132a33a..990b3cc4 100644 --- a/Alc/effects/chorus.cpp +++ b/Alc/effects/chorus.cpp @@ -141,7 +141,7 @@ void ChorusState::update(const ALCcontext *Context, const ALeffectslot *Slot, co const ALCdevice *device{Context->Device}; auto frequency = static_cast(device->Frequency); mDelay = maxi(float2int(props->Chorus.Delay*frequency*FRACTIONONE + 0.5f), mindelay); - mDepth = minf(props->Chorus.Depth * mDelay, (ALfloat)(mDelay - mindelay)); + mDepth = minf(props->Chorus.Depth * mDelay, static_cast(mDelay - mindelay)); mFeedback = props->Chorus.Feedback; @@ -168,9 +168,9 @@ void ChorusState::update(const ALCcontext *Context, const ALeffectslot *Slot, co /* Calculate LFO coefficient (number of samples per cycle). Limit the * max range to avoid overflow when calculating the displacement. */ - ALsizei lfo_range = float2int(minf(frequency/rate + 0.5f, (ALfloat)(INT_MAX/360 - 180))); + ALsizei lfo_range = float2int(minf(frequency/rate + 0.5f, static_cast(INT_MAX/360 - 180))); - mLfoOffset = float2int((ALfloat)mLfoOffset/mLfoRange*lfo_range + 0.5f) % lfo_range; + mLfoOffset = float2int(static_cast(mLfoOffset)/mLfoRange*lfo_range + 0.5f) % lfo_range; mLfoRange = lfo_range; switch(mWaveform) { diff --git a/Alc/effects/compressor.cpp b/Alc/effects/compressor.cpp index ddf104f4..1b840c44 100644 --- a/Alc/effects/compressor.cpp +++ b/Alc/effects/compressor.cpp @@ -60,8 +60,8 @@ ALboolean ALcompressorState::deviceUpdate(const ALCdevice *device) /* Number of samples to do a full attack and release (non-integer sample * counts are okay). */ - const ALfloat attackCount = (ALfloat)device->Frequency * ATTACK_TIME; - const ALfloat releaseCount = (ALfloat)device->Frequency * RELEASE_TIME; + const ALfloat attackCount = static_cast(device->Frequency) * ATTACK_TIME; + const ALfloat releaseCount = static_cast(device->Frequency) * RELEASE_TIME; /* Calculate per-sample multipliers to attack and release at the desired * rates. diff --git a/Alc/effects/equalizer.cpp b/Alc/effects/equalizer.cpp index 94c760ea..defe1485 100644 --- a/Alc/effects/equalizer.cpp +++ b/Alc/effects/equalizer.cpp @@ -113,7 +113,7 @@ ALboolean ALequalizerState::deviceUpdate(const ALCdevice *UNUSED(device)) void ALequalizerState::update(const ALCcontext *context, const ALeffectslot *slot, const ALeffectProps *props, const EffectTarget target) { const ALCdevice *device = context->Device; - ALfloat frequency = (ALfloat)device->Frequency; + ALfloat frequency = static_cast(device->Frequency); ALfloat gain, f0norm; ALuint i; diff --git a/Alc/effects/fshifter.cpp b/Alc/effects/fshifter.cpp index c444872c..994dd90c 100644 --- a/Alc/effects/fshifter.cpp +++ b/Alc/effects/fshifter.cpp @@ -111,7 +111,7 @@ void ALfshifterState::update(const ALCcontext *context, const ALeffectslot *slot { const ALCdevice *device{context->Device}; - ALfloat step{props->Fshifter.Frequency / (ALfloat)device->Frequency}; + ALfloat step{props->Fshifter.Frequency / static_cast(device->Frequency)}; mPhaseStep = fastf2i(minf(step, 0.5f) * FRACTIONONE); switch(props->Fshifter.LeftDirection) @@ -190,7 +190,7 @@ void ALfshifterState::process(ALsizei SamplesToDo, const ALfloat (*RESTRICT Samp for(k = 0;k < SamplesToDo;k++) { double phase = mPhase * ((1.0/FRACTIONONE) * al::MathDefs::Tau()); - BufferOut[k] = (float)(mOutdata[k].real()*std::cos(phase) + + BufferOut[k] = static_cast(mOutdata[k].real()*std::cos(phase) + mOutdata[k].imag()*std::sin(phase)*mLdSign); mPhase += mPhaseStep; diff --git a/Alc/effects/modulator.cpp b/Alc/effects/modulator.cpp index 3544188b..9549740e 100644 --- a/Alc/effects/modulator.cpp +++ b/Alc/effects/modulator.cpp @@ -43,17 +43,17 @@ static inline ALfloat Sin(ALsizei index) { - return std::sin((ALfloat)index * (al::MathDefs::Tau() / (ALfloat)WAVEFORM_FRACONE)); + return std::sin(static_cast(index) * (al::MathDefs::Tau() / static_castWAVEFORM_FRACONE)); } static inline ALfloat Saw(ALsizei index) { - return (ALfloat)index*(2.0f/WAVEFORM_FRACONE) - 1.0f; + return static_cast(index)*(2.0f/WAVEFORM_FRACONE) - 1.0f; } static inline ALfloat Square(ALsizei index) { - return (ALfloat)(((index>>(WAVEFORM_FRACBITS-2))&2) - 1); + return static_cast(((index>>(WAVEFORM_FRACBITS-2))&2) - 1); } static inline ALfloat One(ALsizei UNUSED(index)) @@ -111,7 +111,7 @@ void ALmodulatorState::update(const ALCcontext *context, const ALeffectslot *slo ALfloat f0norm; ALsizei i; - mStep = fastf2i(props->Modulator.Frequency / (ALfloat)device->Frequency * WAVEFORM_FRACONE); + mStep = fastf2i(props->Modulator.Frequency / static_cast(device->Frequency) * WAVEFORM_FRACONE); mStep = clampi(mStep, 0, WAVEFORM_FRACONE-1); if(mStep == 0) @@ -123,7 +123,7 @@ void ALmodulatorState::update(const ALCcontext *context, const ALeffectslot *slo else /*if(Slot->Params.EffectProps.Modulator.Waveform == AL_RING_MODULATOR_SQUARE)*/ mGetSamples = Modulate; - f0norm = props->Modulator.HighPassCutoff / (ALfloat)device->Frequency; + f0norm = props->Modulator.HighPassCutoff / static_cast(device->Frequency); f0norm = clampf(f0norm, 1.0f/512.0f, 0.49f); /* Bandwidth value is constant in octaves. */ mChans[0].Filter.setParams(BiquadType::HighPass, 1.0f, f0norm, @@ -214,7 +214,7 @@ void ALmodulator_setParami(ALeffect *effect, ALCcontext *context, ALenum param, { case AL_RING_MODULATOR_FREQUENCY: case AL_RING_MODULATOR_HIGHPASS_CUTOFF: - ALmodulator_setParamf(effect, context, param, (ALfloat)val); + ALmodulator_setParamf(effect, context, param, static_cast(val)); break; case AL_RING_MODULATOR_WAVEFORM: @@ -236,10 +236,10 @@ void ALmodulator_getParami(const ALeffect *effect, ALCcontext *context, ALenum p switch(param) { case AL_RING_MODULATOR_FREQUENCY: - *val = (ALint)props->Modulator.Frequency; + *val = static_cast(props->Modulator.Frequency); break; case AL_RING_MODULATOR_HIGHPASS_CUTOFF: - *val = (ALint)props->Modulator.HighPassCutoff; + *val = static_cast(props->Modulator.HighPassCutoff); break; case AL_RING_MODULATOR_WAVEFORM: *val = props->Modulator.Waveform; diff --git a/Alc/effects/pshifter.cpp b/Alc/effects/pshifter.cpp index 7c6fb51e..f0b9de1c 100644 --- a/Alc/effects/pshifter.cpp +++ b/Alc/effects/pshifter.cpp @@ -72,7 +72,7 @@ inline int double2int(double d) #else - return (ALint)d; + return static_cast(d); #endif } @@ -156,7 +156,7 @@ ALboolean ALpshifterState::deviceUpdate(const ALCdevice *device) mCount = FIFO_LATENCY; mPitchShiftI = FRACTIONONE; mPitchShift = 1.0f; - mFreqPerBin = device->Frequency / (ALfloat)STFT_SIZE; + mFreqPerBin = device->Frequency / static_cast(STFT_SIZE); std::fill(std::begin(mInFIFO), std::end(mInFIFO), 0.0f); std::fill(std::begin(mOutFIFO), std::end(mOutFIFO), 0.0f); @@ -176,7 +176,7 @@ ALboolean ALpshifterState::deviceUpdate(const ALCdevice *device) void ALpshifterState::update(const ALCcontext* UNUSED(context), const ALeffectslot *slot, const ALeffectProps *props, const EffectTarget target) { const float pitch{std::pow(2.0f, - (ALfloat)(props->Pshifter.CoarseTune*100 + props->Pshifter.FineTune) / 1200.0f + static_cast(props->Pshifter.CoarseTune*100 + props->Pshifter.FineTune) / 1200.0f )}; mPitchShiftI = fastf2i(pitch*FRACTIONONE); mPitchShift = mPitchShiftI * (1.0f/FRACTIONONE); @@ -304,7 +304,7 @@ void ALpshifterState::process(ALsizei SamplesToDo, const ALfloat (*RESTRICT Samp /* Shift accumulator, input & output FIFO */ ALsizei j, k; - for(k = 0;k < STFT_STEP;k++) mOutFIFO[k] = (ALfloat)mOutputAccum[k]; + for(k = 0;k < STFT_STEP;k++) mOutFIFO[k] = static_cast(mOutputAccum[k]); for(j = 0;k < STFT_SIZE;k++,j++) mOutputAccum[j] = mOutputAccum[k]; for(;j < STFT_SIZE;j++) mOutputAccum[j] = 0.0; for(k = 0;k < FIFO_LATENCY;k++) @@ -375,10 +375,10 @@ void ALpshifter_getParami(const ALeffect *effect, ALCcontext *context, ALenum pa switch(param) { case AL_PITCH_SHIFTER_COARSE_TUNE: - *val = (ALint)props->Pshifter.CoarseTune; + *val = props->Pshifter.CoarseTune; break; case AL_PITCH_SHIFTER_FINE_TUNE: - *val = (ALint)props->Pshifter.FineTune; + *val = props->Pshifter.FineTune; break; default: diff --git a/Alc/effects/reverb.cpp b/Alc/effects/reverb.cpp index 6f1b1bb1..a63cc4c3 100644 --- a/Alc/effects/reverb.cpp +++ b/Alc/effects/reverb.cpp @@ -359,7 +359,7 @@ inline ALvoid RealizeLineOffset(ALfloat *sampleBuffer, DelayLineI *Delay) ALfloat *f; ALfloat (*f4)[NUM_LINES]; } u; - u.f = &sampleBuffer[(ptrdiff_t)Delay->Line * NUM_LINES]; + u.f = &sampleBuffer[reinterpret_cast(Delay->Line) * NUM_LINES]; Delay->Line = u.f4; } @@ -377,7 +377,7 @@ ALuint CalcLineLength(const ALfloat length, const ptrdiff_t offset, const ALuint /* All lines share a single sample buffer. */ Delay->Mask = samples - 1; - Delay->Line = (ALfloat(*)[NUM_LINES])offset; + Delay->Line = reinterpret_cast(offset); /* Return the sample count for accumulation. */ return samples; @@ -658,7 +658,7 @@ ALvoid UpdateLateLines(const ALfloat density, const ALfloat diffusion, const ALf /* Scaling factor to convert the normalized reference frequencies from * representing 0...freq to 0...max_reference. */ - const ALfloat norm_weight_factor = (ALfloat)frequency / AL_EAXREVERB_MAX_HFREFERENCE; + const ALfloat norm_weight_factor = static_cast(frequency) / AL_EAXREVERB_MAX_HFREFERENCE; /* To compensate for changes in modal density and decay time of the late * reverb signal, the input is attenuated based on the maximal energy of diff --git a/Alc/helpers.cpp b/Alc/helpers.cpp index 4a80c7e5..88c222bf 100644 --- a/Alc/helpers.cpp +++ b/Alc/helpers.cpp @@ -531,7 +531,7 @@ const PathNamePair &GetProcBinary() len = readlink(selfname, pathname.data(), pathname.size()); } - while(len > 0 && (size_t)len == pathname.size()) + while(len > 0 && static_cast(len) == pathname.size()) { pathname.resize(pathname.size() << 1); len = readlink(selfname, pathname.data(), pathname.size()); diff --git a/Alc/hrtf.cpp b/Alc/hrtf.cpp index 070de55f..4d1c27ee 100644 --- a/Alc/hrtf.cpp +++ b/Alc/hrtf.cpp @@ -329,7 +329,7 @@ void BuildBFormatHrtf(const HrtfEntry *Hrtf, DirectHrtfState *state, const ALsiz { for(ALsizei i{0};i < NumChannels;++i) { - const ALdouble mult{(ALdouble)AmbiOrderHFGain[OrderFromChan[i]] * AmbiMatrix[c][i]}; + const ALdouble mult{static_cast(AmbiOrderHFGain[OrderFromChan[i]]) * AmbiMatrix[c][i]}; const ALsizei numirs{mini(Hrtf->irSize, HRIR_LENGTH-maxi(ldelay, rdelay))}; ALsizei lidx{ldelay}, ridx{rdelay}; for(ALsizei j{0};j < numirs;++j) @@ -384,8 +384,8 @@ void BuildBFormatHrtf(const HrtfEntry *Hrtf, DirectHrtfState *state, const ALsiz { for(ALsizei idx{0};idx < HRIR_LENGTH;idx++) { - state->Chan[i].Coeffs[idx][0] = (ALfloat)tmpres[i][idx][0]; - state->Chan[i].Coeffs[idx][1] = (ALfloat)tmpres[i][idx][1]; + state->Chan[i].Coeffs[idx][0] = static_cast(tmpres[i][idx][0]); + state->Chan[i].Coeffs[idx][1] = static_cast(tmpres[i][idx][1]); } } tmpres.clear(); @@ -435,7 +435,7 @@ HrtfEntry *CreateHrtfStore(ALuint rate, ALsizei irSize, ALfloat distance, ALsize else { uintptr_t offset = sizeof(HrtfEntry); - char *base = (char*)Hrtf; + char *base = reinterpret_cast(Hrtf); ALushort *_evOffset; ALubyte *_azCount; ALubyte (*_delays)[2]; @@ -941,7 +941,7 @@ HrtfEntry *LoadHrtf02(std::istream &data, const char *filename) } return CreateHrtfStore(rate, irSize, - (ALfloat)distance / 1000.0f, evCount, irCount, azCount.data(), evOffset.data(), + static_cast(distance) / 1000.0f, evCount, irCount, azCount.data(), evOffset.data(), &reinterpret_cast(coeffs[0]), &reinterpret_cast(delays[0]), filename ); diff --git a/Alc/mastering.cpp b/Alc/mastering.cpp index dcc5cf40..c71b3cc9 100644 --- a/Alc/mastering.cpp +++ b/Alc/mastering.cpp @@ -398,15 +398,15 @@ std::unique_ptr CompressorInit(const ALsizei NumChans, const ALuint { if(hold > 1) { - Comp->mHold = new ((void*)(Comp.get() + 1)) SlidingHold{}; + Comp->mHold = new (reinterpret_cast(Comp.get() + 1)) SlidingHold{}; Comp->mHold->mValues[0] = -std::numeric_limits::infinity(); Comp->mHold->mExpiries[0] = hold; Comp->mHold->mLength = hold; - Comp->mDelay = (ALfloat(*)[BUFFERSIZE])(Comp->mHold + 1); + Comp->mDelay = reinterpret_cast(Comp->mHold + 1); } else { - Comp->mDelay = (ALfloat(*)[BUFFERSIZE])(Comp.get() + 1); + Comp->mDelay = reinterpret_cast(Comp.get() + 1); } } diff --git a/Alc/mixer/mixer_c.cpp b/Alc/mixer/mixer_c.cpp index 31a5cee4..1b16b733 100644 --- a/Alc/mixer/mixer_c.cpp +++ b/Alc/mixer/mixer_c.cpp @@ -46,7 +46,7 @@ const ALfloat *Resample_copy_C(const InterpState* UNUSED(state), ASSUME(numsamples > 0); #if defined(HAVE_SSE) || defined(HAVE_NEON) /* Avoid copying the source data if it's aligned like the destination. */ - if((((intptr_t)src)&15) == (((intptr_t)dst)&15)) + if((reinterpret_cast(src)&15) == (reinterpret_cast(dst)&15)) return src; #endif std::copy_n(src, numsamples, dst); @@ -137,7 +137,7 @@ void Mix_C(const ALfloat *data, ALsizei OutChans, ALfloat (*RESTRICT OutBuffer)[ ASSUME(OutChans > 0); ASSUME(BufferSize > 0); - const ALfloat delta{(Counter > 0) ? 1.0f/(ALfloat)Counter : 0.0f}; + const ALfloat delta{(Counter > 0) ? 1.0f / static_cast(Counter) : 0.0f}; for(ALsizei c{0};c < OutChans;c++) { ALsizei pos{0}; diff --git a/Alc/mixer/mixer_sse.cpp b/Alc/mixer/mixer_sse.cpp index df5270e7..9eadfd9e 100644 --- a/Alc/mixer/mixer_sse.cpp +++ b/Alc/mixer/mixer_sse.cpp @@ -37,10 +37,10 @@ const ALfloat *Resample_bsinc_SSE(const InterpState *state, const ALfloat *RESTR #undef FRAC_PHASE_BITDIFF ALsizei offset{m*pi*4}; - const __m128 *fil{(const __m128*)(filter + offset)}; offset += m; - const __m128 *scd{(const __m128*)(filter + offset)}; offset += m; - const __m128 *phd{(const __m128*)(filter + offset)}; offset += m; - const __m128 *spd{(const __m128*)(filter + offset)}; + const __m128 *fil{reinterpret_cast(filter + offset)}; offset += m; + const __m128 *scd{reinterpret_cast(filter + offset)}; offset += m; + const __m128 *phd{reinterpret_cast(filter + offset)}; offset += m; + const __m128 *spd{reinterpret_cast(filter + offset)}; // Apply the scale and phase interpolated filter. __m128 r4{_mm_setzero_ps()}; @@ -92,10 +92,10 @@ static inline void ApplyCoeffs(ALsizei Offset, ALfloat (&Values)[HRIR_LENGTH][2] __m128 imp0, imp1; __m128 coeffs{_mm_load_ps(&Coeffs[0][0])}; - __m128 vals{_mm_loadl_pi(_mm_setzero_ps(), (__m64*)&Values[Offset][0])}; + __m128 vals{_mm_loadl_pi(_mm_setzero_ps(), reinterpret_cast<__m64*>(&Values[Offset][0]))}; imp0 = _mm_mul_ps(lrlr, coeffs); vals = _mm_add_ps(imp0, vals); - _mm_storel_pi((__m64*)&Values[Offset][0], vals); + _mm_storel_pi(reinterpret_cast<__m64*>(&Values[Offset][0]), vals); ++Offset; for(ALsizei i{1};;) { @@ -115,10 +115,10 @@ static inline void ApplyCoeffs(ALsizei Offset, ALfloat (&Values)[HRIR_LENGTH][2] break; count = IrSize-1; } - vals = _mm_loadl_pi(vals, (__m64*)&Values[Offset][0]); + vals = _mm_loadl_pi(vals, reinterpret_cast<__m64*>(&Values[Offset][0])); imp0 = _mm_movehl_ps(imp0, imp0); vals = _mm_add_ps(imp0, vals); - _mm_storel_pi((__m64*)&Values[Offset][0], vals); + _mm_storel_pi(reinterpret_cast<__m64*>(&Values[Offset][0]), vals); } else { @@ -156,7 +156,7 @@ void Mix_SSE(const ALfloat *data, ALsizei OutChans, ALfloat (*RESTRICT OutBuffer ASSUME(OutChans > 0); ASSUME(BufferSize > 0); - const ALfloat delta{(Counter > 0) ? 1.0f/(ALfloat)Counter : 0.0f}; + const ALfloat delta{(Counter > 0) ? 1.0f / static_cast(Counter) : 0.0f}; for(ALsizei c{0};c < OutChans;c++) { ALsizei pos{0}; diff --git a/Alc/mixvoice.cpp b/Alc/mixvoice.cpp index eb219bad..e52b330d 100644 --- a/Alc/mixvoice.cpp +++ b/Alc/mixvoice.cpp @@ -211,7 +211,7 @@ template<> inline ALfloat LoadSample(FmtTypeTraits::Type val template<> inline ALfloat LoadSample(FmtTypeTraits::Type val) { return val; } template<> inline ALfloat LoadSample(FmtTypeTraits::Type val) -{ return (ALfloat)val; } +{ return static_cast(val); } template<> inline ALfloat LoadSample(FmtTypeTraits::Type val) { return muLawDecompressionTable[val] * (1.0f/32768.0f); } template<> inline ALfloat LoadSample(FmtTypeTraits::Type val) @@ -295,7 +295,7 @@ ALboolean MixSource(ALvoice *voice, const ALuint SourceID, ALCcontext *Context, /* Get source info */ bool isplaying{true}; /* Will only be called while playing. */ bool isstatic{(voice->Flags&VOICE_IS_STATIC) != 0}; - ALsizei DataPosInt{(ALsizei)voice->position.load(std::memory_order_acquire)}; + ALsizei DataPosInt{static_cast(voice->position.load(std::memory_order_acquire))}; ALsizei DataPosFrac{voice->position_fraction.load(std::memory_order_relaxed)}; ALbufferlistitem *BufferListItem{voice->current_buffer.load(std::memory_order_relaxed)}; ALbufferlistitem *BufferLoopItem{voice->loop_buffer.load(std::memory_order_relaxed)}; @@ -603,13 +603,13 @@ ALboolean MixSource(ALvoice *voice, const ALuint SourceID, ALCcontext *Context, * this mix handles. */ ALfloat gain{lerp(parms.Hrtf.Old.Gain, parms.Hrtf.Target.Gain, - minf(1.0f, (ALfloat)fademix/Counter))}; + minf(1.0f, static_cast(fademix))/Counter)}; MixHrtfParams hrtfparams; hrtfparams.Coeffs = &parms.Hrtf.Target.Coeffs; hrtfparams.Delay[0] = parms.Hrtf.Target.Delay[0]; hrtfparams.Delay[1] = parms.Hrtf.Target.Delay[1]; hrtfparams.Gain = 0.0f; - hrtfparams.GainStep = gain / (ALfloat)fademix; + hrtfparams.GainStep = gain / static_cast(fademix); MixHrtfBlendSamples( voice->Direct.Buffer[OutLIdx], voice->Direct.Buffer[OutRIdx], @@ -631,14 +631,14 @@ ALboolean MixSource(ALvoice *voice, const ALuint SourceID, ALCcontext *Context, */ if(Counter > DstBufferSize) gain = lerp(parms.Hrtf.Old.Gain, gain, - (ALfloat)todo/(Counter-fademix)); + static_cast(todo)/(Counter-fademix)); MixHrtfParams hrtfparams; hrtfparams.Coeffs = &parms.Hrtf.Target.Coeffs; hrtfparams.Delay[0] = parms.Hrtf.Target.Delay[0]; hrtfparams.Delay[1] = parms.Hrtf.Target.Delay[1]; hrtfparams.Gain = parms.Hrtf.Old.Gain; - hrtfparams.GainStep = (gain - parms.Hrtf.Old.Gain) / (ALfloat)todo; + hrtfparams.GainStep = (gain - parms.Hrtf.Old.Gain) / static_cast(todo); MixHrtfSamples( voice->Direct.Buffer[OutLIdx], voice->Direct.Buffer[OutRIdx], samples+fademix, voice->Offset+fademix, OutPos+fademix, IrSize, diff --git a/Alc/panning.cpp b/Alc/panning.cpp index c311e31f..e184a13d 100644 --- a/Alc/panning.cpp +++ b/Alc/panning.cpp @@ -273,12 +273,12 @@ void InitDistanceComp(ALCdevice *device, const AmbDecConf *conf, const ALsizei ( const ALfloat delay{ std::floor((maxdist - speaker.Distance)/SPEEDOFSOUNDMETRESPERSEC*srate + 0.5f) }; - if(delay >= (ALfloat)MAX_DELAY_LENGTH) + if(delay >= static_cast(MAX_DELAY_LENGTH)) ERR("Delay for speaker \"%s\" exceeds buffer length (%f >= %d)\n", speaker.Name.c_str(), delay, MAX_DELAY_LENGTH); device->ChannelDelay[chan].Length = static_cast(clampf( - delay, 0.0f, (ALfloat)(MAX_DELAY_LENGTH-1) + delay, 0.0f, static_cast(MAX_DELAY_LENGTH-1) )); device->ChannelDelay[chan].Gain = speaker.Distance / maxdist; TRACE("Channel %u \"%s\" distance compensation: %d samples, %f gain\n", chan, @@ -951,7 +951,7 @@ void aluInitRenderer(ALCdevice *device, ALint hrtf_id, HrtfRequestMode hrtf_appr * front-right channels, with a crossover at 5khz (could be * higher). */ - const ALfloat scale{(ALfloat)(5000.0 / device->Frequency)}; + const ALfloat scale{static_cast(5000.0 / device->Frequency)}; stablizer->LFilter.init(scale); stablizer->RFilter = stablizer->LFilter; @@ -1016,7 +1016,7 @@ void aluInitRenderer(ALCdevice *device, ALint hrtf_id, HrtfRequestMode hrtf_appr if(device->HrtfList.empty()) device->HrtfList = EnumerateHrtf(device->DeviceName.c_str()); - if(hrtf_id >= 0 && (size_t)hrtf_id < device->HrtfList.size()) + if(hrtf_id >= 0 && static_cast(hrtf_id) < device->HrtfList.size()) { const EnumeratedHrtf &entry = device->HrtfList[hrtf_id]; HrtfEntry *hrtf{GetLoadedHrtf(entry.hrtf)}; diff --git a/OpenAL32/alBuffer.cpp b/OpenAL32/alBuffer.cpp index 7f2085d8..9781ea0c 100644 --- a/OpenAL32/alBuffer.cpp +++ b/OpenAL32/alBuffer.cpp @@ -204,8 +204,9 @@ void LoadData(ALCcontext *context, ALbuffer *ALBuf, ALuint freq, ALsizei size, U case UserFmtBFormat2D: DstChannels = FmtBFormat2D; break; case UserFmtBFormat3D: DstChannels = FmtBFormat3D; break; } - if(UNLIKELY((long)SrcChannels != (long)DstChannels)) - SETERR_RETURN(context, AL_INVALID_ENUM,, "Invalid format"); + if (UNLIKELY(static_cast(SrcChannels) != + static_cast(DstChannels))) + SETERR_RETURN(context, AL_INVALID_ENUM, , "Invalid format"); /* IMA4 and MSADPCM convert to 16-bit short. */ FmtType DstType{FmtUByte}; @@ -227,9 +228,10 @@ void LoadData(ALCcontext *context, ALbuffer *ALBuf, ALuint freq, ALsizei size, U */ if((access&MAP_READ_WRITE_FLAGS)) { - if(UNLIKELY((long)SrcType != (long)DstType)) - SETERR_RETURN(context, AL_INVALID_VALUE,, "%s samples cannot be mapped", - NameFromUserFmtType(SrcType)); + if (UNLIKELY(static_cast(SrcType) != static_cast(DstType))) + SETERR_RETURN(context, AL_INVALID_VALUE, , + "%s samples cannot be mapped", + NameFromUserFmtType(SrcType)); } ALsizei unpackalign{ALBuf->UnpackAlign.load()}; @@ -313,7 +315,7 @@ void LoadData(ALCcontext *context, ALbuffer *ALBuf, ALuint freq, ALsizei size, U } else { - assert((long)SrcType == (long)DstType); + assert(static_cast(SrcType) == static_cast(DstType)); if(data != nullptr && !ALBuf->mData.empty()) std::copy_n(static_cast(data), frames*FrameSize, ALBuf->mData.begin()); ALBuf->OriginalAlign = 1; @@ -683,9 +685,11 @@ AL_API ALvoid AL_APIENTRY alBufferSubDataSOFT(ALuint buffer, ALenum format, cons ALsizei align{SanitizeAlignment(srctype, unpack_align)}; if(UNLIKELY(align < 1)) alSetError(context.get(), AL_INVALID_VALUE, "Invalid unpack alignment %d", unpack_align); - else if(UNLIKELY((long)srcchannels != (long)albuf->mFmtChannels || - srctype != albuf->OriginalType)) - alSetError(context.get(), AL_INVALID_ENUM, "Unpacking data with mismatched format"); + else if (UNLIKELY(static_cast(srcchannels) != + static_cast(albuf->mFmtChannels) || + srctype != albuf->OriginalType)) + alSetError(context.get(), AL_INVALID_ENUM, + "Unpacking data with mismatched format"); else if(UNLIKELY(align != albuf->OriginalAlign)) alSetError(context.get(), AL_INVALID_VALUE, "Unpacking data with alignment %u does not match original alignment %u", @@ -730,8 +734,9 @@ AL_API ALvoid AL_APIENTRY alBufferSubDataSOFT(ALuint buffer, ALenum format, cons static_cast(data), num_chans, length, align); else { - assert((long)srctype == (long)albuf->mFmtType); - memcpy(dst, data, length*frame_size); + assert(static_cast(srctype) == + static_cast(albuf->mFmtType)); + memcpy(dst, data, length * frame_size); } } } diff --git a/OpenAL32/alError.cpp b/OpenAL32/alError.cpp index 303fbeac..d65b910a 100644 --- a/OpenAL32/alError.cpp +++ b/OpenAL32/alError.cpp @@ -43,17 +43,17 @@ void alSetError(ALCcontext *context, ALenum errorCode, const char *msg, ...) int msglen{vsnprintf(message, sizeof(message), msg, args)}; va_end(args); - if(msglen < 0 || (size_t)msglen >= sizeof(message)) + if(msglen < 0 || static_cast(msglen) >= sizeof(message)) { message[sizeof(message)-1] = 0; - msglen = (int)strlen(message); + msglen = static_cast(strlen(message)); } if(msglen > 0) msg = message; else { msg = ""; - msglen = (int)strlen(msg); + msglen = static_cast(strlen(msg)); } WARN("Error generated on context %p, code 0x%04x, \"%s\"\n", diff --git a/OpenAL32/alExtension.cpp b/OpenAL32/alExtension.cpp index aef6f7a4..e5d4cdf1 100644 --- a/OpenAL32/alExtension.cpp +++ b/OpenAL32/alExtension.cpp @@ -67,6 +67,6 @@ AL_API ALvoid* AL_APIENTRY alGetProcAddress(const ALchar *funcName) AL_API ALenum AL_APIENTRY alGetEnumValue(const ALchar *enumName) { - if(!enumName) return (ALenum)0; + if(!enumName) return static_cast(0); return alcGetEnumValue(nullptr, enumName); } diff --git a/OpenAL32/alListener.cpp b/OpenAL32/alListener.cpp index 7ed36f14..14fc58fc 100644 --- a/OpenAL32/alListener.cpp +++ b/OpenAL32/alListener.cpp @@ -169,7 +169,7 @@ AL_API void AL_APIENTRY alListener3i(ALenum param, ALint value1, ALint value2, A { case AL_POSITION: case AL_VELOCITY: - alListener3f(param, (ALfloat)value1, (ALfloat)value2, (ALfloat)value3); + alListener3f(param, static_cast(value1), static_cast(value2), static_cast(value3)); return; } @@ -194,16 +194,16 @@ AL_API void AL_APIENTRY alListeneriv(ALenum param, const ALint *values) { case AL_POSITION: case AL_VELOCITY: - alListener3f(param, (ALfloat)values[0], (ALfloat)values[1], (ALfloat)values[2]); + alListener3f(param, static_cast(values[0]), static_cast(values[1]), static_cast(values[2])); return; case AL_ORIENTATION: - fvals[0] = (ALfloat)values[0]; - fvals[1] = (ALfloat)values[1]; - fvals[2] = (ALfloat)values[2]; - fvals[3] = (ALfloat)values[3]; - fvals[4] = (ALfloat)values[4]; - fvals[5] = (ALfloat)values[5]; + fvals[0] = static_cast(values[0]); + fvals[1] = static_cast(values[1]); + fvals[2] = static_cast(values[2]); + fvals[3] = static_cast(values[3]); + fvals[4] = static_cast(values[4]); + fvals[5] = static_cast(values[5]); alListenerfv(param, fvals); return; } @@ -345,15 +345,15 @@ AL_API void AL_APIENTRY alGetListener3i(ALenum param, ALint *value1, ALint *valu else switch(param) { case AL_POSITION: - *value1 = (ALint)listener.Position[0]; - *value2 = (ALint)listener.Position[1]; - *value3 = (ALint)listener.Position[2]; + *value1 = static_cast(listener.Position[0]); + *value2 = static_cast(listener.Position[1]); + *value3 = static_cast(listener.Position[2]); break; case AL_VELOCITY: - *value1 = (ALint)listener.Velocity[0]; - *value2 = (ALint)listener.Velocity[1]; - *value3 = (ALint)listener.Velocity[2]; + *value1 = static_cast(listener.Velocity[0]); + *value2 = static_cast(listener.Velocity[1]); + *value3 = static_cast(listener.Velocity[2]); break; default: @@ -383,12 +383,12 @@ AL_API void AL_APIENTRY alGetListeneriv(ALenum param, ALint* values) { case AL_ORIENTATION: // AT then UP - values[0] = (ALint)listener.OrientAt[0]; - values[1] = (ALint)listener.OrientAt[1]; - values[2] = (ALint)listener.OrientAt[2]; - values[3] = (ALint)listener.OrientUp[0]; - values[4] = (ALint)listener.OrientUp[1]; - values[5] = (ALint)listener.OrientUp[2]; + values[0] = static_cast(listener.OrientAt[0]); + values[1] = static_cast(listener.OrientAt[1]); + values[2] = static_cast(listener.OrientAt[2]); + values[3] = static_cast(listener.OrientUp[0]); + values[4] = static_cast(listener.OrientUp[1]); + values[5] = static_cast(listener.OrientUp[2]); break; default: diff --git a/OpenAL32/alSource.cpp b/OpenAL32/alSource.cpp index 639d1c37..a04ef6b7 100644 --- a/OpenAL32/alSource.cpp +++ b/OpenAL32/alSource.cpp @@ -173,8 +173,8 @@ ALint64 GetSourceSampleOffset(ALsource *Source, ALCcontext *context, std::chrono { Current = voice->current_buffer.load(std::memory_order_relaxed); - readPos = (ALuint64)voice->position.load(std::memory_order_relaxed) << 32; - readPos |= (ALuint64)voice->position_fraction.load(std::memory_order_relaxed) << + readPos = static_cast(voice->position.load(std::memory_order_relaxed)) << 32; + readPos |= static_cast(voice->position_fraction.load(std::memory_order_relaxed)) << (32-FRACTIONBITS); } std::atomic_thread_fence(std::memory_order_acquire); @@ -185,13 +185,13 @@ ALint64 GetSourceSampleOffset(ALsource *Source, ALCcontext *context, std::chrono const ALbufferlistitem *BufferList{Source->queue}; while(BufferList && BufferList != Current) { - readPos += (ALuint64)BufferList->max_samples << 32; + readPos += static_cast(BufferList->max_samples) << 32; BufferList = BufferList->next.load(std::memory_order_relaxed); } readPos = minu64(readPos, 0x7fffffffffffffff_u64); } - return (ALint64)readPos; + return static_cast(readPos); } /* GetSourceSecOffset @@ -219,7 +219,7 @@ ALdouble GetSourceSecOffset(ALsource *Source, ALCcontext *context, std::chrono:: { Current = voice->current_buffer.load(std::memory_order_relaxed); - readPos = (ALuint64)voice->position.load(std::memory_order_relaxed) << FRACTIONBITS; + readPos = static_cast(voice->position.load(std::memory_order_relaxed)) << FRACTIONBITS; readPos |= voice->position_fraction.load(std::memory_order_relaxed); } std::atomic_thread_fence(std::memory_order_acquire); @@ -234,7 +234,7 @@ ALdouble GetSourceSecOffset(ALsource *Source, ALCcontext *context, std::chrono:: { for(ALsizei i{0};!BufferFmt && i < BufferList->num_buffers;++i) BufferFmt = BufferList->buffers[i]; - readPos += (ALuint64)BufferList->max_samples << FRACTIONBITS; + readPos += static_cast(BufferList->max_samples) << FRACTIONBITS; BufferList = BufferList->next.load(std::memory_order_relaxed); } @@ -246,8 +246,8 @@ ALdouble GetSourceSecOffset(ALsource *Source, ALCcontext *context, std::chrono:: } assert(BufferFmt != nullptr); - offset = (ALdouble)readPos / (ALdouble)FRACTIONONE / - (ALdouble)BufferFmt->Frequency; + offset = static_cast(readPos) / static_castFRACTIONONE / + static_cast(BufferFmt->Frequency); } return offset; @@ -318,11 +318,11 @@ ALdouble GetSourceOffset(ALsource *Source, ALenum name, ALCcontext *context) switch(name) { case AL_SEC_OFFSET: - offset = (readPos + (ALdouble)readPosFrac/FRACTIONONE) / BufferFmt->Frequency; + offset = (readPos + static_cast(readPosFrac)/FRACTIONONE) / BufferFmt->Frequency; break; case AL_SAMPLE_OFFSET: - offset = readPos + (ALdouble)readPosFrac/FRACTIONONE; + offset = readPos + static_cast(readPosFrac)/FRACTIONONE; break; case AL_BYTE_OFFSET: @@ -333,7 +333,7 @@ ALdouble GetSourceOffset(ALsource *Source, ALenum name, ALCcontext *context) ALuint FrameBlockSize = BufferFmt->OriginalAlign; /* Round down to nearest ADPCM block */ - offset = (ALdouble)(readPos / FrameBlockSize * BlockSize); + offset = static_cast(readPos / FrameBlockSize * BlockSize); } else if(BufferFmt->OriginalType == UserFmtMSADPCM) { @@ -342,13 +342,13 @@ ALdouble GetSourceOffset(ALsource *Source, ALenum name, ALCcontext *context) ALuint FrameBlockSize = BufferFmt->OriginalAlign; /* Round down to nearest ADPCM block */ - offset = (ALdouble)(readPos / FrameBlockSize * BlockSize); + offset = static_cast(readPos / FrameBlockSize * BlockSize); } else { const ALsizei FrameSize{FrameSizeFromFmt(BufferFmt->mFmtChannels, BufferFmt->mFmtType)}; - offset = (ALdouble)(readPos * FrameSize); + offset = static_cast(readPos * FrameSize); } break; } @@ -390,7 +390,7 @@ ALboolean GetSampleOffset(ALsource *Source, ALuint *offset, ALsizei *frac) { case AL_BYTE_OFFSET: /* Determine the ByteOffset (and ensure it is block aligned) */ - *offset = (ALuint)Source->Offset; + *offset = static_cast(Source->Offset); if(BufferFmt->OriginalType == UserFmtIMA4) { ALsizei align = (BufferFmt->OriginalAlign-1)/2 + 4; @@ -410,14 +410,14 @@ ALboolean GetSampleOffset(ALsource *Source, ALuint *offset, ALsizei *frac) case AL_SAMPLE_OFFSET: dblfrac = modf(Source->Offset, &dbloff); - *offset = (ALuint)mind(dbloff, std::numeric_limits::max()); - *frac = (ALsizei)mind(dblfrac*FRACTIONONE, FRACTIONONE-1.0); + *offset = static_cast(mind(dbloff, std::numeric_limits::max())); + *frac = static_cast(mind(dblfrac*FRACTIONONE, FRACTIONONE-1.0)); break; case AL_SEC_OFFSET: dblfrac = modf(Source->Offset*BufferFmt->Frequency, &dbloff); - *offset = (ALuint)mind(dbloff, std::numeric_limits::max()); - *frac = (ALsizei)mind(dblfrac*FRACTIONONE, FRACTIONONE-1.0); + *offset = static_cast(mind(dbloff, std::numeric_limits::max())); + *frac = static_cast(mind(dblfrac*FRACTIONONE, FRACTIONONE-1.0)); break; } Source->OffsetType = AL_NONE; @@ -443,7 +443,7 @@ ALboolean ApplyOffset(ALsource *Source, ALvoice *voice) ALbufferlistitem *BufferList{Source->queue}; while(BufferList && totalBufferLen <= offset) { - if((ALuint)BufferList->max_samples > offset-totalBufferLen) + if(static_cast(BufferList->max_samples) > offset-totalBufferLen) { /* Offset is in this buffer */ voice->position.store(offset - totalBufferLen, std::memory_order_relaxed); @@ -1174,12 +1174,12 @@ ALboolean SetSourcefv(ALsource *Source, ALCcontext *Context, SourceProp prop, co case AL_DIRECT_CHANNELS_SOFT: case AL_SOURCE_RESAMPLER_SOFT: case AL_SOURCE_SPATIALIZE_SOFT: - ival = (ALint)values[0]; + ival = static_cast(values[0]); return SetSourceiv(Source, Context, prop, &ival); case AL_BUFFERS_QUEUED: case AL_BUFFERS_PROCESSED: - ival = (ALint)((ALuint)values[0]); + ival = static_cast(static_cast(values[0])); return SetSourceiv(Source, Context, prop, &ival); case AL_BUFFER: @@ -1219,14 +1219,14 @@ ALboolean SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, co case AL_SOURCE_RELATIVE: CHECKVAL(*values == AL_FALSE || *values == AL_TRUE); - Source->HeadRelative = (ALboolean)*values; + Source->HeadRelative = static_cast(*values); DO_UPDATEPROPS(); return AL_TRUE; case AL_LOOPING: CHECKVAL(*values == AL_FALSE || *values == AL_TRUE); - Source->Looping = (ALboolean)*values; + Source->Looping = static_cast(*values); if(IsPlayingOrPaused(Source)) { ALvoice *voice{GetSourceVoice(Source, Context)}; @@ -1413,7 +1413,7 @@ ALboolean SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, co if(!(values[0] == 0 || (slot=LookupEffectSlot(Context, values[0])) != nullptr)) SETERR_RETURN(Context, AL_INVALID_VALUE, AL_FALSE, "Invalid effect ID %u", values[0]); - if((ALuint)values[1] >= (ALuint)device->NumAuxSends) + if(static_cast(values[1]) >= static_cast(device->NumAuxSends)) SETERR_RETURN(Context, AL_INVALID_VALUE, AL_FALSE, "Invalid send %u", values[1]); filtlock = std::unique_lock{device->FilterLock}; @@ -1483,26 +1483,26 @@ ALboolean SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, co case AL_AIR_ABSORPTION_FACTOR: case AL_ROOM_ROLLOFF_FACTOR: case AL_SOURCE_RADIUS: - fvals[0] = (ALfloat)*values; + fvals[0] = static_cast(*values); return SetSourcefv(Source, Context, prop, fvals); /* 3x float */ case AL_POSITION: case AL_VELOCITY: case AL_DIRECTION: - fvals[0] = (ALfloat)values[0]; - fvals[1] = (ALfloat)values[1]; - fvals[2] = (ALfloat)values[2]; + fvals[0] = static_cast(values[0]); + fvals[1] = static_cast(values[1]); + fvals[2] = static_cast(values[2]); return SetSourcefv(Source, Context, prop, fvals); /* 6x float */ case AL_ORIENTATION: - fvals[0] = (ALfloat)values[0]; - fvals[1] = (ALfloat)values[1]; - fvals[2] = (ALfloat)values[2]; - fvals[3] = (ALfloat)values[3]; - fvals[4] = (ALfloat)values[4]; - fvals[5] = (ALfloat)values[5]; + fvals[0] = static_cast(values[0]); + fvals[1] = static_cast(values[1]); + fvals[2] = static_cast(values[2]); + fvals[3] = static_cast(values[3]); + fvals[4] = static_cast(values[4]); + fvals[5] = static_cast(values[5]); return SetSourcefv(Source, Context, prop, fvals); case AL_SAMPLE_OFFSET_LATENCY_SOFT: @@ -1550,7 +1550,7 @@ ALboolean SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, case AL_SOURCE_SPATIALIZE_SOFT: CHECKVAL(*values <= INT_MAX && *values >= INT_MIN); - ivals[0] = (ALint)*values; + ivals[0] = static_cast(*values); return SetSourceiv(Source, Context, prop, ivals); /* 1x uint */ @@ -1558,7 +1558,7 @@ ALboolean SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, case AL_DIRECT_FILTER: CHECKVAL(*values <= UINT_MAX && *values >= 0); - ivals[0] = (ALuint)*values; + ivals[0] = static_cast(*values); return SetSourceiv(Source, Context, prop, ivals); /* 3x uint */ @@ -1567,9 +1567,9 @@ ALboolean SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, values[1] <= UINT_MAX && values[1] >= 0 && values[2] <= UINT_MAX && values[2] >= 0); - ivals[0] = (ALuint)values[0]; - ivals[1] = (ALuint)values[1]; - ivals[2] = (ALuint)values[2]; + ivals[0] = static_cast(values[0]); + ivals[1] = static_cast(values[1]); + ivals[2] = static_cast(values[2]); return SetSourceiv(Source, Context, prop, ivals); /* 1x float */ @@ -1588,26 +1588,26 @@ ALboolean SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, case AL_AIR_ABSORPTION_FACTOR: case AL_ROOM_ROLLOFF_FACTOR: case AL_SOURCE_RADIUS: - fvals[0] = (ALfloat)*values; + fvals[0] = static_cast(*values); return SetSourcefv(Source, Context, prop, fvals); /* 3x float */ case AL_POSITION: case AL_VELOCITY: case AL_DIRECTION: - fvals[0] = (ALfloat)values[0]; - fvals[1] = (ALfloat)values[1]; - fvals[2] = (ALfloat)values[2]; + fvals[0] = static_cast(values[0]); + fvals[1] = static_cast(values[1]); + fvals[2] = static_cast(values[2]); return SetSourcefv(Source, Context, prop, fvals); /* 6x float */ case AL_ORIENTATION: - fvals[0] = (ALfloat)values[0]; - fvals[1] = (ALfloat)values[1]; - fvals[2] = (ALfloat)values[2]; - fvals[3] = (ALfloat)values[3]; - fvals[4] = (ALfloat)values[4]; - fvals[5] = (ALfloat)values[5]; + fvals[0] = static_cast(values[0]); + fvals[1] = static_cast(values[1]); + fvals[2] = static_cast(values[2]); + fvals[3] = static_cast(values[3]); + fvals[4] = static_cast(values[4]); + fvals[5] = static_cast(values[5]); return SetSourcefv(Source, Context, prop, fvals); case AL_SEC_OFFSET_LATENCY_SOFT: @@ -1718,7 +1718,7 @@ ALboolean GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, AL clocktime = GetClockLatency(device); } if(srcclock == clocktime.ClockTime) - values[1] = (ALdouble)clocktime.Latency.count() / 1000000000.0; + values[1] = static_cast(clocktime.Latency.count()) / 1000000000.0; else { /* If the clock time incremented, reduce the latency by that @@ -1726,7 +1726,7 @@ ALboolean GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, AL * earlier. */ std::chrono::nanoseconds diff = clocktime.ClockTime - srcclock; - values[1] = (ALdouble)(clocktime.Latency - std::min(clocktime.Latency, diff)).count() / + values[1] = static_cast((clocktime.Latency - std::min(clocktime.Latency, diff)).count()) / 1000000000.0; } return AL_TRUE; @@ -1778,7 +1778,7 @@ ALboolean GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, AL case AL_SOURCE_RESAMPLER_SOFT: case AL_SOURCE_SPATIALIZE_SOFT: if((err=GetSourceiv(Source, Context, prop, ivals)) != AL_FALSE) - *values = (ALdouble)ivals[0]; + *values = static_cast(ivals[0]); return err; case AL_BUFFER: @@ -1914,7 +1914,7 @@ ALboolean GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, AL case AL_CONE_OUTER_GAINHF: case AL_SOURCE_RADIUS: if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE) - *values = (ALint)dvals[0]; + *values = static_cast(dvals[0]); return err; /* 3x float/double */ @@ -1923,9 +1923,9 @@ ALboolean GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, AL case AL_DIRECTION: if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE) { - values[0] = (ALint)dvals[0]; - values[1] = (ALint)dvals[1]; - values[2] = (ALint)dvals[2]; + values[0] = static_cast(dvals[0]); + values[1] = static_cast(dvals[1]); + values[2] = static_cast(dvals[2]); } return err; @@ -1933,12 +1933,12 @@ ALboolean GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, AL case AL_ORIENTATION: if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE) { - values[0] = (ALint)dvals[0]; - values[1] = (ALint)dvals[1]; - values[2] = (ALint)dvals[2]; - values[3] = (ALint)dvals[3]; - values[4] = (ALint)dvals[4]; - values[5] = (ALint)dvals[5]; + values[0] = static_cast(dvals[0]); + values[1] = static_cast(dvals[1]); + values[2] = static_cast(dvals[2]); + values[3] = static_cast(dvals[3]); + values[4] = static_cast(dvals[4]); + values[5] = static_cast(dvals[5]); } return err; @@ -2018,7 +2018,7 @@ ALboolean GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, case AL_CONE_OUTER_GAINHF: case AL_SOURCE_RADIUS: if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE) - *values = (ALint64)dvals[0]; + *values = static_cast(dvals[0]); return err; /* 3x float/double */ @@ -2027,9 +2027,9 @@ ALboolean GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, case AL_DIRECTION: if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE) { - values[0] = (ALint64)dvals[0]; - values[1] = (ALint64)dvals[1]; - values[2] = (ALint64)dvals[2]; + values[0] = static_cast(dvals[0]); + values[1] = static_cast(dvals[1]); + values[2] = static_cast(dvals[2]); } return err; @@ -2037,12 +2037,12 @@ ALboolean GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, case AL_ORIENTATION: if((err=GetSourcedv(Source, Context, prop, dvals)) != AL_FALSE) { - values[0] = (ALint64)dvals[0]; - values[1] = (ALint64)dvals[1]; - values[2] = (ALint64)dvals[2]; - values[3] = (ALint64)dvals[3]; - values[4] = (ALint64)dvals[4]; - values[5] = (ALint64)dvals[5]; + values[0] = static_cast(dvals[0]); + values[1] = static_cast(dvals[1]); + values[2] = static_cast(dvals[2]); + values[3] = static_cast(dvals[3]); + values[4] = static_cast(dvals[4]); + values[5] = static_cast(dvals[5]); } return err; @@ -2068,16 +2068,16 @@ ALboolean GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, case AL_BUFFER: case AL_DIRECT_FILTER: if((err=GetSourceiv(Source, Context, prop, ivals)) != AL_FALSE) - *values = (ALuint)ivals[0]; + *values = static_cast(ivals[0]); return err; /* 3x uint */ case AL_AUXILIARY_SEND_FILTER: if((err=GetSourceiv(Source, Context, prop, ivals)) != AL_FALSE) { - values[0] = (ALuint)ivals[0]; - values[1] = (ALuint)ivals[1]; - values[2] = (ALuint)ivals[2]; + values[0] = static_cast(ivals[0]); + values[1] = static_cast(ivals[1]); + values[2] = static_cast(ivals[2]); } return err; @@ -2246,7 +2246,7 @@ AL_API ALvoid AL_APIENTRY alSourcedSOFT(ALuint source, ALenum param, ALdouble va alSetError(context.get(), AL_INVALID_ENUM, "Invalid double property 0x%04x", param); else { - ALfloat fval = (ALfloat)value; + ALfloat fval = static_cast(value); SetSourcefv(Source, context.get(), static_cast(param), &fval); } } @@ -2263,9 +2263,10 @@ AL_API ALvoid AL_APIENTRY alSource3dSOFT(ALuint source, ALenum param, ALdouble v alSetError(context.get(), AL_INVALID_NAME, "Invalid source ID %u", source); else if(DoubleValsByProp(param) != 3) alSetError(context.get(), AL_INVALID_ENUM, "Invalid 3-double property 0x%04x", param); - else - { - ALfloat fvals[3] = { (ALfloat)value1, (ALfloat)value2, (ALfloat)value3 }; + else { + ALfloat fvals[3] = {static_cast(value1), + static_cast(value2), + static_cast(value3)}; SetSourcefv(Source, context.get(), static_cast(param), fvals); } } @@ -2293,7 +2294,7 @@ AL_API ALvoid AL_APIENTRY alSourcedvSOFT(ALuint source, ALenum param, const ALdo ALint i; for(i = 0;i < count;i++) - fvals[i] = (ALfloat)values[i]; + fvals[i] = static_cast(values[i]); SetSourcefv(Source, context.get(), static_cast(param), fvals); } } @@ -2425,7 +2426,7 @@ AL_API ALvoid AL_APIENTRY alGetSourcef(ALuint source, ALenum param, ALfloat *val { ALdouble dval; if(GetSourcedv(Source, context.get(), static_cast(param), &dval)) - *value = (ALfloat)dval; + *value = static_cast(dval); } } @@ -2448,9 +2449,9 @@ AL_API ALvoid AL_APIENTRY alGetSource3f(ALuint source, ALenum param, ALfloat *va ALdouble dvals[3]; if(GetSourcedv(Source, context.get(), static_cast(param), dvals)) { - *value1 = (ALfloat)dvals[0]; - *value2 = (ALfloat)dvals[1]; - *value3 = (ALfloat)dvals[2]; + *value1 = static_cast(dvals[0]); + *value2 = static_cast(dvals[1]); + *value3 = static_cast(dvals[2]); } } } @@ -2478,7 +2479,7 @@ AL_API ALvoid AL_APIENTRY alGetSourcefv(ALuint source, ALenum param, ALfloat *va if(GetSourcedv(Source, context.get(), static_cast(param), dvals)) { for(ALint i{0};i < count;i++) - values[i] = (ALfloat)dvals[i]; + values[i] = static_cast(dvals[i]); } } } diff --git a/OpenAL32/alState.cpp b/OpenAL32/alState.cpp index 3f55687d..c6dd171e 100644 --- a/OpenAL32/alState.cpp +++ b/OpenAL32/alState.cpp @@ -195,36 +195,36 @@ AL_API ALdouble AL_APIENTRY alGetDouble(ALenum pname) switch(pname) { case AL_DOPPLER_FACTOR: - value = (ALdouble)context->DopplerFactor; + value = static_cast(context->DopplerFactor); break; case AL_DOPPLER_VELOCITY: - value = (ALdouble)context->DopplerVelocity; + value = static_cast(context->DopplerVelocity); break; case AL_DISTANCE_MODEL: - value = (ALdouble)context->mDistanceModel; + value = static_cast(context->mDistanceModel); break; case AL_SPEED_OF_SOUND: - value = (ALdouble)context->SpeedOfSound; + value = static_cast(context->SpeedOfSound); break; case AL_DEFERRED_UPDATES_SOFT: if(context->DeferUpdates.load(std::memory_order_acquire)) - value = (ALdouble)AL_TRUE; + value = static_cast(AL_TRUE); break; case AL_GAIN_LIMIT_SOFT: - value = (ALdouble)GAIN_MIX_MAX/context->GainBoost; + value = static_castGAIN_MIX_MAX/context->GainBoost; break; case AL_NUM_RESAMPLERS_SOFT: - value = (ALdouble)(ResamplerMax + 1); + value = static_cast(ResamplerMax + 1); break; case AL_DEFAULT_RESAMPLER_SOFT: - value = (ALdouble)ResamplerDefault; + value = static_cast(ResamplerDefault); break; default: @@ -252,7 +252,7 @@ AL_API ALfloat AL_APIENTRY alGetFloat(ALenum pname) break; case AL_DISTANCE_MODEL: - value = (ALfloat)context->mDistanceModel; + value = static_cast(context->mDistanceModel); break; case AL_SPEED_OF_SOUND: @@ -261,7 +261,7 @@ AL_API ALfloat AL_APIENTRY alGetFloat(ALenum pname) case AL_DEFERRED_UPDATES_SOFT: if(context->DeferUpdates.load(std::memory_order_acquire)) - value = (ALfloat)AL_TRUE; + value = static_cast(AL_TRUE); break; case AL_GAIN_LIMIT_SOFT: @@ -269,11 +269,11 @@ AL_API ALfloat AL_APIENTRY alGetFloat(ALenum pname) break; case AL_NUM_RESAMPLERS_SOFT: - value = (ALfloat)(ResamplerMax + 1); + value = static_cast(ResamplerMax + 1); break; case AL_DEFAULT_RESAMPLER_SOFT: - value = (ALfloat)ResamplerDefault; + value = static_cast(ResamplerDefault); break; default: @@ -293,28 +293,28 @@ AL_API ALint AL_APIENTRY alGetInteger(ALenum pname) switch(pname) { case AL_DOPPLER_FACTOR: - value = (ALint)context->DopplerFactor; + value = static_cast(context->DopplerFactor); break; case AL_DOPPLER_VELOCITY: - value = (ALint)context->DopplerVelocity; + value = static_cast(context->DopplerVelocity); break; case AL_DISTANCE_MODEL: - value = (ALint)context->mDistanceModel; + value = static_cast(context->mDistanceModel); break; case AL_SPEED_OF_SOUND: - value = (ALint)context->SpeedOfSound; + value = static_cast(context->SpeedOfSound); break; case AL_DEFERRED_UPDATES_SOFT: if(context->DeferUpdates.load(std::memory_order_acquire)) - value = (ALint)AL_TRUE; + value = static_cast(AL_TRUE); break; case AL_GAIN_LIMIT_SOFT: - value = (ALint)(GAIN_MIX_MAX/context->GainBoost); + value = static_cast(GAIN_MIX_MAX/context->GainBoost); break; case AL_NUM_RESAMPLERS_SOFT: @@ -663,7 +663,7 @@ AL_API ALvoid AL_APIENTRY alDopplerVelocity(ALfloat value) { static constexpr ALCchar msg[] = "alDopplerVelocity is deprecated in AL1.1, use alSpeedOfSound"; - const ALsizei msglen = (ALsizei)strlen(msg); + const ALsizei msglen = static_cast(strlen(msg)); std::lock_guard _{context->EventCbLock}; ALbitfieldSOFT enabledevts{context->EnabledEvts.load(std::memory_order_relaxed)}; if((enabledevts&EventType_Deprecated) && context->EventCb) @@ -749,7 +749,7 @@ AL_API const ALchar* AL_APIENTRY alGetStringiSOFT(ALenum pname, ALsizei index) switch(pname) { case AL_RESAMPLER_NAME_SOFT: - if(index < 0 || (size_t)index >= COUNTOF(ResamplerNames)) + if(index < 0 || static_cast(index) >= COUNTOF(ResamplerNames)) alSetError(context.get(), AL_INVALID_VALUE, "Resampler name index %d out of range", index); else diff --git a/common/alcomplex.cpp b/common/alcomplex.cpp index de2d1be9..ace1b43f 100644 --- a/common/alcomplex.cpp +++ b/common/alcomplex.cpp @@ -54,7 +54,7 @@ void complex_fft(std::complex *FFTBuffer, int FFTSize, double Sign) void complex_hilbert(std::complex *Buffer, int size) { - const double inverse_size = 1.0/(double)size; + const double inverse_size = 1.0/static_cast(size); for(int i{0};i < size;i++) Buffer[i].imag(0.0); diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index f9ced483..11ff126d 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -459,7 +459,7 @@ nanoseconds AudioState::getClockNoLock() { ALint ioffset; alGetSourcei(mSource, AL_SAMPLE_OFFSET, &ioffset); - offset[0] = (ALint64SOFT)ioffset << 32; + offset[0] = static_cast(ioffset) << 32; offset[1] = 0; } alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); @@ -545,7 +545,7 @@ int AudioState::getSync() /* Constrain the per-update difference to avoid exceedingly large skips */ diff = std::min(std::max(diff, -AudioSampleCorrectionMax), AudioSampleCorrectionMax); - return (int)std::chrono::duration_cast(diff*mCodecCtx->sample_rate).count(); + return static_cast(std::chrono::duration_cast(diff*mCodecCtx->sample_rate).count()); } int AudioState::decodeFrame() @@ -894,7 +894,7 @@ int AudioState::handler() mSwresCtx.reset(swr_alloc_set_opts(nullptr, mDstChanLayout, mDstSampleFmt, mCodecCtx->sample_rate, mCodecCtx->channel_layout ? mCodecCtx->channel_layout : - (uint64_t)av_get_default_channel_layout(mCodecCtx->channels), + static_cast(av_get_default_channel_layout(mCodecCtx->channels)), mCodecCtx->sample_fmt, mCodecCtx->sample_rate, 0, nullptr )); @@ -910,9 +910,9 @@ int AudioState::handler() if(EnableDirectOut) alSourcei(mSource, AL_DIRECT_CHANNELS_SOFT, AL_TRUE); - if(EnableWideStereo) - { - ALfloat angles[2] = { (ALfloat)(M_PI/3.0), (ALfloat)(-M_PI/3.0) }; + if (EnableWideStereo) { + ALfloat angles[2] = {static_cast(M_PI / 3.0), + static_cast(-M_PI / 3.0)}; alSourcefv(mSource, AL_STEREO_ANGLES, angles); } @@ -952,7 +952,7 @@ int AudioState::handler() /* Refill the buffer queue. */ ALint queued; alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); - while((ALuint)queued < mBuffers.size()) + while(static_cast(queued) < mBuffers.size()) { ALuint bufid = mBuffers[mBufferIdx]; @@ -1081,15 +1081,15 @@ void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer) mCodecCtx->height; } if(aspect_ratio <= 0.0f) - aspect_ratio = (float)mCodecCtx->width / (float)mCodecCtx->height; + aspect_ratio = static_cast(mCodecCtx->width) / static_cast(mCodecCtx->height); SDL_GetWindowSize(screen, &win_w, &win_h); h = win_h; - w = ((int)rint(h * aspect_ratio) + 3) & ~3; + w = (static_cast(rint(h * aspect_ratio)) + 3) & ~3; if(w > win_w) { w = win_w; - h = ((int)rint(w / aspect_ratio) + 3) & ~3; + h = (static_cast(rint(w / aspect_ratio)) + 3) & ~3; } x = (win_w - w) / 2; y = (win_h - h) / 2; @@ -1225,9 +1225,9 @@ void VideoState::updatePicture(SDL_Window *screen, SDL_Renderer *renderer) { double aspect_ratio = av_q2d(mCodecCtx->sample_aspect_ratio); if(aspect_ratio >= 1.0) - w = (int)(w*aspect_ratio + 0.5); + w = static_cast(w*aspect_ratio + 0.5); else if(aspect_ratio > 0.0) - h = (int)(h/aspect_ratio + 0.5); + h = static_cast(h/aspect_ratio + 0.5); } SDL_SetWindowSize(screen, w, h); } @@ -1274,7 +1274,7 @@ void VideoState::updatePicture(SDL_Window *screen, SDL_Renderer *renderer) pict_linesize[1] = pitch / 2; pict_linesize[2] = pitch / 2; - sws_scale(mSwscaleCtx.get(), (const uint8_t**)frame->data, + sws_scale(mSwscaleCtx.get(), reinterpret_cast(frame->data), frame->linesize, 0, h, pict_data, pict_linesize); SDL_UnlockTexture(vp->mImage); } @@ -1458,7 +1458,7 @@ nanoseconds MovieState::getDuration() int MovieState::streamComponentOpen(int stream_index) { - if(stream_index < 0 || (unsigned int)stream_index >= mFormatCtx->nb_streams) + if(stream_index < 0 || static_cast(stream_index) >= mFormatCtx->nb_streams) return -1; /* Get a pointer to the codec context for the stream, and open the diff --git a/utils/alsoft-config/mainwindow.cpp b/utils/alsoft-config/mainwindow.cpp index ce319637..920bc5a3 100644 --- a/utils/alsoft-config/mainwindow.cpp +++ b/utils/alsoft-config/mainwindow.cpp @@ -1229,7 +1229,7 @@ void MainWindow::updateJackBufferSizeEdit(int size) void MainWindow::updateJackBufferSizeSlider() { int value = ui->jackBufferSizeLine->text().toInt(); - int pos = (int)floor(log2(value) + 0.5); + int pos = static_cast(floor(log2(value) + 0.5)); ui->jackBufferSizeSlider->setSliderPosition(pos); enableApplyButton(); } diff --git a/utils/makehrtf.cpp b/utils/makehrtf.cpp index 30440838..ce6643a4 100644 --- a/utils/makehrtf.cpp +++ b/utils/makehrtf.cpp @@ -986,8 +986,8 @@ static void LimitMagnitudeResponse(const uint n, const uint m, const double limi for(i = 0;i < m;i++) out[i] = 20.0 * std::log10(in[i]); // Use six octaves to calculate the average magnitude of the signal. - lower = ((uint)std::ceil(n / std::pow(2.0, 8.0))) - 1; - upper = ((uint)std::floor(n / std::pow(2.0, 2.0))) - 1; + lower = (static_cast(std::ceil(n / std::pow(2.0, 8.0)))) - 1; + upper = (static_cast(std::floor(n / std::pow(2.0, 2.0)))) - 1; ave = 0.0; for(i = lower;i <= upper;i++) ave += out[i]; @@ -1121,8 +1121,8 @@ static uint CalcKaiserOrder(const double rejection, const double transition) { double w_t = 2.0 * M_PI * transition; if(rejection > 21.0) - return (uint)std::ceil((rejection - 7.95) / (2.285 * w_t)); - return (uint)std::ceil(5.79 / w_t); + return static_cast(std::ceil((rejection - 7.95) / (2.285 * w_t))); + return static_cast(std::ceil(5.79 / w_t)); } // Calculates the beta value of the Kaiser window. Rejection is in dB. @@ -1150,7 +1150,7 @@ static double CalcKaiserBeta(const double rejection) */ static double SincFilter(const int l, const double b, const double gain, const double cutoff, const int i) { - return Kaiser(b, (double)(i - l) / l) * 2.0 * gain * cutoff * Sinc(2.0 * cutoff * (i - l)); + return Kaiser(b, static_cast(i - l) / l) * 2.0 * gain * cutoff * Sinc(2.0 * cutoff * (i - l)); } /* This is a polyphase sinc-filtered resampler. @@ -1211,8 +1211,8 @@ static void ResamplerSetup(ResamplerT *rs, const uint srcRate, const uint dstRat rs->mM = l*2 + 1; rs->mL = l; rs->mF.resize(rs->mM); - for(i = 0;i < ((int)rs->mM);i++) - rs->mF[i] = SincFilter((int)l, beta, rs->mP, cutoff, i); + for(i = 0;i < (static_cast(rs->mM));i++) + rs->mF[i] = SincFilter(static_cast(l), beta, rs->mP, cutoff, i); } // Perform the upsample-filter-downsample resampling operation using a @@ -1365,13 +1365,13 @@ static int ReadBinAsDouble(FILE *fp, const char *filename, const ByteOrderT orde else { if(bits > 0) - v4.ui >>= (8*bytes) - ((uint)bits); + v4.ui >>= (8*bytes) - (static_cast(bits)); else v4.ui &= (0xFFFFFFFF >> (32+bits)); - if(v4.ui&(uint)(1<<(std::abs(bits)-1))) + if(v4.ui&static_cast(1<<(std::abs(bits)-1))) v4.ui |= (0xFFFFFFFF << std::abs(bits)); - *out = v4.i / (double)(1<<(std::abs(bits)-1)); + *out = v4.i / static_cast(1<<(std::abs(bits)-1)); } } return 1; @@ -1410,7 +1410,7 @@ static int ReadAsciiAsDouble(TokenReaderT *tr, const char *filename, const Eleme fprintf(stderr, "Error: Bad read from file '%s'.\n", filename); return 0; } - *out = v / (double)((1<<(bits-1))-1); + *out = v / static_cast((1<<(bits-1))-1); } return 1; } @@ -1425,7 +1425,7 @@ static int ReadWaveFormat(FILE *fp, const ByteOrderT order, const uint hrirRate, chunkSize = 0; do { if(chunkSize > 0) - fseek(fp, (long) chunkSize, SEEK_CUR); + fseek(fp, static_cast(chunkSize), SEEK_CUR); if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) || !ReadBin4(fp, src->mPath, order, 4, &chunkSize)) return 0; @@ -1457,15 +1457,15 @@ static int ReadWaveFormat(FILE *fp, const ByteOrderT order, const uint hrirRate, fseek(fp, 4, SEEK_CUR); if(!ReadBin4(fp, src->mPath, order, 2, &format)) return 0; - fseek(fp, (long)(chunkSize - 26), SEEK_CUR); + fseek(fp, static_cast(chunkSize - 26), SEEK_CUR); } else { bits = 8 * size; if(chunkSize > 14) - fseek(fp, (long)(chunkSize - 16), SEEK_CUR); + fseek(fp, static_cast(chunkSize - 16), SEEK_CUR); else - fseek(fp, (long)(chunkSize - 14), SEEK_CUR); + fseek(fp, static_cast(chunkSize - 14), SEEK_CUR); } if(format != WAVE_FORMAT_PCM && format != WAVE_FORMAT_IEEE_FLOAT) { @@ -1506,7 +1506,7 @@ static int ReadWaveFormat(FILE *fp, const ByteOrderT order, const uint hrirRate, src->mType = ET_FP; } src->mSize = size; - src->mBits = (int)bits; + src->mBits = static_cast(bits); src->mSkip = channels; return 1; } @@ -1517,8 +1517,8 @@ static int ReadWaveData(FILE *fp, const SourceRefT *src, const ByteOrderT order, int pre, post, skip; uint i; - pre = (int)(src->mSize * src->mChannel); - post = (int)(src->mSize * (src->mSkip - src->mChannel - 1)); + pre = static_cast(src->mSize * src->mChannel); + post = static_cast(src->mSize * (src->mSkip - src->mChannel - 1)); skip = 0; for(i = 0;i < n;i++) { @@ -1557,7 +1557,7 @@ static int ReadWaveList(FILE *fp, const SourceRefT *src, const ByteOrderT order, fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath); return 0; } - fseek(fp, (long)(src->mOffset * block), SEEK_CUR); + fseek(fp, static_cast(src->mOffset * block), SEEK_CUR); if(!ReadWaveData(fp, src, order, n, &hrir[0])) return 0; return 1; @@ -1571,7 +1571,7 @@ static int ReadWaveList(FILE *fp, const SourceRefT *src, const ByteOrderT order, break; } if(chunkSize > 0) - fseek(fp, (long)chunkSize, SEEK_CUR); + fseek(fp, static_cast(chunkSize), SEEK_CUR); } listSize = chunkSize; block = src->mSize * src->mSkip; @@ -1589,7 +1589,7 @@ static int ReadWaveList(FILE *fp, const SourceRefT *src, const ByteOrderT order, count = chunkSize / block; if(count > skip) { - fseek(fp, (long)(skip * block), SEEK_CUR); + fseek(fp, static_cast(skip * block), SEEK_CUR); chunkSize -= skip * block; count -= skip; skip = 0; @@ -1629,7 +1629,7 @@ static int ReadWaveList(FILE *fp, const SourceRefT *src, const ByteOrderT order, } } if(chunkSize > 0) - fseek(fp, (long)chunkSize, SEEK_CUR); + fseek(fp, static_cast(chunkSize), SEEK_CUR); } if(offset < n) { @@ -1677,13 +1677,13 @@ static int LoadBinarySource(FILE *fp, const SourceRefT *src, const ByteOrderT or { uint i; - fseek(fp, (long)src->mOffset, SEEK_SET); + fseek(fp, static_cast(src->mOffset), SEEK_SET); for(i = 0;i < n;i++) { if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i])) return 0; if(src->mSkip > 0) - fseek(fp, (long)src->mSkip, SEEK_CUR); + fseek(fp, static_cast(src->mSkip), SEEK_CUR); } return 1; } @@ -1699,16 +1699,16 @@ static int LoadAsciiSource(FILE *fp, const SourceRefT *src, const uint n, double TrSetup(fp, nullptr, &tr); for(i = 0;i < src->mOffset;i++) { - if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy)) + if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, static_cast(src->mBits), &dummy)) return 0; } for(i = 0;i < n;i++) { - if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &hrir[i])) + if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, static_cast(src->mBits), &hrir[i])) return 0; for(j = 0;j < src->mSkip;j++) { - if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy)) + if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, static_cast(src->mBits), &dummy)) return 0; } } @@ -1806,25 +1806,25 @@ static int StoreMhr(const HrirDataT *hData, const char *filename) } if(!WriteAscii(MHR_FORMAT, fp, filename)) return 0; - if(!WriteBin4(BO_LITTLE, 4, (uint32_t)hData->mIrRate, fp, filename)) + if(!WriteBin4(BO_LITTLE, 4, static_cast(hData->mIrRate), fp, filename)) return 0; - if(!WriteBin4(BO_LITTLE, 1, (uint32_t)hData->mSampleType, fp, filename)) + if(!WriteBin4(BO_LITTLE, 1, static_cast(hData->mSampleType), fp, filename)) return 0; - if(!WriteBin4(BO_LITTLE, 1, (uint32_t)hData->mChannelType, fp, filename)) + if(!WriteBin4(BO_LITTLE, 1, static_cast(hData->mChannelType), fp, filename)) return 0; - if(!WriteBin4(BO_LITTLE, 1, (uint32_t)hData->mIrPoints, fp, filename)) + if(!WriteBin4(BO_LITTLE, 1, static_cast(hData->mIrPoints), fp, filename)) return 0; - if(!WriteBin4(BO_LITTLE, 1, (uint32_t)hData->mFdCount, fp, filename)) + if(!WriteBin4(BO_LITTLE, 1, static_cast(hData->mFdCount), fp, filename)) return 0; for(fi = 0;fi < hData->mFdCount;fi++) { - if(!WriteBin4(BO_LITTLE, 2, (uint32_t)(1000.0 * hData->mFds[fi].mDistance), fp, filename)) + if(!WriteBin4(BO_LITTLE, 2, static_cast(1000.0 * hData->mFds[fi].mDistance), fp, filename)) return 0; - if(!WriteBin4(BO_LITTLE, 1, (uint32_t)hData->mFds[fi].mEvCount, fp, filename)) + if(!WriteBin4(BO_LITTLE, 1, static_cast(hData->mFds[fi].mEvCount), fp, filename)) return 0; for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++) { - if(!WriteBin4(BO_LITTLE, 1, (uint32_t)hData->mFds[fi].mEvs[ei].mAzCount, fp, filename)) + if(!WriteBin4(BO_LITTLE, 1, static_cast(hData->mFds[fi].mEvs[ei].mAzCount), fp, filename)) return 0; } } @@ -1848,8 +1848,8 @@ static int StoreMhr(const HrirDataT *hData, const char *filename) TpdfDither(out+1, azd->mIrs[1], scale, n, channels, &dither_seed); for(i = 0;i < (channels * n);i++) { - int v = (int)Clamp(out[i], -scale-1.0, scale); - if(!WriteBin4(BO_LITTLE, bps, (uint32_t)v, fp, filename)) + int v = static_cast(Clamp(out[i], -scale-1.0, scale)); + if(!WriteBin4(BO_LITTLE, bps, static_cast(v), fp, filename)) return 0; } } @@ -1862,15 +1862,15 @@ static int StoreMhr(const HrirDataT *hData, const char *filename) for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++) { const HrirAzT &azd = hData->mFds[fi].mEvs[ei].mAzs[ai]; - int v = (int)std::min(std::round(hData->mIrRate * azd.mDelays[0]), MAX_HRTD); + int v = static_cast(std::min(std::round(hData->mIrRate * azd.mDelays[0]), MAX_HRTD)); - if(!WriteBin4(BO_LITTLE, 1, (uint32_t)v, fp, filename)) + if(!WriteBin4(BO_LITTLE, 1, static_cast(v), fp, filename)) return 0; if(hData->mChannelType == CT_STEREO) { - v = (int)std::min(std::round(hData->mIrRate * azd.mDelays[1]), MAX_HRTD); + v = static_cast(std::min(std::round(hData->mIrRate * azd.mDelays[1]), MAX_HRTD)); - if(!WriteBin4(BO_LITTLE, 1, (uint32_t)v, fp, filename)) + if(!WriteBin4(BO_LITTLE, 1, static_cast(v), fp, filename)) return 0; } } @@ -1900,7 +1900,7 @@ static double AverageHrirOnset(const uint rate, const uint n, const double *hrir if(std::abs(hrir[i]) >= mag) break; } - return Lerp(onset, (double)i / rate, f); + return Lerp(onset, static_cast(i) / rate, f); } // Calculate the magnitude response of an HRIR and average it with any @@ -2130,7 +2130,7 @@ static void ResampleHrirs(const uint rate, HrirDataT *hData) static void CalcAzIndices(const HrirDataT *hData, const uint fi, const uint ei, const double az, uint *a0, uint *a1, double *af) { double f = (2.0*M_PI + az) * hData->mFds[fi].mEvs[ei].mAzCount / (2.0*M_PI); - uint i = (uint)f % hData->mFds[fi].mEvs[ei].mAzCount; + uint i = static_cast(f) % hData->mFds[fi].mEvs[ei].mAzCount; f -= std::floor(f); *a0 = i; @@ -2161,7 +2161,7 @@ static void SynthesizeOnsets(HrirDataT *hData) hData->mFds[fi].mEvs[0].mAzs[0].mDelays[ti] = 1.32e-4 + (t / hData->mFds[fi].mEvs[oi].mAzCount); for(ei = 1;ei < hData->mFds[fi].mEvStart;ei++) { - of = (double)ei / hData->mFds[fi].mEvStart; + of = static_cast(ei) / hData->mFds[fi].mEvStart; for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++) { CalcAzIndices(hData, fi, oi, hData->mFds[fi].mEvs[ei].mAzs[ai].mAzimuth, &a0, &a1, &af); @@ -2209,7 +2209,7 @@ static void SynthesizeHrirs(HrirDataT *hData) } for(ei = 1;ei < hData->mFds[fi].mEvStart;ei++) { - of = (double)ei / hData->mFds[fi].mEvStart; + of = static_cast(ei) / hData->mFds[fi].mEvStart; b = (1.0 - of) * (3.5e-6 * hData->mIrRate); for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++) { @@ -2467,7 +2467,7 @@ static int ProcessMetrics(TokenReaderT *tr, const uint fftSize, const uint trunc return 0; if(!TrReadInt(tr, MIN_RATE, MAX_RATE, &intVal)) return 0; - hData->mIrRate = (uint)intVal; + hData->mIrRate = static_cast(intVal); hasRate = 1; } else if(strcasecmp(ident, "type") == 0) @@ -2504,7 +2504,7 @@ static int ProcessMetrics(TokenReaderT *tr, const uint fftSize, const uint trunc TrIndication(tr, &line, &col); if(!TrReadInt(tr, MIN_POINTS, MAX_POINTS, &intVal)) return 0; - points = (uint)intVal; + points = static_cast(intVal); if(fftSize > 0 && points > fftSize) { TrErrorAt(tr, line, col, "Value exceeds the overridden FFT size.\n"); @@ -2600,7 +2600,7 @@ static int ProcessMetrics(TokenReaderT *tr, const uint fftSize, const uint trunc { if(!TrReadInt(tr, MIN_AZ_COUNT, MAX_AZ_COUNT, &intVal)) return 0; - azCounts[(count * MAX_EV_COUNT) + evCounts[count]++] = (uint)intVal; + azCounts[(count * MAX_EV_COUNT) + evCounts[count]++] = static_cast(intVal); if(TrIsOperator(tr, ",")) { if(evCounts[count] >= MAX_EV_COUNT) @@ -2677,9 +2677,9 @@ static int ReadIndexTriplet(TokenReaderT *tr, const HrirDataT *hData, uint *fi, if(hData->mFdCount > 1) { - if(!TrReadInt(tr, 0, (int)hData->mFdCount - 1, &intVal)) + if(!TrReadInt(tr, 0, static_cast(hData->mFdCount) - 1, &intVal)) return 0; - *fi = (uint)intVal; + *fi = static_cast(intVal); if(!TrReadOperator(tr, ",")) return 0; } @@ -2687,14 +2687,14 @@ static int ReadIndexTriplet(TokenReaderT *tr, const HrirDataT *hData, uint *fi, { *fi = 0; } - if(!TrReadInt(tr, 0, (int)hData->mFds[*fi].mEvCount - 1, &intVal)) + if(!TrReadInt(tr, 0, static_cast(hData->mFds[*fi].mEvCount) - 1, &intVal)) return 0; - *ei = (uint)intVal; + *ei = static_cast(intVal); if(!TrReadOperator(tr, ",")) return 0; - if(!TrReadInt(tr, 0, (int)hData->mFds[*fi].mEvs[*ei].mAzCount - 1, &intVal)) + if(!TrReadInt(tr, 0, static_cast(hData->mFds[*fi].mEvs[*ei].mAzCount) - 1, &intVal)) return 0; - *ai = (uint)intVal; + *ai = static_cast(intVal); return 1; } @@ -2747,7 +2747,7 @@ static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src) src->mType = ET_NONE; src->mSize = 0; src->mBits = 0; - src->mChannel = (uint)intVal; + src->mChannel = static_cast(intVal); src->mSkip = 0; } else @@ -2769,16 +2769,16 @@ static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src) { if(!TrReadInt(tr, MIN_BIN_SIZE, MAX_BIN_SIZE, &intVal)) return 0; - src->mSize = (uint)intVal; + src->mSize = static_cast(intVal); if(!TrIsOperator(tr, ",")) - src->mBits = (int)(8*src->mSize); + src->mBits = static_cast(8*src->mSize); else { TrReadOperator(tr, ","); TrIndication(tr, &line, &col); if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal)) return 0; - if(std::abs(intVal) < MIN_BIN_BITS || (uint)std::abs(intVal) > (8*src->mSize)) + if(std::abs(intVal) < MIN_BIN_BITS || static_cast(std::abs(intVal)) > (8*src->mSize)) { TrErrorAt(tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8*src->mSize); return 0; @@ -2796,7 +2796,7 @@ static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src) TrErrorAt(tr, line, col, "Expected a value of 4 or 8.\n"); return 0; } - src->mSize = (uint)intVal; + src->mSize = static_cast(intVal); src->mBits = 0; } } @@ -2822,7 +2822,7 @@ static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src) TrReadOperator(tr, ";"); if(!TrReadInt(tr, 0, 0x7FFFFFFF, &intVal)) return 0; - src->mSkip = (uint)intVal; + src->mSkip = static_cast(intVal); } } if(!TrReadOperator(tr, ")")) @@ -2832,7 +2832,7 @@ static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src) TrReadOperator(tr, "@"); if(!TrReadInt(tr, 0, 0x7FFFFFFF, &intVal)) return 0; - src->mOffset = (uint)intVal; + src->mOffset = static_cast(intVal); } else src->mOffset = 0; @@ -2911,7 +2911,7 @@ static int ProcessSources(const HeadModelT model, TokenReaderT *tr, HrirDataT *h if(!TrReadIdent(tr, MAX_IDENT_LEN, ident)) return 0; ti = MatchTargetEar(ident); - if((int)ti < 0) + if(static_cast(ti) < 0) { TrErrorAt(tr, line, col, "Expected a target ear.\n"); return 0; -- cgit v1.2.3 From d7eee032725ed40f42387d25b2caaadce0a54004 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 8 Jan 2019 19:08:03 -0800 Subject: Replace a couple more C-style casts --- OpenAL32/Include/alMain.h | 2 +- examples/alffplay.cpp | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) (limited to 'examples') diff --git a/OpenAL32/Include/alMain.h b/OpenAL32/Include/alMain.h index f0771386..bea48296 100644 --- a/OpenAL32/Include/alMain.h +++ b/OpenAL32/Include/alMain.h @@ -292,7 +292,7 @@ inline int float2int(float f) noexcept #else - return (ALint)f; + return static_cast(f); #endif } diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 11ff126d..0375aecc 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -596,9 +596,8 @@ int AudioState::decodeFrame() mSamplesMax = mDecodedFrame->nb_samples; } /* Return the amount of sample frames converted */ - int data_size = swr_convert(mSwresCtx.get(), &mSamples, mDecodedFrame->nb_samples, - (const uint8_t**)mDecodedFrame->data, mDecodedFrame->nb_samples - ); + int data_size{swr_convert(mSwresCtx.get(), &mSamples, mDecodedFrame->nb_samples, + const_cast(mDecodedFrame->data), mDecodedFrame->nb_samples)}; av_frame_unref(mDecodedFrame.get()); return data_size; -- cgit v1.2.3 From e55f9b42e9f1f51f1d4af4537d10dbf63c55d4e5 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 27 Jan 2019 14:53:46 -0800 Subject: Partially handle ambisonics in alffplay This is currently really only applicable to Opus-encoded files. It assumes AmbiX (SN3D normalization, ACN ordering) and only comes into play when the channel layout is blank. FFmpeg/libavcodec doesn't have a way to detect B-Format input or what normalization and ordering it uses. Note in particular .amb files do not play correctly (libavcodec seems to apply a default channel layout for 4-channel wav-type files, regardless of its channel mask value). --- examples/alffplay.cpp | 126 +++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 98 insertions(+), 28 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 0375aecc..28b968e2 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -85,6 +85,8 @@ typedef void (AL_APIENTRY*LPALGETPOINTERVSOFT)(ALenum pname, void **values); namespace { +inline constexpr int64_t operator "" _i64(unsigned long long int n) noexcept { return static_cast(n); } + #ifndef M_PI #define M_PI (3.14159265358979323846) #endif @@ -146,7 +148,7 @@ enum class SyncMaster { inline microseconds get_avtime() -{ return microseconds(av_gettime()); } +{ return microseconds{av_gettime()}; } /* Define unique_ptrs to auto-cleanup associated ffmpeg objects. */ struct AVIOContextDeleter { @@ -286,7 +288,7 @@ struct AudioState { nanoseconds getClockNoLock(); nanoseconds getClock() { - std::lock_guard lock(mSrcMutex); + std::lock_guard lock{mSrcMutex}; return getClockNoLock(); } @@ -771,13 +773,15 @@ int AudioState::handler() /* Find a suitable format for OpenAL. */ mDstChanLayout = 0; - if(mCodecCtx->sample_fmt == AV_SAMPLE_FMT_U8 || mCodecCtx->sample_fmt == AV_SAMPLE_FMT_U8P) + mFormat = AL_NONE; + if((mCodecCtx->sample_fmt == AV_SAMPLE_FMT_FLT || mCodecCtx->sample_fmt == AV_SAMPLE_FMT_FLTP) && + alIsExtensionPresent("AL_EXT_FLOAT32")) { - mDstSampleFmt = AV_SAMPLE_FMT_U8; - mFrameSize = 1; + mDstSampleFmt = AV_SAMPLE_FMT_FLT; + mFrameSize = 4; if(mCodecCtx->channel_layout == AV_CH_LAYOUT_7POINT1 && alIsExtensionPresent("AL_EXT_MCFORMATS") && - (fmt=alGetEnumValue("AL_FORMAT_71CHN8")) != AL_NONE && fmt != -1) + (fmt=alGetEnumValue("AL_FORMAT_71CHN32")) != AL_NONE && fmt != -1) { mDstChanLayout = mCodecCtx->channel_layout; mFrameSize *= 8; @@ -786,7 +790,7 @@ int AudioState::handler() if((mCodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1 || mCodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1_BACK) && alIsExtensionPresent("AL_EXT_MCFORMATS") && - (fmt=alGetEnumValue("AL_FORMAT_51CHN8")) != AL_NONE && fmt != -1) + (fmt=alGetEnumValue("AL_FORMAT_51CHN32")) != AL_NONE && fmt != -1) { mDstChanLayout = mCodecCtx->channel_layout; mFrameSize *= 6; @@ -796,23 +800,42 @@ int AudioState::handler() { mDstChanLayout = mCodecCtx->channel_layout; mFrameSize *= 1; - mFormat = AL_FORMAT_MONO8; + mFormat = AL_FORMAT_MONO_FLOAT32; + } + /* Assume 3D B-Format (ambisonics) if the channel layout is blank and + * there's 4 or more channels. FFmpeg/libavcodec otherwise seems to + * have no way to specify if the source is actually B-Format (let alone + * if it's 2D or 3D). + */ + if(mCodecCtx->channel_layout == 0 && mCodecCtx->channels >= 4 && + alIsExtensionPresent("AL_EXT_BFORMAT") && + (fmt=alGetEnumValue("AL_FORMAT_BFORMAT3D_FLOAT32")) != AL_NONE && fmt != -1) + { + int order{static_cast(std::sqrt(mCodecCtx->channels)) - 1}; + if((order+1)*(order+1) == mCodecCtx->channels || + (order+1)*(order+1) + 2 == mCodecCtx->channels) + { + /* OpenAL only supports first-order with AL_EXT_BFORMAT, which + * is 4 channels for 3D buffers. + */ + mFrameSize *= 4; + mFormat = fmt; + } } - if(!mDstChanLayout) + if(!mFormat) { mDstChanLayout = AV_CH_LAYOUT_STEREO; mFrameSize *= 2; - mFormat = AL_FORMAT_STEREO8; + mFormat = AL_FORMAT_STEREO_FLOAT32; } } - if((mCodecCtx->sample_fmt == AV_SAMPLE_FMT_FLT || mCodecCtx->sample_fmt == AV_SAMPLE_FMT_FLTP) && - alIsExtensionPresent("AL_EXT_FLOAT32")) + if(mCodecCtx->sample_fmt == AV_SAMPLE_FMT_U8 || mCodecCtx->sample_fmt == AV_SAMPLE_FMT_U8P) { - mDstSampleFmt = AV_SAMPLE_FMT_FLT; - mFrameSize = 4; + mDstSampleFmt = AV_SAMPLE_FMT_U8; + mFrameSize = 1; if(mCodecCtx->channel_layout == AV_CH_LAYOUT_7POINT1 && alIsExtensionPresent("AL_EXT_MCFORMATS") && - (fmt=alGetEnumValue("AL_FORMAT_71CHN32")) != AL_NONE && fmt != -1) + (fmt=alGetEnumValue("AL_FORMAT_71CHN8")) != AL_NONE && fmt != -1) { mDstChanLayout = mCodecCtx->channel_layout; mFrameSize *= 8; @@ -821,7 +844,7 @@ int AudioState::handler() if((mCodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1 || mCodecCtx->channel_layout == AV_CH_LAYOUT_5POINT1_BACK) && alIsExtensionPresent("AL_EXT_MCFORMATS") && - (fmt=alGetEnumValue("AL_FORMAT_51CHN32")) != AL_NONE && fmt != -1) + (fmt=alGetEnumValue("AL_FORMAT_51CHN8")) != AL_NONE && fmt != -1) { mDstChanLayout = mCodecCtx->channel_layout; mFrameSize *= 6; @@ -831,16 +854,28 @@ int AudioState::handler() { mDstChanLayout = mCodecCtx->channel_layout; mFrameSize *= 1; - mFormat = AL_FORMAT_MONO_FLOAT32; + mFormat = AL_FORMAT_MONO8; + } + if(mCodecCtx->channel_layout == 0 && mCodecCtx->channels >= 4 && + alIsExtensionPresent("AL_EXT_BFORMAT") && + (fmt=alGetEnumValue("AL_FORMAT_BFORMAT3D8")) != AL_NONE && fmt != -1) + { + int order{static_cast(std::sqrt(mCodecCtx->channels)) - 1}; + if((order+1)*(order+1) == mCodecCtx->channels || + (order+1)*(order+1) + 2 == mCodecCtx->channels) + { + mFrameSize *= 4; + mFormat = fmt; + } } - if(!mDstChanLayout) + if(!mFormat) { mDstChanLayout = AV_CH_LAYOUT_STEREO; mFrameSize *= 2; - mFormat = AL_FORMAT_STEREO_FLOAT32; + mFormat = AL_FORMAT_STEREO8; } } - if(!mDstChanLayout) + if(!mFormat) { mDstSampleFmt = AV_SAMPLE_FMT_S16; mFrameSize = 2; @@ -867,7 +902,19 @@ int AudioState::handler() mFrameSize *= 1; mFormat = AL_FORMAT_MONO16; } - if(!mDstChanLayout) + if(mCodecCtx->channel_layout == 0 && mCodecCtx->channels >= 4 && + alIsExtensionPresent("AL_EXT_BFORMAT") && + (fmt=alGetEnumValue("AL_FORMAT_BFORMAT3D16")) != AL_NONE && fmt != -1) + { + int order{static_cast(std::sqrt(mCodecCtx->channels)) - 1}; + if((order+1)*(order+1) == mCodecCtx->channels || + (order+1)*(order+1) + 2 == mCodecCtx->channels) + { + mFrameSize *= 4; + mFormat = fmt; + } + } + if(!mFormat) { mDstChanLayout = AV_CH_LAYOUT_STEREO; mFrameSize *= 2; @@ -890,13 +937,36 @@ int AudioState::handler() goto finish; } - mSwresCtx.reset(swr_alloc_set_opts(nullptr, - mDstChanLayout, mDstSampleFmt, mCodecCtx->sample_rate, - mCodecCtx->channel_layout ? mCodecCtx->channel_layout : - static_cast(av_get_default_channel_layout(mCodecCtx->channels)), - mCodecCtx->sample_fmt, mCodecCtx->sample_rate, - 0, nullptr - )); + if(!mDstChanLayout) + { + /* OpenAL only supports first-order ambisonics with AL_EXT_BFORMAT, so + * we have to drop any extra channels. It also only supports FuMa + * channel ordering and normalization, so a custom matrix is needed to + * scale and reorder the source from AmbiX. + */ + mSwresCtx.reset(swr_alloc_set_opts(nullptr, + (1_i64<<4)-1, mDstSampleFmt, mCodecCtx->sample_rate, + (1_i64<channels)-1, mCodecCtx->sample_fmt, mCodecCtx->sample_rate, + 0, nullptr)); + + /* Note that ffmpeg/libavcodec has no method to check the ambisonic + * channel order and normalization, so we can only assume AmbiX as the + * defacto-standard. This is not true for .amb files, which use FuMa. + */ + std::vector mtx(64*64, 0.0); + mtx[0 + 0*64] = std::sqrt(0.5); + mtx[3 + 1*64] = 1.0; + mtx[1 + 2*64] = 1.0; + mtx[2 + 3*64] = 1.0; + swr_set_matrix(mSwresCtx.get(), mtx.data(), 64); + } + else + mSwresCtx.reset(swr_alloc_set_opts(nullptr, + mDstChanLayout, mDstSampleFmt, mCodecCtx->sample_rate, + mCodecCtx->channel_layout ? mCodecCtx->channel_layout : + static_cast(av_get_default_channel_layout(mCodecCtx->channels)), + mCodecCtx->sample_fmt, mCodecCtx->sample_rate, + 0, nullptr)); if(!mSwresCtx || swr_init(mSwresCtx.get()) != 0) { std::cerr<< "Failed to initialize audio converter" < Date: Thu, 31 Jan 2019 00:11:50 -0800 Subject: Fixed alffplay underrun recovery timing --- examples/alffplay.cpp | 59 +++++++++++++++++++++++---------------------------- 1 file changed, 26 insertions(+), 33 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 28b968e2..c51c5119 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -91,16 +91,17 @@ inline constexpr int64_t operator "" _i64(unsigned long long int n) noexcept { r #define M_PI (3.14159265358979323846) #endif +using fixed32 = std::chrono::duration>; using nanoseconds = std::chrono::nanoseconds; using microseconds = std::chrono::microseconds; using milliseconds = std::chrono::milliseconds; using seconds = std::chrono::seconds; using seconds_d64 = std::chrono::duration; -const std::string AppName("alffplay"); +const std::string AppName{"alffplay"}; -bool EnableDirectOut = false; -bool EnableWideStereo = false; +bool EnableDirectOut{false}; +bool EnableWideStereo{false}; LPALGETSOURCEI64VSOFT alGetSourcei64vSOFT; LPALCGETINTEGER64VSOFT alcGetInteger64vSOFT; @@ -115,20 +116,20 @@ LPALEVENTCONTROLSOFT alEventControlSOFT; LPALEVENTCALLBACKSOFT alEventCallbackSOFT; #endif -const seconds AVNoSyncThreshold(10); +const seconds AVNoSyncThreshold{10}; const milliseconds VideoSyncThreshold(10); #define VIDEO_PICTURE_QUEUE_SIZE 16 -const seconds_d64 AudioSyncThreshold(0.03); -const milliseconds AudioSampleCorrectionMax(50); +const seconds_d64 AudioSyncThreshold{0.03}; +const milliseconds AudioSampleCorrectionMax{50}; /* Averaging filter coefficient for audio sync. */ #define AUDIO_DIFF_AVG_NB 20 -const double AudioAvgFilterCoeff = std::pow(0.01, 1.0/AUDIO_DIFF_AVG_NB); +const double AudioAvgFilterCoeff{std::pow(0.01, 1.0/AUDIO_DIFF_AVG_NB)}; /* Per-buffer size, in time */ -const milliseconds AudioBufferTime(20); +const milliseconds AudioBufferTime{20}; /* Buffer total size, in time (should be divisible by the buffer time) */ -const milliseconds AudioBufferTotalTime(800); +const milliseconds AudioBufferTotalTime{800}; #define MAX_QUEUE_SIZE (15 * 1024 * 1024) /* Bytes of compressed data to keep queued */ @@ -419,15 +420,15 @@ nanoseconds AudioState::getClockNoLock() // Get the current device clock time and latency. auto device = alcGetContextsDevice(alcGetCurrentContext()); - ALCint64SOFT devtimes[2] = {0,0}; + ALCint64SOFT devtimes[2]{0,0}; alcGetInteger64vSOFT(device, ALC_DEVICE_CLOCK_LATENCY_SOFT, 2, devtimes); - auto latency = nanoseconds(devtimes[1]); - auto device_time = nanoseconds(devtimes[0]); + auto latency = nanoseconds{devtimes[1]}; + auto device_time = nanoseconds{devtimes[0]}; // The clock is simply the current device time relative to the recorded // start time. We can also subtract the latency to get more a accurate // position of where the audio device actually is in the output stream. - return device_time - mDeviceStartTime - latency; + std::max(device_time - mDeviceStartTime - latency, nanoseconds::zero()); } /* The source-based clock is based on 4 components: @@ -445,12 +446,10 @@ nanoseconds AudioState::getClockNoLock() * sample at OpenAL's current position, and subtracting the source latency * from that gives the timestamp of the sample currently at the DAC. */ - nanoseconds pts = mCurrentPts; + nanoseconds pts{mCurrentPts}; if(mSource) { ALint64SOFT offset[2]; - ALint queued; - ALint status; /* NOTE: The source state must be checked last, in case an underrun * occurs and the source stops between retrieving the offset+latency @@ -461,9 +460,10 @@ nanoseconds AudioState::getClockNoLock() { ALint ioffset; alGetSourcei(mSource, AL_SAMPLE_OFFSET, &ioffset); - offset[0] = static_cast(ioffset) << 32; + offset[0] = ALint64SOFT{ioffset} << 32; offset[1] = 0; } + ALint queued, status; alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); alGetSourcei(mSource, AL_SOURCE_STATE, &status); @@ -473,16 +473,13 @@ nanoseconds AudioState::getClockNoLock() * when it starts recovery. */ if(status != AL_STOPPED) { - using fixed32 = std::chrono::duration>; - pts -= AudioBufferTime*queued; pts += std::chrono::duration_cast( - fixed32(offset[0] / mCodecCtx->sample_rate) - ); + fixed32{offset[0] / mCodecCtx->sample_rate}); } /* Don't offset by the latency if the source isn't playing. */ if(status == AL_PLAYING) - pts -= nanoseconds(offset[1]); + pts -= nanoseconds{offset[1]}; } return std::max(pts, nanoseconds::zero()); @@ -503,16 +500,14 @@ void AudioState::startPlayback() alSourcePlay(mSource); if(alcGetInteger64vSOFT) { - using fixed32 = std::chrono::duration>; - // Subtract the total buffer queue time from the current pts to get the // pts of the start of the queue. - nanoseconds startpts = mCurrentPts - AudioBufferTotalTime; - int64_t srctimes[2]={0,0}; + nanoseconds startpts{mCurrentPts - AudioBufferTotalTime}; + int64_t srctimes[2]{0,0}; alGetSourcei64vSOFT(mSource, AL_SAMPLE_OFFSET_CLOCK_SOFT, srctimes); - auto device_time = nanoseconds(srctimes[1]); - auto src_offset = std::chrono::duration_cast(fixed32(srctimes[0])) / - mCodecCtx->sample_rate; + auto device_time = nanoseconds{srctimes[1]}; + auto src_offset = std::chrono::duration_cast(fixed32{srctimes[0]}) / + mCodecCtx->sample_rate; // The mixer may have ticked and incremented the device time and sample // offset, so subtract the source offset from the device time to get @@ -1068,10 +1063,8 @@ int AudioState::handler() */ int64_t devtime{}; alcGetInteger64vSOFT(alcGetContextsDevice(alcGetCurrentContext()), - ALC_DEVICE_CLOCK_SOFT, 1, &devtime); - auto device_time = nanoseconds{devtime}; - - mDeviceStartTime = device_time - mCurrentPts + AudioBufferTotalTime; + ALC_DEVICE_CLOCK_SOFT, 1, &devtime); + mDeviceStartTime = nanoseconds{devtime} - mCurrentPts; } continue; } -- cgit v1.2.3 From 8a34bd59b009c2deee120aa2685965f7bed7fab8 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Mon, 25 Feb 2019 02:03:43 -0800 Subject: Unlock the audio decoder mutex before disabling events in alffplay The callback may be waiting on the mutex, but disabling the callback needs any current invocation to finish first. --- examples/alffplay.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index c51c5119..31099c75 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -748,7 +748,7 @@ void AL_APIENTRY AudioState::EventCallback(ALenum eventType, ALuint object, ALui int AudioState::handler() { - std::unique_lock lock(mSrcMutex); + std::unique_lock srclock(mSrcMutex); milliseconds sleep_time = AudioBufferTime / 3; ALenum fmt; @@ -1074,7 +1074,7 @@ int AudioState::handler() mMovie.mPlaying.load(std::memory_order_relaxed)) startPlayback(); - mSrcCond.wait_for(lock, sleep_time); + mSrcCond.wait_for(srclock, sleep_time); } alSourceRewind(mSource); @@ -1082,6 +1082,7 @@ int AudioState::handler() finish: av_freep(&samples); + srclock.unlock(); #ifdef AL_SOFT_events if(alEventControlSOFT) -- cgit v1.2.3 From 0aa0f24dd749fecadade906ce58f56b6726c0f20 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Fri, 1 Mar 2019 22:46:56 -0800 Subject: Use a proper flag to indicate audio is prepared in alffplay --- examples/alffplay.cpp | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 31099c75..6298cb43 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -264,6 +264,7 @@ struct AudioState { std::mutex mSrcMutex; std::condition_variable mSrcCond; std::atomic_flag mConnected; + std::atomic mPrepared{false}; ALuint mSource{0}; std::vector mBuffers; ALsizei mBufferIdx{0}; @@ -293,7 +294,7 @@ struct AudioState { return getClockNoLock(); } - bool isBufferFilled(); + bool isBufferFilled() const { return mPrepared.load(); } void startPlayback(); int getSync(); @@ -485,16 +486,6 @@ nanoseconds AudioState::getClockNoLock() return std::max(pts, nanoseconds::zero()); } -bool AudioState::isBufferFilled() -{ - /* All of OpenAL's buffer queueing happens under the mSrcMutex lock, as - * does the source gen. So when we're able to grab the lock and the source - * is valid, the queue must be full. - */ - std::lock_guard lock(mSrcMutex); - return mSource != 0; -} - void AudioState::startPlayback() { alSourcePlay(mSource); @@ -1070,9 +1061,13 @@ int AudioState::handler() } /* (re)start the source if needed, and wait for a buffer to finish */ - if(state != AL_PLAYING && state != AL_PAUSED && - mMovie.mPlaying.load(std::memory_order_relaxed)) - startPlayback(); + if(state != AL_PLAYING && state != AL_PAUSED) + { + if(mMovie.mPlaying.load(std::memory_order_relaxed)) + startPlayback(); + else + mPrepared.store(true); + } mSrcCond.wait_for(srclock, sleep_time); } -- cgit v1.2.3 From e9bf7e4b15460139c0474a97b9619c9e9fb3177f Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 30 Jun 2019 18:17:23 -0700 Subject: Add an option to disable video in alffplay --- examples/alffplay.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 6298cb43..8016fd00 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -102,6 +102,7 @@ const std::string AppName{"alffplay"}; bool EnableDirectOut{false}; bool EnableWideStereo{false}; +bool DisableVideo{false}; LPALGETSOURCEI64VSOFT alGetSourcei64vSOFT; LPALCGETINTEGER64VSOFT alcGetInteger64vSOFT; @@ -1572,7 +1573,7 @@ int MovieState::parse_handler() for(unsigned int i = 0;i < mFormatCtx->nb_streams;i++) { auto codecpar = mFormatCtx->streams[i]->codecpar; - if(codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_index < 0) + if(codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !DisableVideo && video_index < 0) video_index = streamComponentOpen(i); else if(codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_index < 0) audio_index = streamComponentOpen(i); @@ -1859,6 +1860,8 @@ int main(int argc, char *argv[]) EnableWideStereo = true; } } + else if(strcmp(argv[fileidx], "-novideo") == 0) + DisableVideo = false; else break; } -- cgit v1.2.3 From 0aeaf061736e28a803fb46d25860a07b3d45bb05 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 30 Jun 2019 20:43:19 -0700 Subject: Properly set DisableVideo to true --- examples/alffplay.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 8016fd00..f4d50d52 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -1861,7 +1861,7 @@ int main(int argc, char *argv[]) } } else if(strcmp(argv[fileidx], "-novideo") == 0) - DisableVideo = false; + DisableVideo = true; else break; } -- cgit v1.2.3 From 90b1bc7b7a009113932b15208e3bdfbed2b3b65b Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 30 Jun 2019 23:32:09 -0700 Subject: Make sure a variable is set before use --- examples/alrecord.c | 1 + 1 file changed, 1 insertion(+) (limited to 'examples') diff --git a/examples/alrecord.c b/examples/alrecord.c index 30f5f792..c4984f99 100644 --- a/examples/alrecord.c +++ b/examples/alrecord.c @@ -317,6 +317,7 @@ int main(int argc, char **argv) recorder.mRecTime, (recorder.mRecTime != 1.0f) ? "s" : "" ); + err = ALC_NO_ERROR; alcCaptureStart(recorder.mDevice); while((double)recorder.mDataSize/(double)recorder.mSampleRate < recorder.mRecTime && (err=alcGetError(recorder.mDevice)) == ALC_NO_ERROR && !ferror(recorder.mFile)) -- cgit v1.2.3 From 2783b4c04b92d949178e9acd4d3407b2315efe16 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 6 Jul 2019 22:18:52 -0700 Subject: Somewhat simplify alffplay playback timing --- examples/alffplay.cpp | 78 +++++++++++++++++++-------------------------------- 1 file changed, 29 insertions(+), 49 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index f4d50d52..21b3f9c8 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -265,7 +265,6 @@ struct AudioState { std::mutex mSrcMutex; std::condition_variable mSrcCond; std::atomic_flag mConnected; - std::atomic mPrepared{false}; ALuint mSource{0}; std::vector mBuffers; ALsizei mBufferIdx{0}; @@ -295,7 +294,6 @@ struct AudioState { return getClockNoLock(); } - bool isBufferFilled() const { return mPrepared.load(); } void startPlayback(); int getSync(); @@ -350,7 +348,6 @@ struct VideoState { VideoState(MovieState &movie) : mMovie(movie) { } nanoseconds getClock(); - bool isBufferFilled(); static Uint32 SDLCALL sdl_refresh_timer_cb(Uint32 interval, void *opaque); void schedRefresh(milliseconds delay); @@ -368,7 +365,6 @@ struct MovieState { SyncMaster mAVSyncType{SyncMaster::Default}; microseconds mClockBase{0}; - std::atomic mPlaying{false}; std::mutex mSendMtx; std::condition_variable mSendCond; @@ -430,7 +426,7 @@ nanoseconds AudioState::getClockNoLock() // The clock is simply the current device time relative to the recorded // start time. We can also subtract the latency to get more a accurate // position of where the audio device actually is in the output stream. - std::max(device_time - mDeviceStartTime - latency, nanoseconds::zero()); + return device_time - mDeviceStartTime - latency; } /* The source-based clock is based on 4 components: @@ -532,8 +528,7 @@ int AudioState::getSync() return 0; /* Constrain the per-update difference to avoid exceedingly large skips */ - diff = std::min(std::max(diff, -AudioSampleCorrectionMax), - AudioSampleCorrectionMax); + diff = std::min(diff, AudioSampleCorrectionMax); return static_cast(std::chrono::duration_cast(diff*mCodecCtx->sample_rate).count()); } @@ -991,6 +986,13 @@ int AudioState::handler() #endif samples = av_malloc(buffer_len); + { + int64_t devtime{}; + alcGetInteger64vSOFT(alcGetContextsDevice(alcGetCurrentContext()), ALC_DEVICE_CLOCK_SOFT, + 1, &devtime); + mDeviceStartTime = nanoseconds{devtime} - mCurrentPts; + } + while(alGetError() == AL_NO_ERROR && !mMovie.mQuit.load(std::memory_order_relaxed) && mConnected.test_and_set(std::memory_order_relaxed)) { @@ -1000,9 +1002,9 @@ int AudioState::handler() while(processed > 0) { std::array bids; - alSourceUnqueueBuffers(mSource, std::min(bids.size(), processed), - bids.data()); - processed -= std::min(bids.size(), processed); + const ALsizei todq{std::min(bids.size(), processed)}; + alSourceUnqueueBuffers(mSource, todq, bids.data()); + processed -= todq; } /* Refill the buffer queue. */ @@ -1011,19 +1013,23 @@ int AudioState::handler() while(static_cast(queued) < mBuffers.size()) { ALuint bufid = mBuffers[mBufferIdx]; - - uint8_t *ptr = reinterpret_cast(samples + uint8_t *ptr = static_cast(samples); #ifdef AL_SOFT_map_buffer - ? samples : alMapBufferSOFT(bufid, 0, buffer_len, AL_MAP_WRITE_BIT_SOFT) + bool mapped{false}; + if(!ptr) + { + ptr = static_cast(alMapBufferSOFT(bufid, 0, buffer_len, + AL_MAP_WRITE_BIT_SOFT)); + if(!ptr) break; + mapped = true; + } #endif - ); - if(!ptr) break; /* Read the next chunk of data, filling the buffer, and queue it on * the source */ bool got_audio = readAudio(ptr, buffer_len); #ifdef AL_SOFT_map_buffer - if(!samples) alUnmapBufferSOFT(bufid); + if(mapped) alUnmapBufferSOFT(bufid); #endif if(!got_audio) break; @@ -1063,12 +1069,7 @@ int AudioState::handler() /* (re)start the source if needed, and wait for a buffer to finish */ if(state != AL_PLAYING && state != AL_PAUSED) - { - if(mMovie.mPlaying.load(std::memory_order_relaxed)) - startPlayback(); - else - mPrepared.store(true); - } + startPlayback(); mSrcCond.wait_for(srclock, sleep_time); } @@ -1099,12 +1100,6 @@ nanoseconds VideoState::getClock() return mCurrentPts + delta; } -bool VideoState::isBufferFilled() -{ - std::unique_lock lock(mPictQMutex); - return mPictQSize >= mPictQ.size(); -} - Uint32 SDLCALL VideoState::sdl_refresh_timer_cb(Uint32 /*interval*/, void *opaque) { SDL_Event evt{}; @@ -1177,11 +1172,6 @@ void VideoState::refreshTimer(SDL_Window *screen, SDL_Renderer *renderer) schedRefresh(milliseconds(100)); return; } - if(!mMovie.mPlaying.load(std::memory_order_relaxed)) - { - schedRefresh(milliseconds(1)); - return; - } std::unique_lock lock(mPictQMutex); retry: @@ -1498,8 +1488,6 @@ void MovieState::setTitle(SDL_Window *window) nanoseconds MovieState::getClock() { - if(!mPlaying.load(std::memory_order_relaxed)) - return nanoseconds::zero(); return get_avtime() - mClockBase; } @@ -1569,6 +1557,11 @@ int MovieState::parse_handler() /* Dump information about file onto standard error */ av_dump_format(mFormatCtx.get(), 0, mFilename.c_str(), 0); + /* Set the base time 500ms ahead of the current av time. */ + mClockBase = get_avtime() + milliseconds{500}; + mVideo.mCurrentPtsTime = mClockBase; + mVideo.mFrameTimer = mVideo.mCurrentPtsTime; + /* Find the first video and audio streams */ for(unsigned int i = 0;i < mFormatCtx->nb_streams;i++) { @@ -1635,23 +1628,10 @@ int MovieState::parse_handler() if(queue_size == 0 || (queue_size < MAX_QUEUE_SIZE && !input_finished)) break; - if(!mPlaying.load(std::memory_order_relaxed)) - { - if((!mAudio.mCodecCtx || mAudio.isBufferFilled()) && - (!mVideo.mCodecCtx || mVideo.isBufferFilled())) - { - /* Set the base time 50ms ahead of the current av time. */ - mClockBase = get_avtime() + milliseconds(50); - mVideo.mCurrentPtsTime = mClockBase; - mVideo.mFrameTimer = mVideo.mCurrentPtsTime; - mAudio.startPlayback(); - mPlaying.store(std::memory_order_release); - } - } /* Nothing to send or get for now, wait a bit and try again. */ { std::unique_lock lock(mSendMtx); if(mSendDataGood.test_and_set(std::memory_order_relaxed)) - mSendCond.wait_for(lock, milliseconds(10)); + mSendCond.wait_for(lock, milliseconds{10}); } } while(!mQuit.load(std::memory_order_relaxed)); } -- cgit v1.2.3 From 3ffb6867a3bac856bacebf25dfbcf48b4482d50f Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Mon, 8 Jul 2019 13:18:10 -0700 Subject: Rework packet handling in alffplay Turns out avcodec_send_packet is what can invoke the decode for serialized codecs, so don't call that in the parse handler thread. The packet queue is used to get the compressed data from the parse handler to the audio/video threads. Additionally, don't serialize the video frame preparation with the decode thread. --- examples/alffplay.cpp | 398 +++++++++++++++++++++----------------------------- 1 file changed, 170 insertions(+), 228 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 21b3f9c8..f6bf6863 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -119,7 +119,7 @@ LPALEVENTCALLBACKSOFT alEventCallbackSOFT; const seconds AVNoSyncThreshold{10}; -const milliseconds VideoSyncThreshold(10); +const milliseconds VideoSyncThreshold{10}; #define VIDEO_PICTURE_QUEUE_SIZE 16 const seconds_d64 AudioSyncThreshold{0.03}; @@ -132,8 +132,6 @@ const milliseconds AudioBufferTime{20}; /* Buffer total size, in time (should be divisible by the buffer time) */ const milliseconds AudioBufferTotalTime{800}; -#define MAX_QUEUE_SIZE (15 * 1024 * 1024) /* Bytes of compressed data to keep queued */ - enum { FF_UPDATE_EVENT = SDL_USEREVENT, FF_REFRESH_EVENT, @@ -184,27 +182,58 @@ struct SwsContextDeleter { using SwsContextPtr = std::unique_ptr; +template class PacketQueue { + std::mutex mMutex; + std::condition_variable mCondVar; std::deque mPackets; size_t mTotalSize{0}; + bool mFinished{false}; public: - ~PacketQueue() { clear(); } + ~PacketQueue() + { + for(AVPacket &pkt : mPackets) + av_packet_unref(&pkt); + mPackets.clear(); + mTotalSize = 0; + } - bool empty() const noexcept { return mPackets.empty(); } - size_t totalSize() const noexcept { return mTotalSize; } + void setFinished() + { + { + std::lock_guard _{mMutex}; + mFinished = true; + } + mCondVar.notify_one(); + } - void put(const AVPacket *pkt) + AVPacket *getPacket(std::unique_lock &lock) { - mPackets.push_back(AVPacket{}); - if(av_packet_ref(&mPackets.back(), pkt) != 0) - mPackets.pop_back(); - else - mTotalSize += mPackets.back().size; + while(mPackets.empty() && !mFinished) + mCondVar.wait(lock); + return mPackets.empty() ? nullptr : &mPackets.front(); } - AVPacket *front() noexcept - { return &mPackets.front(); } + bool put(const AVPacket *pkt) + { + { + std::unique_lock lock{mMutex}; + if(mTotalSize >= SizeLimit) + return false; + + mPackets.push_back(AVPacket{}); + if(av_packet_ref(&mPackets.back(), pkt) != 0) + { + mPackets.pop_back(); + return true; + } + + mTotalSize += mPackets.back().size; + } + mCondVar.notify_one(); + return true; + } void pop() { @@ -214,13 +243,7 @@ public: mPackets.pop_front(); } - void clear() - { - for(AVPacket &pkt : mPackets) - av_packet_unref(&pkt); - mPackets.clear(); - mTotalSize = 0; - } + std::mutex &getMutex() noexcept { return mMutex; } }; @@ -232,8 +255,7 @@ struct AudioState { AVStream *mStream{nullptr}; AVCodecCtxPtr mCodecCtx; - std::mutex mQueueMtx; - std::condition_variable mQueueCond; + PacketQueue<2*1024*1024> mPackets; /* Used for clock difference average computation */ seconds_d64 mClockDiffAvg{0}; @@ -309,8 +331,7 @@ struct VideoState { AVStream *mStream{nullptr}; AVCodecCtxPtr mCodecCtx; - std::mutex mQueueMtx; - std::condition_variable mQueueCond; + PacketQueue<14*1024*1024> mPackets; nanoseconds mClock{0}; nanoseconds mFrameTimer{0}; @@ -320,14 +341,13 @@ struct VideoState { /* time (av_gettime) at which we updated mCurrentPts - used to have running video pts */ microseconds mCurrentPtsTime{0}; - /* Decompressed video frame, and swscale context for conversion */ - AVFramePtr mDecodedFrame; + /* Swscale context for format conversion */ SwsContextPtr mSwscaleCtx; struct Picture { SDL_Texture *mImage{nullptr}; int mWidth{0}, mHeight{0}; /* Logical image size (actual size may be larger) */ - std::atomic mUpdated{false}; + AVFramePtr mFrame{av_frame_alloc()}; nanoseconds mPts{0}; ~Picture() @@ -339,6 +359,7 @@ struct VideoState { }; std::array mPictQ; size_t mPictQSize{0}, mPictQRead{0}, mPictQWrite{0}; + size_t mPictQPrepSize{0}, mPictQPrep{0}; std::mutex mPictQMutex; std::condition_variable mPictQCond; bool mFirstUpdate{true}; @@ -354,7 +375,7 @@ struct VideoState { void display(SDL_Window *screen, SDL_Renderer *renderer); void refreshTimer(SDL_Window *screen, SDL_Renderer *renderer); void updatePicture(SDL_Window *screen, SDL_Renderer *renderer); - int queuePicture(nanoseconds pts); + bool queuePicture(nanoseconds pts, AVFrame *frame); int handler(); }; @@ -366,11 +387,6 @@ struct MovieState { microseconds mClockBase{0}; - std::mutex mSendMtx; - std::condition_variable mSendCond; - /* NOTE: false/clear = need data, true/set = no data needed */ - std::atomic_flag mSendDataGood; - std::atomic mQuit{false}; AudioState mAudio; @@ -536,22 +552,20 @@ int AudioState::decodeFrame() { while(!mMovie.mQuit.load(std::memory_order_relaxed)) { - std::unique_lock lock(mQueueMtx); - int ret = avcodec_receive_frame(mCodecCtx.get(), mDecodedFrame.get()); - if(ret == AVERROR(EAGAIN)) { - mMovie.mSendDataGood.clear(std::memory_order_relaxed); - std::unique_lock(mMovie.mSendMtx).unlock(); - mMovie.mSendCond.notify_one(); - do { - mQueueCond.wait(lock); - ret = avcodec_receive_frame(mCodecCtx.get(), mDecodedFrame.get()); - } while(ret == AVERROR(EAGAIN)); + std::unique_lock lock{mPackets.getMutex()}; + AVPacket *lastpkt{}; + while((lastpkt=mPackets.getPacket(lock)) != nullptr) + { + int ret{avcodec_send_packet(mCodecCtx.get(), lastpkt)}; + if(ret == AVERROR(EAGAIN)) break; + mPackets.pop(); + } + if(!lastpkt) + avcodec_send_packet(mCodecCtx.get(), nullptr); } - lock.unlock(); + int ret{avcodec_receive_frame(mCodecCtx.get(), mDecodedFrame.get())}; if(ret == AVERROR_EOF) break; - mMovie.mSendDataGood.clear(std::memory_order_relaxed); - mMovie.mSendCond.notify_one(); if(ret < 0) { std::cerr<< "Failed to decode frame: "<best_effort_timestamp != AV_NOPTS_VALUE) mCurrentPts = std::chrono::duration_cast( - seconds_d64(av_q2d(mStream->time_base)*mDecodedFrame->best_effort_timestamp) + seconds_d64{av_q2d(mStream->time_base)*mDecodedFrame->best_effort_timestamp} ); if(mDecodedFrame->nb_samples > mSamplesMax) @@ -639,7 +653,7 @@ bool AudioState::readAudio(uint8_t *samples, int length) // Adjust the device start time and current pts by the amount we're // skipping/duplicating, so that the clock remains correct for the // current stream position. - auto skip = nanoseconds(seconds(mSamplesPos)) / mCodecCtx->sample_rate; + auto skip = nanoseconds{seconds{mSamplesPos}} / mCodecCtx->sample_rate; mDeviceStartTime -= skip; mCurrentPts += skip; continue; @@ -692,7 +706,7 @@ void AL_APIENTRY AudioState::EventCallback(ALenum eventType, ALuint object, ALui ALsizei length, const ALchar *message, void *userParam) { - AudioState *self = reinterpret_cast(userParam); + AudioState *self = static_cast(userParam); if(eventType == AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT) { @@ -719,7 +733,7 @@ void AL_APIENTRY AudioState::EventCallback(ALenum eventType, ALuint object, ALui std::cout<< "\n" "Object ID: "<(length)}<<"\n----"<< std::endl; if(eventType == AL_EVENT_TYPE_DISCONNECTED_SOFT) @@ -727,7 +741,6 @@ void AL_APIENTRY AudioState::EventCallback(ALenum eventType, ALuint object, ALui { std::lock_guard lock(self->mSrcMutex); self->mConnected.clear(std::memory_order_release); } - std::unique_lock(self->mSrcMutex).unlock(); self->mSrcCond.notify_one(); } } @@ -903,7 +916,7 @@ int AudioState::handler() mFormat = AL_FORMAT_STEREO16; } } - void *samples = nullptr; + void *samples{nullptr}; ALsizei buffer_len = std::chrono::duration_cast>( mCodecCtx->sample_rate * AudioBufferTime).count() * mFrameSize; @@ -1012,29 +1025,26 @@ int AudioState::handler() alGetSourcei(mSource, AL_BUFFERS_QUEUED, &queued); while(static_cast(queued) < mBuffers.size()) { - ALuint bufid = mBuffers[mBufferIdx]; - uint8_t *ptr = static_cast(samples); + const ALuint bufid{mBuffers[mBufferIdx]}; + /* Read the next chunk of data, filling the buffer, and queue it on + * the source. + */ #ifdef AL_SOFT_map_buffer - bool mapped{false}; - if(!ptr) + if(!samples) { - ptr = static_cast(alMapBufferSOFT(bufid, 0, buffer_len, + auto ptr = static_cast(alMapBufferSOFT(bufid, 0, buffer_len, AL_MAP_WRITE_BIT_SOFT)); - if(!ptr) break; - mapped = true; + bool got_audio{readAudio(ptr, buffer_len)}; + alUnmapBufferSOFT(bufid); + if(!got_audio) break; } + else #endif - - /* Read the next chunk of data, filling the buffer, and queue it on - * the source */ - bool got_audio = readAudio(ptr, buffer_len); -#ifdef AL_SOFT_map_buffer - if(mapped) alUnmapBufferSOFT(bufid); -#endif - if(!got_audio) break; - - if(samples) + { + if(!readAudio(static_cast(samples), buffer_len)) + break; alBufferData(bufid, mFormat, samples, buffer_len, mCodecCtx->sample_rate); + } alSourceQueueBuffers(mSource, 1, &bufid); mBufferIdx = (mBufferIdx+1) % mBuffers.size(); @@ -1169,18 +1179,18 @@ void VideoState::refreshTimer(SDL_Window *screen, SDL_Renderer *renderer) mPictQCond.notify_all(); return; } - schedRefresh(milliseconds(100)); + schedRefresh(milliseconds{100}); return; } - std::unique_lock lock(mPictQMutex); + std::unique_lock lock{mPictQMutex}; retry: - if(mPictQSize == 0) + if(mPictQPrepSize == 0 || mMovie.mQuit.load(std::memory_order_relaxed)) { if(mEOS) mFinalUpdate = true; else - schedRefresh(milliseconds(1)); + schedRefresh(milliseconds{10}); lock.unlock(); mPictQCond.notify_all(); return; @@ -1192,7 +1202,7 @@ retry: /* Get delay using the frame pts and the pts from last frame. */ auto delay = vp->mPts - mFrameLastPts; - if(delay <= seconds::zero() || delay >= seconds(1)) + if(delay <= seconds::zero() || delay >= seconds{1}) { /* If incorrect delay, use previous one. */ delay = mFrameLastDelay; @@ -1200,6 +1210,7 @@ retry: /* Save for next frame. */ mFrameLastDelay = delay; mFrameLastPts = vp->mPts; + lock.unlock(); /* Update delay to sync to clock if not master source. */ if(mMovie.mAVSyncType != SyncMaster::Video) @@ -1224,8 +1235,10 @@ retry: if(!(actual_delay >= VideoSyncThreshold)) { /* We don't have time to handle this picture, just skip to the next one. */ + lock.lock(); mPictQRead = (mPictQRead+1)%mPictQ.size(); - mPictQSize--; + --mPictQSize; --mPictQPrepSize; + mPictQCond.notify_all(); goto retry; } schedRefresh(std::chrono::duration_cast(actual_delay)); @@ -1234,8 +1247,9 @@ retry: display(screen, renderer); /* Update queue for next picture. */ + lock.lock(); mPictQRead = (mPictQRead+1)%mPictQ.size(); - mPictQSize--; + --mPictQSize; --mPictQPrepSize; lock.unlock(); mPictQCond.notify_all(); } @@ -1245,7 +1259,10 @@ retry: */ void VideoState::updatePicture(SDL_Window *screen, SDL_Renderer *renderer) { - Picture *vp = &mPictQ[mPictQWrite]; + if(mMovie.mQuit.load(std::memory_order_relaxed)) + return; + + Picture *vp = &mPictQ[mPictQPrep]; bool fmt_updated = false; /* allocate or resize the buffer! */ @@ -1282,11 +1299,11 @@ void VideoState::updatePicture(SDL_Window *screen, SDL_Renderer *renderer) } } + AVFrame *frame{vp->mFrame.get()}; if(vp->mImage) { - AVFrame *frame = mDecodedFrame.get(); - void *pixels = nullptr; - int pitch = 0; + void *pixels{nullptr}; + int pitch{0}; if(mCodecCtx->pix_fmt == AV_PIX_FMT_YUV420P) SDL_UpdateYUVTexture(vp->mImage, nullptr, @@ -1299,10 +1316,10 @@ void VideoState::updatePicture(SDL_Window *screen, SDL_Renderer *renderer) else { // Convert the image into YUV format that SDL uses - int coded_w = mCodecCtx->coded_width; - int coded_h = mCodecCtx->coded_height; - int w = mCodecCtx->width; - int h = mCodecCtx->height; + int coded_w{mCodecCtx->coded_width}; + int coded_h{mCodecCtx->coded_height}; + int w{mCodecCtx->width}; + int h{mCodecCtx->height}; if(!mSwscaleCtx || fmt_updated) { mSwscaleCtx.reset(sws_getContext( @@ -1323,78 +1340,64 @@ void VideoState::updatePicture(SDL_Window *screen, SDL_Renderer *renderer) pict_linesize[1] = pitch / 2; pict_linesize[2] = pitch / 2; - sws_scale(mSwscaleCtx.get(), reinterpret_cast(frame->data), - frame->linesize, 0, h, pict_data, pict_linesize); + sws_scale(mSwscaleCtx.get(), reinterpret_cast(frame->data), frame->linesize, + 0, h, pict_data, pict_linesize); SDL_UnlockTexture(vp->mImage); } } + av_frame_unref(frame); - vp->mUpdated.store(true, std::memory_order_release); - std::unique_lock(mPictQMutex).unlock(); - mPictQCond.notify_one(); + mPictQPrep = (mPictQPrep+1)%mPictQ.size(); + ++mPictQPrepSize; } -int VideoState::queuePicture(nanoseconds pts) +bool VideoState::queuePicture(nanoseconds pts, AVFrame *frame) { /* Wait until we have space for a new pic */ - std::unique_lock lock(mPictQMutex); + std::unique_lock lock{mPictQMutex}; while(mPictQSize >= mPictQ.size() && !mMovie.mQuit.load(std::memory_order_relaxed)) mPictQCond.wait(lock); - lock.unlock(); if(mMovie.mQuit.load(std::memory_order_relaxed)) - return -1; + return false; - Picture *vp = &mPictQ[mPictQWrite]; + Picture *vp{&mPictQ[mPictQWrite]}; + av_frame_move_ref(vp->mFrame.get(), frame); + vp->mPts = pts; + + mPictQWrite = (mPictQWrite+1)%mPictQ.size(); + ++mPictQSize; + lock.unlock(); /* We have to create/update the picture in the main thread */ - vp->mUpdated.store(false, std::memory_order_relaxed); SDL_Event evt{}; evt.user.type = FF_UPDATE_EVENT; evt.user.data1 = this; SDL_PushEvent(&evt); - /* Wait until the picture is updated. */ - lock.lock(); - while(!vp->mUpdated.load(std::memory_order_relaxed)) - { - if(mMovie.mQuit.load(std::memory_order_relaxed)) - return -1; - mPictQCond.wait(lock); - } - if(mMovie.mQuit.load(std::memory_order_relaxed)) - return -1; - vp->mPts = pts; - - mPictQWrite = (mPictQWrite+1)%mPictQ.size(); - mPictQSize++; - lock.unlock(); - - return 0; + return true; } int VideoState::handler() { - mDecodedFrame.reset(av_frame_alloc()); + AVFramePtr decoded_frame{av_frame_alloc()}; while(!mMovie.mQuit.load(std::memory_order_relaxed)) { - std::unique_lock lock(mQueueMtx); - /* Decode video frame */ - int ret = avcodec_receive_frame(mCodecCtx.get(), mDecodedFrame.get()); - if(ret == AVERROR(EAGAIN)) { - mMovie.mSendDataGood.clear(std::memory_order_relaxed); - std::unique_lock(mMovie.mSendMtx).unlock(); - mMovie.mSendCond.notify_one(); - do { - mQueueCond.wait(lock); - ret = avcodec_receive_frame(mCodecCtx.get(), mDecodedFrame.get()); - } while(ret == AVERROR(EAGAIN)); + std::unique_lock lock{mPackets.getMutex()}; + AVPacket *lastpkt{}; + while((lastpkt=mPackets.getPacket(lock)) != nullptr) + { + int ret{avcodec_send_packet(mCodecCtx.get(), lastpkt)}; + if(ret == AVERROR(EAGAIN)) break; + mPackets.pop(); + } + if(!lastpkt) + avcodec_send_packet(mCodecCtx.get(), nullptr); } - lock.unlock(); + /* Decode video frame */ + int ret = avcodec_receive_frame(mCodecCtx.get(), decoded_frame.get()); if(ret == AVERROR_EOF) break; - mMovie.mSendDataGood.clear(std::memory_order_relaxed); - mMovie.mSendCond.notify_one(); if(ret < 0) { std::cerr<< "Failed to decode frame: "<best_effort_timestamp != AV_NOPTS_VALUE) + if(decoded_frame->best_effort_timestamp != AV_NOPTS_VALUE) mClock = std::chrono::duration_cast( - seconds_d64(av_q2d(mStream->time_base)*mDecodedFrame->best_effort_timestamp) - ); - pts = mClock; + seconds_d64{av_q2d(mStream->time_base)*decoded_frame->best_effort_timestamp}); + nanoseconds pts{mClock}; /* Update the video clock to the next expected PTS. */ auto frame_delay = av_q2d(mCodecCtx->time_base); - frame_delay += mDecodedFrame->repeat_pict * (frame_delay * 0.5); - mClock += std::chrono::duration_cast(seconds_d64(frame_delay)); + frame_delay += decoded_frame->repeat_pict * (frame_delay * 0.5); + mClock += std::chrono::duration_cast(seconds_d64{frame_delay}); - if(queuePicture(pts) < 0) + if(!queuePicture(pts, decoded_frame.get())) break; - av_frame_unref(mDecodedFrame.get()); } mEOS = true; std::unique_lock lock(mPictQMutex); - if(mMovie.mQuit.load(std::memory_order_relaxed)) - { - mPictQRead = 0; - mPictQWrite = 0; - mPictQSize = 0; - } while(!mFinalUpdate) mPictQCond.wait(lock); @@ -1436,7 +1430,7 @@ int VideoState::handler() int MovieState::decode_interrupt_cb(void *ctx) { - return reinterpret_cast(ctx)->mQuit.load(std::memory_order_relaxed); + return static_cast(ctx)->mQuit.load(std::memory_order_relaxed); } bool MovieState::prepare() @@ -1531,15 +1525,11 @@ int MovieState::streamComponentOpen(int stream_index) case AVMEDIA_TYPE_AUDIO: mAudio.mStream = mFormatCtx->streams[stream_index]; mAudio.mCodecCtx = std::move(avctx); - - mAudioThread = std::thread(std::mem_fn(&AudioState::handler), &mAudio); break; case AVMEDIA_TYPE_VIDEO: mVideo.mStream = mFormatCtx->streams[stream_index]; mVideo.mCodecCtx = std::move(avctx); - - mVideoThread = std::thread(std::mem_fn(&VideoState::handler), &mVideo); break; default: @@ -1551,17 +1541,15 @@ int MovieState::streamComponentOpen(int stream_index) int MovieState::parse_handler() { - int video_index = -1; - int audio_index = -1; + auto &audio_queue = mAudio.mPackets; + auto &video_queue = mVideo.mPackets; + + int video_index{-1}; + int audio_index{-1}; /* Dump information about file onto standard error */ av_dump_format(mFormatCtx.get(), 0, mFilename.c_str(), 0); - /* Set the base time 500ms ahead of the current av time. */ - mClockBase = get_avtime() + milliseconds{500}; - mVideo.mCurrentPtsTime = mClockBase; - mVideo.mFrameTimer = mVideo.mCurrentPtsTime; - /* Find the first video and audio streams */ for(unsigned int i = 0;i < mFormatCtx->nb_streams;i++) { @@ -1578,82 +1566,40 @@ int MovieState::parse_handler() mQuit = true; } - PacketQueue audio_queue, video_queue; - bool input_finished = false; + /* Set the base time 500ms ahead of the current av time. */ + mClockBase = get_avtime() + milliseconds{500}; + mVideo.mCurrentPtsTime = mClockBase; + mVideo.mFrameTimer = mVideo.mCurrentPtsTime; + + if(audio_index >= 0) + mAudioThread = std::thread{std::mem_fn(&AudioState::handler), &mAudio}; + if(video_index >= 0) + mVideoThread = std::thread{std::mem_fn(&VideoState::handler), &mVideo}; /* Main packet reading/dispatching loop */ - while(!mQuit.load(std::memory_order_relaxed) && !input_finished) + while(!mQuit.load(std::memory_order_relaxed)) { AVPacket packet; if(av_read_frame(mFormatCtx.get(), &packet) < 0) - input_finished = true; - else - { - /* Copy the packet into the queue it's meant for. */ - if(packet.stream_index == video_index) - video_queue.put(&packet); - else if(packet.stream_index == audio_index) - audio_queue.put(&packet); - av_packet_unref(&packet); - } - - do { - /* Send whatever queued packets we have. */ - if(!audio_queue.empty()) - { - std::unique_lock lock(mAudio.mQueueMtx); - int ret; - do { - ret = avcodec_send_packet(mAudio.mCodecCtx.get(), audio_queue.front()); - if(ret != AVERROR(EAGAIN)) audio_queue.pop(); - } while(ret != AVERROR(EAGAIN) && !audio_queue.empty()); - lock.unlock(); - mAudio.mQueueCond.notify_one(); - } - if(!video_queue.empty()) - { - std::unique_lock lock(mVideo.mQueueMtx); - int ret; - do { - ret = avcodec_send_packet(mVideo.mCodecCtx.get(), video_queue.front()); - if(ret != AVERROR(EAGAIN)) video_queue.pop(); - } while(ret != AVERROR(EAGAIN) && !video_queue.empty()); - lock.unlock(); - mVideo.mQueueCond.notify_one(); - } - /* If the queues are completely empty, or it's not full and there's - * more input to read, go get more. - */ - size_t queue_size = audio_queue.totalSize() + video_queue.totalSize(); - if(queue_size == 0 || (queue_size < MAX_QUEUE_SIZE && !input_finished)) - break; + break; - /* Nothing to send or get for now, wait a bit and try again. */ - { std::unique_lock lock(mSendMtx); - if(mSendDataGood.test_and_set(std::memory_order_relaxed)) - mSendCond.wait_for(lock, milliseconds{10}); - } - } while(!mQuit.load(std::memory_order_relaxed)); - } - /* Pass a null packet to finish the send buffers (the receive functions - * will get AVERROR_EOF when emptied). - */ - if(mVideo.mCodecCtx) - { - { std::lock_guard lock(mVideo.mQueueMtx); - avcodec_send_packet(mVideo.mCodecCtx.get(), nullptr); + /* Copy the packet into the queue it's meant for. */ + if(packet.stream_index == video_index) + { + while(!mQuit.load(std::memory_order_acquire) && !video_queue.put(&packet)) + std::this_thread::sleep_for(milliseconds{50}); } - mVideo.mQueueCond.notify_one(); - } - if(mAudio.mCodecCtx) - { - { std::lock_guard lock(mAudio.mQueueMtx); - avcodec_send_packet(mAudio.mCodecCtx.get(), nullptr); + else if(packet.stream_index == audio_index) + { + while(!mQuit.load(std::memory_order_acquire) && !audio_queue.put(&packet)) + std::this_thread::sleep_for(milliseconds{50}); } - mAudio.mQueueCond.notify_one(); + + av_packet_unref(&packet); } - video_queue.clear(); - audio_queue.clear(); + /* Finish the queues so the receivers know nothing more is coming. */ + if(mVideo.mCodecCtx) video_queue.setFinished(); + if(mAudio.mCodecCtx) audio_queue.setFinished(); /* all done - wait for it */ if(mVideoThread.joinable()) @@ -1916,15 +1862,11 @@ int main(int argc, char *argv[]) break; case FF_UPDATE_EVENT: - reinterpret_cast(event.user.data1)->updatePicture( - screen, renderer - ); + static_cast(event.user.data1)->updatePicture(screen, renderer); break; case FF_REFRESH_EVENT: - reinterpret_cast(event.user.data1)->refreshTimer( - screen, renderer - ); + static_cast(event.user.data1)->refreshTimer(screen, renderer); break; case FF_MOVIE_DONE_EVENT: -- cgit v1.2.3 From 159024acc997540a812fb2fb1197864f46da1dec Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 9 Jul 2019 17:14:15 -0700 Subject: Improve alffplay video clock timing --- examples/alffplay.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index f6bf6863..4deda33a 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -372,7 +372,7 @@ struct VideoState { static Uint32 SDLCALL sdl_refresh_timer_cb(Uint32 interval, void *opaque); void schedRefresh(milliseconds delay); - void display(SDL_Window *screen, SDL_Renderer *renderer); + void display(SDL_Window *screen, SDL_Renderer *renderer, Picture *vp); void refreshTimer(SDL_Window *screen, SDL_Renderer *renderer); void updatePicture(SDL_Window *screen, SDL_Renderer *renderer); bool queuePicture(nanoseconds pts, AVFrame *frame); @@ -1106,6 +1106,7 @@ finish: nanoseconds VideoState::getClock() { /* NOTE: This returns incorrect times while not playing. */ + std::lock_guard _{mPictQMutex}; auto delta = get_avtime() - mCurrentPtsTime; return mCurrentPts + delta; } @@ -1126,10 +1127,8 @@ void VideoState::schedRefresh(milliseconds delay) } /* Called by VideoState::refreshTimer to display the next video frame. */ -void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer) +void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer, Picture *vp) { - Picture *vp = &mPictQ[mPictQRead]; - if(!vp->mImage) return; @@ -1197,8 +1196,6 @@ retry: } Picture *vp = &mPictQ[mPictQRead]; - mCurrentPts = vp->mPts; - mCurrentPtsTime = get_avtime(); /* Get delay using the frame pts and the pts from last frame. */ auto delay = vp->mPts - mFrameLastPts; @@ -1236,6 +1233,9 @@ retry: { /* We don't have time to handle this picture, just skip to the next one. */ lock.lock(); + mCurrentPts = vp->mPts; + mCurrentPtsTime = get_avtime(); + mPictQRead = (mPictQRead+1)%mPictQ.size(); --mPictQSize; --mPictQPrepSize; mPictQCond.notify_all(); @@ -1244,10 +1244,13 @@ retry: schedRefresh(std::chrono::duration_cast(actual_delay)); /* Show the picture! */ - display(screen, renderer); + display(screen, renderer, vp); /* Update queue for next picture. */ lock.lock(); + mCurrentPts = vp->mPts; + mCurrentPtsTime = get_avtime(); + mPictQRead = (mPictQRead+1)%mPictQ.size(); --mPictQSize; --mPictQPrepSize; lock.unlock(); @@ -1662,7 +1665,9 @@ int main(int argc, char *argv[]) return 1; } /* Register all formats and codecs */ +#if !(LIBAVFORMAT_VERSION_INT >= AV_VERSION_INT(58, 9, 100)) av_register_all(); +#endif /* Initialize networking protocols */ avformat_network_init(); -- cgit v1.2.3 From 426c4587ccc78ee9a3d36c7120596fbb037b3ff8 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Wed, 10 Jul 2019 02:13:28 -0700 Subject: Some clean up to use uniform initialization --- examples/alffplay.cpp | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 4deda33a..21ebce77 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -1399,7 +1399,7 @@ int VideoState::handler() avcodec_send_packet(mCodecCtx.get(), nullptr); } /* Decode video frame */ - int ret = avcodec_receive_frame(mCodecCtx.get(), decoded_frame.get()); + int ret{avcodec_receive_frame(mCodecCtx.get(), decoded_frame.get())}; if(ret == AVERROR_EOF) break; if(ret < 0) { @@ -1438,8 +1438,8 @@ int MovieState::decode_interrupt_cb(void *ctx) bool MovieState::prepare() { - AVIOContext *avioctx = nullptr; - AVIOInterruptCB intcb = { decode_interrupt_cb, this }; + AVIOContext *avioctx{nullptr}; + AVIOInterruptCB intcb{decode_interrupt_cb, this}; if(avio_open2(&avioctx, mFilename.c_str(), AVIO_FLAG_READ, &intcb, nullptr)) { std::cerr<< "Failed to open "<pb = mIOContext.get(); fmtctx->interrupt_callback = intcb; if(avformat_open_input(&fmtctx, mFilename.c_str(), nullptr, nullptr) != 0) @@ -1467,9 +1467,9 @@ bool MovieState::prepare() return false; } - mVideo.schedRefresh(milliseconds(40)); + mVideo.schedRefresh(milliseconds{40}); - mParseThread = std::thread(std::mem_fn(&MovieState::parse_handler), this); + mParseThread = std::thread{std::mem_fn(&MovieState::parse_handler), this}; return true; } @@ -1508,17 +1508,17 @@ int MovieState::streamComponentOpen(int stream_index) /* Get a pointer to the codec context for the stream, and open the * associated codec. */ - AVCodecCtxPtr avctx(avcodec_alloc_context3(nullptr)); + AVCodecCtxPtr avctx{avcodec_alloc_context3(nullptr)}; if(!avctx) return -1; if(avcodec_parameters_to_context(avctx.get(), mFormatCtx->streams[stream_index]->codecpar)) return -1; - AVCodec *codec = avcodec_find_decoder(avctx->codec_id); + AVCodec *codec{avcodec_find_decoder(avctx->codec_id)}; if(!codec || avcodec_open2(avctx.get(), codec, nullptr) < 0) { std::cerr<< "Unsupported codec: "<codec_id) - << " (0x"<codec_id<codec_id<nb_streams;i++) + for(unsigned int i{0u};i < mFormatCtx->nb_streams;i++) { auto codecpar = mFormatCtx->streams[i]->codecpar; if(codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !DisableVideo && video_index < 0) @@ -1611,7 +1611,7 @@ int MovieState::parse_handler() mAudioThread.join(); mVideo.mEOS = true; - std::unique_lock lock(mVideo.mPictQMutex); + std::unique_lock lock{mVideo.mPictQMutex}; while(!mVideo.mFinalUpdate) mVideo.mPictQCond.wait(lock); lock.unlock(); @@ -1642,7 +1642,7 @@ inline std::ostream &operator<<(std::ostream &os, const PrettyTime &rhs) } // Only handle up to hour formatting - if(t >= hours(1)) + if(t >= hours{1}) os << duration_cast(t).count() << 'h' << std::setfill('0') << std::setw(2) << (duration_cast(t).count() % 60) << 'm'; else @@ -1678,25 +1678,25 @@ int main(int argc, char *argv[]) } /* Make a window to put our video */ - SDL_Window *screen = SDL_CreateWindow(AppName.c_str(), 0, 0, 640, 480, SDL_WINDOW_RESIZABLE); + SDL_Window *screen{SDL_CreateWindow(AppName.c_str(), 0, 0, 640, 480, SDL_WINDOW_RESIZABLE)}; if(!screen) { std::cerr<< "SDL: could not set video mode - exiting" <(new MovieState(argv[fileidx++])); + movState = std::unique_ptr{new MovieState{argv[fileidx++]}}; if(!movState->prepare()) movState = nullptr; } if(!movState) @@ -1812,12 +1812,12 @@ int main(int argc, char *argv[]) /* Default to going to the next movie at the end of one. */ enum class EomAction { Next, Quit - } eom_action = EomAction::Next; - seconds last_time(-1); - SDL_Event event; + } eom_action{EomAction::Next}; + seconds last_time{-1}; + SDL_Event event{}; while(1) { - int have_evt = SDL_WaitEventTimeout(&event, 10); + int have_evt{SDL_WaitEventTimeout(&event, 10)}; auto cur_time = std::chrono::duration_cast(movState->getMasterClock()); if(cur_time != last_time) @@ -1882,7 +1882,7 @@ int main(int argc, char *argv[]) movState = nullptr; while(fileidx < argc && !movState) { - movState = std::unique_ptr(new MovieState(argv[fileidx++])); + movState = std::unique_ptr{new MovieState{argv[fileidx++]}}; if(!movState->prepare()) movState = nullptr; } if(movState) -- cgit v1.2.3 From 2e6c7808b014de6e15c16aa58506192a0b141cd2 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Thu, 11 Jul 2019 03:54:26 -0700 Subject: Try to improve alffplay timing again --- examples/alffplay.cpp | 63 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 38 insertions(+), 25 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 21ebce77..eecaaeff 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -322,7 +322,7 @@ struct AudioState { int decodeFrame(); bool readAudio(uint8_t *samples, int length); - int handler(); + int handler(const milliseconds start_delay); }; struct VideoState { @@ -339,7 +339,7 @@ struct VideoState { nanoseconds mFrameLastDelay{0}; nanoseconds mCurrentPts{0}; /* time (av_gettime) at which we updated mCurrentPts - used to have running video pts */ - microseconds mCurrentPtsTime{0}; + microseconds mCurrentPtsTime{microseconds::min()}; /* Swscale context for format conversion */ SwsContextPtr mSwscaleCtx; @@ -376,7 +376,7 @@ struct VideoState { void refreshTimer(SDL_Window *screen, SDL_Renderer *renderer); void updatePicture(SDL_Window *screen, SDL_Renderer *renderer); bool queuePicture(nanoseconds pts, AVFrame *frame); - int handler(); + int handler(const milliseconds start_delay); }; struct MovieState { @@ -385,7 +385,7 @@ struct MovieState { SyncMaster mAVSyncType{SyncMaster::Default}; - microseconds mClockBase{0}; + microseconds mClockBase{microseconds::min()}; std::atomic mQuit{false}; @@ -706,14 +706,14 @@ void AL_APIENTRY AudioState::EventCallback(ALenum eventType, ALuint object, ALui ALsizei length, const ALchar *message, void *userParam) { - AudioState *self = static_cast(userParam); + auto self = static_cast(userParam); if(eventType == AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT) { /* Temporarily lock the source mutex to ensure it's not between * checking the processed count and going to sleep. */ - std::unique_lock(self->mSrcMutex).unlock(); + std::unique_lock{self->mSrcMutex}.unlock(); self->mSrcCond.notify_one(); return; } @@ -738,7 +738,8 @@ void AL_APIENTRY AudioState::EventCallback(ALenum eventType, ALuint object, ALui if(eventType == AL_EVENT_TYPE_DISCONNECTED_SOFT) { - { std::lock_guard lock(self->mSrcMutex); + { + std::lock_guard lock{self->mSrcMutex}; self->mConnected.clear(std::memory_order_release); } self->mSrcCond.notify_one(); @@ -746,12 +747,21 @@ void AL_APIENTRY AudioState::EventCallback(ALenum eventType, ALuint object, ALui } #endif -int AudioState::handler() +int AudioState::handler(const milliseconds /*start_delay*/) { - std::unique_lock srclock(mSrcMutex); - milliseconds sleep_time = AudioBufferTime / 3; + std::unique_lock srclock{mSrcMutex}; + milliseconds sleep_time{AudioBufferTime / 3}; ALenum fmt; + if(alcGetInteger64vSOFT) + { + int64_t devtime{}; + alcGetInteger64vSOFT(alcGetContextsDevice(alcGetCurrentContext()), ALC_DEVICE_CLOCK_SOFT, + 1, &devtime); + mDeviceStartTime = nanoseconds{devtime} - mCurrentPts; + } + srclock.unlock(); + #ifdef AL_SOFT_events const std::array evt_types{{ AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT, AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT, @@ -999,13 +1009,7 @@ int AudioState::handler() #endif samples = av_malloc(buffer_len); - { - int64_t devtime{}; - alcGetInteger64vSOFT(alcGetContextsDevice(alcGetCurrentContext()), ALC_DEVICE_CLOCK_SOFT, - 1, &devtime); - mDeviceStartTime = nanoseconds{devtime} - mCurrentPts; - } - + srclock.lock(); while(alGetError() == AL_NO_ERROR && !mMovie.mQuit.load(std::memory_order_relaxed) && mConnected.test_and_set(std::memory_order_relaxed)) { @@ -1086,10 +1090,10 @@ int AudioState::handler() alSourceRewind(mSource); alSourcei(mSource, AL_BUFFER, 0); + srclock.unlock(); finish: av_freep(&samples); - srclock.unlock(); #ifdef AL_SOFT_events if(alEventControlSOFT) @@ -1107,6 +1111,8 @@ nanoseconds VideoState::getClock() { /* NOTE: This returns incorrect times while not playing. */ std::lock_guard _{mPictQMutex}; + if(mCurrentPtsTime == microseconds::min()) + return nanoseconds::zero(); auto delta = get_avtime() - mCurrentPtsTime; return mCurrentPts + delta; } @@ -1217,7 +1223,7 @@ retry: /* Skip or repeat the frame. Take delay into account. */ auto sync_threshold = std::min(delay, VideoSyncThreshold); - if(!(diff < AVNoSyncThreshold && diff > -AVNoSyncThreshold)) + if(diff < AVNoSyncThreshold && diff > -AVNoSyncThreshold) { if(diff <= -sync_threshold) delay = nanoseconds::zero(); @@ -1381,8 +1387,14 @@ bool VideoState::queuePicture(nanoseconds pts, AVFrame *frame) return true; } -int VideoState::handler() +int VideoState::handler(const milliseconds start_delay) { + { + std::lock_guard _{mPictQMutex}; + mCurrentPtsTime = get_avtime(); + mFrameTimer = mCurrentPtsTime + start_delay; + } + AVFramePtr decoded_frame{av_frame_alloc()}; while(!mMovie.mQuit.load(std::memory_order_relaxed)) { @@ -1485,6 +1497,8 @@ void MovieState::setTitle(SDL_Window *window) nanoseconds MovieState::getClock() { + if(mClockBase == microseconds::min()) + return nanoseconds::zero(); return get_avtime() - mClockBase; } @@ -1570,14 +1584,13 @@ int MovieState::parse_handler() } /* Set the base time 500ms ahead of the current av time. */ - mClockBase = get_avtime() + milliseconds{500}; - mVideo.mCurrentPtsTime = mClockBase; - mVideo.mFrameTimer = mVideo.mCurrentPtsTime; + constexpr milliseconds start_delay{500}; + mClockBase = get_avtime() + start_delay; if(audio_index >= 0) - mAudioThread = std::thread{std::mem_fn(&AudioState::handler), &mAudio}; + mAudioThread = std::thread{std::mem_fn(&AudioState::handler), &mAudio, start_delay}; if(video_index >= 0) - mVideoThread = std::thread{std::mem_fn(&VideoState::handler), &mVideo}; + mVideoThread = std::thread{std::mem_fn(&VideoState::handler), &mVideo, start_delay}; /* Main packet reading/dispatching loop */ while(!mQuit.load(std::memory_order_relaxed)) -- cgit v1.2.3 From f99474c913109dba9a4824979d6ea6f41f150831 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Fri, 12 Jul 2019 23:34:21 -0700 Subject: Handle alffplay video using continuous rendering --- examples/alffplay.cpp | 527 ++++++++++++++++++++++---------------------------- 1 file changed, 236 insertions(+), 291 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index eecaaeff..0b80e20f 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -133,9 +133,7 @@ const milliseconds AudioBufferTime{20}; const milliseconds AudioBufferTotalTime{800}; enum { - FF_UPDATE_EVENT = SDL_USEREVENT, - FF_REFRESH_EVENT, - FF_MOVIE_DONE_EVENT + FF_MOVIE_DONE_EVENT = SDL_USEREVENT }; enum class SyncMaster { @@ -322,7 +320,7 @@ struct AudioState { int decodeFrame(); bool readAudio(uint8_t *samples, int length); - int handler(const milliseconds start_delay); + int handler(); }; struct VideoState { @@ -333,13 +331,13 @@ struct VideoState { PacketQueue<14*1024*1024> mPackets; - nanoseconds mClock{0}; - nanoseconds mFrameTimer{0}; - nanoseconds mFrameLastPts{0}; - nanoseconds mFrameLastDelay{0}; + /* The expected pts of the next frame to decode. */ nanoseconds mCurrentPts{0}; - /* time (av_gettime) at which we updated mCurrentPts - used to have running video pts */ - microseconds mCurrentPtsTime{microseconds::min()}; + /* The pts of the currently displayed frame, and the time (av_gettime) it + * was last updated - used to have running video pts + */ + nanoseconds mDisplayPts{0}; + microseconds mDisplayPtsTime{microseconds::min()}; /* Swscale context for format conversion */ SwsContextPtr mSwscaleCtx; @@ -347,19 +345,23 @@ struct VideoState { struct Picture { SDL_Texture *mImage{nullptr}; int mWidth{0}, mHeight{0}; /* Logical image size (actual size may be larger) */ - AVFramePtr mFrame{av_frame_alloc()}; - nanoseconds mPts{0}; + AVFramePtr mFrame{}; + nanoseconds mPts{nanoseconds::min()}; + bool mUpdated{false}; + Picture() = default; + Picture(Picture&&) = delete; ~Picture() { if(mImage) SDL_DestroyTexture(mImage); mImage = nullptr; } + Picture& operator=(Picture&&) = delete; }; std::array mPictQ; - size_t mPictQSize{0}, mPictQRead{0}, mPictQWrite{0}; - size_t mPictQPrepSize{0}, mPictQPrep{0}; + size_t mPictQSize{0u}, mPictQRead{0u}, mPictQWrite{1u}; + size_t mPictQPrepSize{0u}, mPictQPrep{1u}; std::mutex mPictQMutex; std::condition_variable mPictQCond; bool mFirstUpdate{true}; @@ -370,13 +372,10 @@ struct VideoState { nanoseconds getClock(); - static Uint32 SDLCALL sdl_refresh_timer_cb(Uint32 interval, void *opaque); - void schedRefresh(milliseconds delay); void display(SDL_Window *screen, SDL_Renderer *renderer, Picture *vp); - void refreshTimer(SDL_Window *screen, SDL_Renderer *renderer); - void updatePicture(SDL_Window *screen, SDL_Renderer *renderer); + void updateVideo(SDL_Window *screen, SDL_Renderer *renderer); bool queuePicture(nanoseconds pts, AVFrame *frame); - int handler(const milliseconds start_delay); + int handler(); }; struct MovieState { @@ -747,7 +746,7 @@ void AL_APIENTRY AudioState::EventCallback(ALenum eventType, ALuint object, ALui } #endif -int AudioState::handler(const milliseconds /*start_delay*/) +int AudioState::handler() { std::unique_lock srclock{mSrcMutex}; milliseconds sleep_time{AudioBufferTime / 3}; @@ -1111,28 +1110,13 @@ nanoseconds VideoState::getClock() { /* NOTE: This returns incorrect times while not playing. */ std::lock_guard _{mPictQMutex}; - if(mCurrentPtsTime == microseconds::min()) + if(mDisplayPtsTime == microseconds::min()) return nanoseconds::zero(); - auto delta = get_avtime() - mCurrentPtsTime; - return mCurrentPts + delta; -} - -Uint32 SDLCALL VideoState::sdl_refresh_timer_cb(Uint32 /*interval*/, void *opaque) -{ - SDL_Event evt{}; - evt.user.type = FF_REFRESH_EVENT; - evt.user.data1 = opaque; - SDL_PushEvent(&evt); - return 0; /* 0 means stop timer */ -} - -/* Schedules an FF_REFRESH_EVENT event to occur in 'delay' ms. */ -void VideoState::schedRefresh(milliseconds delay) -{ - SDL_AddTimer(delay.count(), sdl_refresh_timer_cb, this); + auto delta = get_avtime() - mDisplayPtsTime; + return mDisplayPts + delta; } -/* Called by VideoState::refreshTimer to display the next video frame. */ +/* Called by VideoState::updateVideo to display the next video frame. */ void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer, Picture *vp) { if(!vp->mImage) @@ -1169,232 +1153,201 @@ void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer, Picture *vp SDL_RenderPresent(renderer); } -/* FF_REFRESH_EVENT handler called on the main thread where the SDL_Renderer - * was created. It handles the display of the next decoded video frame (if not - * falling behind), and sets up the timer for the following video frame. +/* Called regularly on the main thread where the SDL_Renderer was created. It + * handles updating the textures of decoded frames and displaying the latest + * frame. */ -void VideoState::refreshTimer(SDL_Window *screen, SDL_Renderer *renderer) +void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) { - if(!mStream) - { - if(mEOS) - { - mFinalUpdate = true; - std::unique_lock(mPictQMutex).unlock(); - mPictQCond.notify_all(); - return; - } - schedRefresh(milliseconds{100}); - return; - } - std::unique_lock lock{mPictQMutex}; -retry: - if(mPictQPrepSize == 0 || mMovie.mQuit.load(std::memory_order_relaxed)) + while(mPictQPrep != mPictQWrite && !mMovie.mQuit.load(std::memory_order_relaxed)) { - if(mEOS) - mFinalUpdate = true; - else - schedRefresh(milliseconds{10}); + Picture *vp{&mPictQ[mPictQPrep]}; + bool fmt_updated{false}; lock.unlock(); - mPictQCond.notify_all(); - return; - } - Picture *vp = &mPictQ[mPictQRead]; + /* allocate or resize the buffer! */ + if(!vp->mImage || vp->mWidth != mCodecCtx->width || vp->mHeight != mCodecCtx->height) + { + fmt_updated = true; + if(vp->mImage) + SDL_DestroyTexture(vp->mImage); + vp->mImage = SDL_CreateTexture( + renderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, + mCodecCtx->coded_width, mCodecCtx->coded_height + ); + if(!vp->mImage) + std::cerr<< "Failed to create YV12 texture!" <mWidth = mCodecCtx->width; + vp->mHeight = mCodecCtx->height; - /* Get delay using the frame pts and the pts from last frame. */ - auto delay = vp->mPts - mFrameLastPts; - if(delay <= seconds::zero() || delay >= seconds{1}) - { - /* If incorrect delay, use previous one. */ - delay = mFrameLastDelay; - } - /* Save for next frame. */ - mFrameLastDelay = delay; - mFrameLastPts = vp->mPts; - lock.unlock(); + if(mFirstUpdate && vp->mWidth > 0 && vp->mHeight > 0) + { + /* For the first update, set the window size to the video size. */ + mFirstUpdate = false; - /* Update delay to sync to clock if not master source. */ - if(mMovie.mAVSyncType != SyncMaster::Video) - { - auto ref_clock = mMovie.getMasterClock(); - auto diff = vp->mPts - ref_clock; + int w = vp->mWidth; + int h = vp->mHeight; + if(mCodecCtx->sample_aspect_ratio.den != 0) + { + double aspect_ratio = av_q2d(mCodecCtx->sample_aspect_ratio); + if(aspect_ratio >= 1.0) + w = static_cast(w*aspect_ratio + 0.5); + else if(aspect_ratio > 0.0) + h = static_cast(h/aspect_ratio + 0.5); + } + SDL_SetWindowSize(screen, w, h); + } + } - /* Skip or repeat the frame. Take delay into account. */ - auto sync_threshold = std::min(delay, VideoSyncThreshold); - if(diff < AVNoSyncThreshold && diff > -AVNoSyncThreshold) + if(vp->mImage) { - if(diff <= -sync_threshold) - delay = nanoseconds::zero(); - else if(diff >= sync_threshold) - delay *= 2; + AVFrame *frame{vp->mFrame.get()}; + void *pixels{nullptr}; + int pitch{0}; + + if(mCodecCtx->pix_fmt == AV_PIX_FMT_YUV420P) + SDL_UpdateYUVTexture(vp->mImage, nullptr, + frame->data[0], frame->linesize[0], + frame->data[1], frame->linesize[1], + frame->data[2], frame->linesize[2] + ); + else if(SDL_LockTexture(vp->mImage, nullptr, &pixels, &pitch) != 0) + std::cerr<< "Failed to lock texture" <coded_width}; + int coded_h{mCodecCtx->coded_height}; + int w{mCodecCtx->width}; + int h{mCodecCtx->height}; + if(!mSwscaleCtx || fmt_updated) + { + mSwscaleCtx.reset(sws_getContext( + w, h, mCodecCtx->pix_fmt, + w, h, AV_PIX_FMT_YUV420P, 0, + nullptr, nullptr, nullptr + )); + } + + /* point pict at the queue */ + uint8_t *pict_data[3]; + pict_data[0] = static_cast(pixels); + pict_data[1] = pict_data[0] + coded_w*coded_h; + pict_data[2] = pict_data[1] + coded_w*coded_h/4; + + int pict_linesize[3]; + pict_linesize[0] = pitch; + pict_linesize[1] = pitch / 2; + pict_linesize[2] = pitch / 2; + + sws_scale(mSwscaleCtx.get(), reinterpret_cast(frame->data), frame->linesize, + 0, h, pict_data, pict_linesize); + SDL_UnlockTexture(vp->mImage); + } } - } + vp->mUpdated = true; + av_frame_unref(vp->mFrame.get()); - mFrameTimer += delay; - /* Compute the REAL delay. */ - auto actual_delay = mFrameTimer - get_avtime(); - if(!(actual_delay >= VideoSyncThreshold)) - { - /* We don't have time to handle this picture, just skip to the next one. */ - lock.lock(); - mCurrentPts = vp->mPts; - mCurrentPtsTime = get_avtime(); + mPictQPrep = (mPictQPrep+1)%mPictQ.size(); + ++mPictQPrepSize; - mPictQRead = (mPictQRead+1)%mPictQ.size(); - --mPictQSize; --mPictQPrepSize; - mPictQCond.notify_all(); - goto retry; + lock.lock(); } - schedRefresh(std::chrono::duration_cast(actual_delay)); - /* Show the picture! */ - display(screen, renderer, vp); + Picture *vp{&mPictQ[mPictQRead]}; + auto clocktime = mMovie.getMasterClock(); - /* Update queue for next picture. */ - lock.lock(); - mCurrentPts = vp->mPts; - mCurrentPtsTime = get_avtime(); + bool updated{false}; + while(mPictQPrepSize > 0 && !mMovie.mQuit.load(std::memory_order_relaxed)) + { + size_t nextIdx{(mPictQRead+1)%mPictQ.size()}; + Picture *newvp{&mPictQ[nextIdx]}; + if(clocktime < newvp->mPts || !newvp->mUpdated) + break; - mPictQRead = (mPictQRead+1)%mPictQ.size(); - --mPictQSize; --mPictQPrepSize; - lock.unlock(); - mPictQCond.notify_all(); -} + newvp->mUpdated = false; + if(!newvp->mImage) + std::swap(vp->mImage, newvp->mImage); + vp = newvp; + updated = true; -/* FF_UPDATE_EVENT handler, updates the picture's texture. It's called on the - * main thread where the renderer was created. - */ -void VideoState::updatePicture(SDL_Window *screen, SDL_Renderer *renderer) -{ + mPictQRead = nextIdx; + --mPictQSize; --mPictQPrepSize; + } if(mMovie.mQuit.load(std::memory_order_relaxed)) + { + if(mEOS) + mFinalUpdate = true; + lock.unlock(); + mPictQCond.notify_all(); return; + } + lock.unlock(); + if(updated) + mPictQCond.notify_all(); - Picture *vp = &mPictQ[mPictQPrep]; - bool fmt_updated = false; + /* Show the picture! */ + display(screen, renderer, vp); - /* allocate or resize the buffer! */ - if(!vp->mImage || vp->mWidth != mCodecCtx->width || vp->mHeight != mCodecCtx->height) + if(updated) { - fmt_updated = true; - if(vp->mImage) - SDL_DestroyTexture(vp->mImage); - vp->mImage = SDL_CreateTexture( - renderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, - mCodecCtx->coded_width, mCodecCtx->coded_height - ); - if(!vp->mImage) - std::cerr<< "Failed to create YV12 texture!" <mWidth = mCodecCtx->width; - vp->mHeight = mCodecCtx->height; - - if(mFirstUpdate && vp->mWidth > 0 && vp->mHeight > 0) + lock.lock(); + mDisplayPts = vp->mPts; + mDisplayPtsTime = get_avtime(); + if(mEOS.load(std::memory_order_acquire) && mPictQSize == 0) { - /* For the first update, set the window size to the video size. */ - mFirstUpdate = false; - - int w = vp->mWidth; - int h = vp->mHeight; - if(mCodecCtx->sample_aspect_ratio.den != 0) - { - double aspect_ratio = av_q2d(mCodecCtx->sample_aspect_ratio); - if(aspect_ratio >= 1.0) - w = static_cast(w*aspect_ratio + 0.5); - else if(aspect_ratio > 0.0) - h = static_cast(h/aspect_ratio + 0.5); - } - SDL_SetWindowSize(screen, w, h); + mFinalUpdate = true; + mPictQCond.notify_all(); } + lock.unlock(); } - - AVFrame *frame{vp->mFrame.get()}; - if(vp->mImage) + else if(mEOS.load(std::memory_order_acquire)) { - void *pixels{nullptr}; - int pitch{0}; - - if(mCodecCtx->pix_fmt == AV_PIX_FMT_YUV420P) - SDL_UpdateYUVTexture(vp->mImage, nullptr, - frame->data[0], frame->linesize[0], - frame->data[1], frame->linesize[1], - frame->data[2], frame->linesize[2] - ); - else if(SDL_LockTexture(vp->mImage, nullptr, &pixels, &pitch) != 0) - std::cerr<< "Failed to lock texture" <coded_width}; - int coded_h{mCodecCtx->coded_height}; - int w{mCodecCtx->width}; - int h{mCodecCtx->height}; - if(!mSwscaleCtx || fmt_updated) - { - mSwscaleCtx.reset(sws_getContext( - w, h, mCodecCtx->pix_fmt, - w, h, AV_PIX_FMT_YUV420P, 0, - nullptr, nullptr, nullptr - )); - } - - /* point pict at the queue */ - uint8_t *pict_data[3]; - pict_data[0] = reinterpret_cast(pixels); - pict_data[1] = pict_data[0] + coded_w*coded_h; - pict_data[2] = pict_data[1] + coded_w*coded_h/4; - - int pict_linesize[3]; - pict_linesize[0] = pitch; - pict_linesize[1] = pitch / 2; - pict_linesize[2] = pitch / 2; - - sws_scale(mSwscaleCtx.get(), reinterpret_cast(frame->data), frame->linesize, - 0, h, pict_data, pict_linesize); - SDL_UnlockTexture(vp->mImage); + mFinalUpdate = true; + mPictQCond.notify_all(); } + lock.unlock(); } - av_frame_unref(frame); - - mPictQPrep = (mPictQPrep+1)%mPictQ.size(); - ++mPictQPrepSize; } bool VideoState::queuePicture(nanoseconds pts, AVFrame *frame) { /* Wait until we have space for a new pic */ std::unique_lock lock{mPictQMutex}; - while(mPictQSize >= mPictQ.size() && !mMovie.mQuit.load(std::memory_order_relaxed)) + while(mPictQSize >= (mPictQ.size()-1) && !mMovie.mQuit.load(std::memory_order_relaxed)) mPictQCond.wait(lock); if(mMovie.mQuit.load(std::memory_order_relaxed)) return false; + /* Put the frame in the queue to be loaded into a texture (and eventually + * displayed) by the rendering thread. + */ Picture *vp{&mPictQ[mPictQWrite]}; av_frame_move_ref(vp->mFrame.get(), frame); vp->mPts = pts; mPictQWrite = (mPictQWrite+1)%mPictQ.size(); ++mPictQSize; - lock.unlock(); - - /* We have to create/update the picture in the main thread */ - SDL_Event evt{}; - evt.user.type = FF_UPDATE_EVENT; - evt.user.data1 = this; - SDL_PushEvent(&evt); return true; } -int VideoState::handler(const milliseconds start_delay) +int VideoState::handler() { { std::lock_guard _{mPictQMutex}; - mCurrentPtsTime = get_avtime(); - mFrameTimer = mCurrentPtsTime + start_delay; + mDisplayPtsTime = get_avtime(); } + std::for_each(mPictQ.begin(), mPictQ.end(), + [](Picture &pict) -> void + { pict.mFrame = AVFramePtr{av_frame_alloc()}; }); + AVFramePtr decoded_frame{av_frame_alloc()}; while(!mMovie.mQuit.load(std::memory_order_relaxed)) { @@ -1421,14 +1374,14 @@ int VideoState::handler(const milliseconds start_delay) /* Get the PTS for this frame. */ if(decoded_frame->best_effort_timestamp != AV_NOPTS_VALUE) - mClock = std::chrono::duration_cast( + mCurrentPts = std::chrono::duration_cast( seconds_d64{av_q2d(mStream->time_base)*decoded_frame->best_effort_timestamp}); - nanoseconds pts{mClock}; + nanoseconds pts{mCurrentPts}; /* Update the video clock to the next expected PTS. */ auto frame_delay = av_q2d(mCodecCtx->time_base); frame_delay += decoded_frame->repeat_pict * (frame_delay * 0.5); - mClock += std::chrono::duration_cast(seconds_d64{frame_delay}); + mCurrentPts += std::chrono::duration_cast(seconds_d64{frame_delay}); if(!queuePicture(pts, decoded_frame.get())) break; @@ -1479,8 +1432,6 @@ bool MovieState::prepare() return false; } - mVideo.schedRefresh(milliseconds{40}); - mParseThread = std::thread{std::mem_fn(&MovieState::parse_handler), this}; return true; } @@ -1584,13 +1535,12 @@ int MovieState::parse_handler() } /* Set the base time 500ms ahead of the current av time. */ - constexpr milliseconds start_delay{500}; - mClockBase = get_avtime() + start_delay; + mClockBase = get_avtime() + milliseconds{500}; if(audio_index >= 0) - mAudioThread = std::thread{std::mem_fn(&AudioState::handler), &mAudio, start_delay}; + mAudioThread = std::thread{std::mem_fn(&AudioState::handler), &mAudio}; if(video_index >= 0) - mVideoThread = std::thread{std::mem_fn(&VideoState::handler), &mVideo, start_delay}; + mVideoThread = std::thread{std::mem_fn(&VideoState::handler), &mVideo}; /* Main packet reading/dispatching loop */ while(!mQuit.load(std::memory_order_relaxed)) @@ -1641,13 +1591,13 @@ int MovieState::parse_handler() struct PrettyTime { seconds mTime; }; -inline std::ostream &operator<<(std::ostream &os, const PrettyTime &rhs) +std::ostream &operator<<(std::ostream &os, const PrettyTime &rhs) { using hours = std::chrono::hours; using minutes = std::chrono::minutes; using std::chrono::duration_cast; - seconds t = rhs.mTime; + seconds t{rhs.mTime}; if(t.count() < 0) { os << '-'; @@ -1827,9 +1777,9 @@ int main(int argc, char *argv[]) Next, Quit } eom_action{EomAction::Next}; seconds last_time{-1}; - SDL_Event event{}; while(1) { + SDL_Event event{}; int have_evt{SDL_WaitEventTimeout(&event, 10)}; auto cur_time = std::chrono::duration_cast(movState->getMasterClock()); @@ -1839,88 +1789,83 @@ int main(int argc, char *argv[]) std::cout<< "\r "<mQuit = true; - eom_action = EomAction::Quit; - break; - - case SDLK_n: - movState->mQuit = true; - eom_action = EomAction::Next; - break; - - default: - break; - } - break; - - case SDL_WINDOWEVENT: - switch(event.window.event) - { - case SDL_WINDOWEVENT_RESIZED: - SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); - SDL_RenderFillRect(renderer, nullptr); - break; - default: - break; - } - break; + if(have_evt) do { + switch(event.type) + { + case SDL_KEYDOWN: + switch(event.key.keysym.sym) + { + case SDLK_ESCAPE: + movState->mQuit = true; + eom_action = EomAction::Quit; + break; + + case SDLK_n: + movState->mQuit = true; + eom_action = EomAction::Next; + break; + + default: + break; + } + break; - case SDL_QUIT: - movState->mQuit = true; - eom_action = EomAction::Quit; - break; + case SDL_WINDOWEVENT: + switch(event.window.event) + { + case SDL_WINDOWEVENT_RESIZED: + SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); + SDL_RenderFillRect(renderer, nullptr); + break; - case FF_UPDATE_EVENT: - static_cast(event.user.data1)->updatePicture(screen, renderer); - break; + default: + break; + } + break; - case FF_REFRESH_EVENT: - static_cast(event.user.data1)->refreshTimer(screen, renderer); - break; + case SDL_QUIT: + movState->mQuit = true; + eom_action = EomAction::Quit; + break; - case FF_MOVIE_DONE_EVENT: - std::cout<<'\n'; - last_time = seconds(-1); - if(eom_action != EomAction::Quit) - { - movState = nullptr; - while(fileidx < argc && !movState) + case FF_MOVIE_DONE_EVENT: + std::cout<<'\n'; + last_time = seconds(-1); + if(eom_action != EomAction::Quit) { - movState = std::unique_ptr{new MovieState{argv[fileidx++]}}; - if(!movState->prepare()) movState = nullptr; + movState = nullptr; + while(fileidx < argc && !movState) + { + movState = std::unique_ptr{new MovieState{argv[fileidx++]}}; + if(!movState->prepare()) movState = nullptr; + } + if(movState) + { + movState->setTitle(screen); + break; + } } - if(movState) - { - movState->setTitle(screen); - break; - } - } - /* Nothing more to play. Shut everything down and quit. */ - movState = nullptr; + /* Nothing more to play. Shut everything down and quit. */ + movState = nullptr; - CloseAL(); + CloseAL(); - SDL_DestroyRenderer(renderer); - renderer = nullptr; - SDL_DestroyWindow(screen); - screen = nullptr; + SDL_DestroyRenderer(renderer); + renderer = nullptr; + SDL_DestroyWindow(screen); + screen = nullptr; - SDL_Quit(); - exit(0); + SDL_Quit(); + exit(0); - default: - break; - } + default: + break; + } + } while(SDL_PollEvent(&event)); + + movState->mVideo.updateVideo(screen, renderer); } std::cerr<< "SDL_WaitEvent error - "< Date: Sat, 13 Jul 2019 19:27:28 -0700 Subject: Don't use one texture per picture in alffplay --- examples/alffplay.cpp | 139 ++++++++++++++++++++++---------------------------- 1 file changed, 60 insertions(+), 79 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 0b80e20f..c42e1aeb 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -343,36 +343,32 @@ struct VideoState { SwsContextPtr mSwscaleCtx; struct Picture { - SDL_Texture *mImage{nullptr}; - int mWidth{0}, mHeight{0}; /* Logical image size (actual size may be larger) */ AVFramePtr mFrame{}; nanoseconds mPts{nanoseconds::min()}; - bool mUpdated{false}; - - Picture() = default; - Picture(Picture&&) = delete; - ~Picture() - { - if(mImage) - SDL_DestroyTexture(mImage); - mImage = nullptr; - } - Picture& operator=(Picture&&) = delete; }; std::array mPictQ; size_t mPictQSize{0u}, mPictQRead{0u}, mPictQWrite{1u}; - size_t mPictQPrepSize{0u}, mPictQPrep{1u}; std::mutex mPictQMutex; std::condition_variable mPictQCond; + + SDL_Texture *mImage{nullptr}; + int mWidth{0}, mHeight{0}; /* Logical image size (actual size may be larger) */ + bool mFirstUpdate{true}; std::atomic mEOS{false}; std::atomic mFinalUpdate{false}; VideoState(MovieState &movie) : mMovie(movie) { } + ~VideoState() + { + if(mImage) + SDL_DestroyTexture(mImage); + mImage = nullptr; + } nanoseconds getClock(); - void display(SDL_Window *screen, SDL_Renderer *renderer, Picture *vp); + void display(SDL_Window *screen, SDL_Renderer *renderer); void updateVideo(SDL_Window *screen, SDL_Renderer *renderer); bool queuePicture(nanoseconds pts, AVFrame *frame); int handler(); @@ -1117,9 +1113,9 @@ nanoseconds VideoState::getClock() } /* Called by VideoState::updateVideo to display the next video frame. */ -void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer, Picture *vp) +void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer) { - if(!vp->mImage) + if(!mImage) return; float aspect_ratio; @@ -1147,9 +1143,9 @@ void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer, Picture *vp x = (win_w - w) / 2; y = (win_h - h) / 2; - SDL_Rect src_rect{ 0, 0, vp->mWidth, vp->mHeight }; + SDL_Rect src_rect{ 0, 0, mWidth, mHeight }; SDL_Rect dst_rect{ x, y, w, h }; - SDL_RenderCopy(renderer, vp->mImage, &src_rect, &dst_rect); + SDL_RenderCopy(renderer, mImage, &src_rect, &dst_rect); SDL_RenderPresent(renderer); } @@ -1160,34 +1156,57 @@ void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer, Picture *vp void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) { std::unique_lock lock{mPictQMutex}; - while(mPictQPrep != mPictQWrite && !mMovie.mQuit.load(std::memory_order_relaxed)) + Picture *vp{&mPictQ[mPictQRead]}; + auto clocktime = mMovie.getMasterClock(); + + bool updated{false}; + while(mPictQSize > 0) { - Picture *vp{&mPictQ[mPictQPrep]}; - bool fmt_updated{false}; + size_t nextIdx{(mPictQRead+1)%mPictQ.size()}; + Picture *newvp{&mPictQ[nextIdx]}; + if(clocktime < newvp->mPts) + break; + + vp = newvp; + updated = true; + + mPictQRead = nextIdx; + --mPictQSize; + } + if(mMovie.mQuit.load(std::memory_order_relaxed)) + { + if(mEOS) + mFinalUpdate = true; lock.unlock(); + mPictQCond.notify_all(); + return; + } + lock.unlock(); + if(updated) + { + mPictQCond.notify_all(); /* allocate or resize the buffer! */ - if(!vp->mImage || vp->mWidth != mCodecCtx->width || vp->mHeight != mCodecCtx->height) + bool fmt_updated{false}; + if(!mImage || mWidth != mCodecCtx->width || mHeight != mCodecCtx->height) { fmt_updated = true; - if(vp->mImage) - SDL_DestroyTexture(vp->mImage); - vp->mImage = SDL_CreateTexture( - renderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, - mCodecCtx->coded_width, mCodecCtx->coded_height - ); - if(!vp->mImage) + if(mImage) + SDL_DestroyTexture(mImage); + mImage = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, + mCodecCtx->coded_width, mCodecCtx->coded_height); + if(!mImage) std::cerr<< "Failed to create YV12 texture!" <mWidth = mCodecCtx->width; - vp->mHeight = mCodecCtx->height; + mWidth = mCodecCtx->width; + mHeight = mCodecCtx->height; - if(mFirstUpdate && vp->mWidth > 0 && vp->mHeight > 0) + if(mFirstUpdate && mWidth > 0 && mHeight > 0) { /* For the first update, set the window size to the video size. */ mFirstUpdate = false; - int w = vp->mWidth; - int h = vp->mHeight; + int w{mWidth}; + int h{mHeight}; if(mCodecCtx->sample_aspect_ratio.den != 0) { double aspect_ratio = av_q2d(mCodecCtx->sample_aspect_ratio); @@ -1200,19 +1219,19 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) } } - if(vp->mImage) + if(mImage) { AVFrame *frame{vp->mFrame.get()}; void *pixels{nullptr}; int pitch{0}; if(mCodecCtx->pix_fmt == AV_PIX_FMT_YUV420P) - SDL_UpdateYUVTexture(vp->mImage, nullptr, + SDL_UpdateYUVTexture(mImage, nullptr, frame->data[0], frame->linesize[0], frame->data[1], frame->linesize[1], frame->data[2], frame->linesize[2] ); - else if(SDL_LockTexture(vp->mImage, nullptr, &pixels, &pitch) != 0) + else if(SDL_LockTexture(mImage, nullptr, &pixels, &pitch) != 0) std::cerr<< "Failed to lock texture" <(frame->data), frame->linesize, 0, h, pict_data, pict_linesize); - SDL_UnlockTexture(vp->mImage); + SDL_UnlockTexture(mImage); } } - vp->mUpdated = true; av_frame_unref(vp->mFrame.get()); - - mPictQPrep = (mPictQPrep+1)%mPictQ.size(); - ++mPictQPrepSize; - - lock.lock(); } - Picture *vp{&mPictQ[mPictQRead]}; - auto clocktime = mMovie.getMasterClock(); - - bool updated{false}; - while(mPictQPrepSize > 0 && !mMovie.mQuit.load(std::memory_order_relaxed)) - { - size_t nextIdx{(mPictQRead+1)%mPictQ.size()}; - Picture *newvp{&mPictQ[nextIdx]}; - if(clocktime < newvp->mPts || !newvp->mUpdated) - break; - - newvp->mUpdated = false; - if(!newvp->mImage) - std::swap(vp->mImage, newvp->mImage); - vp = newvp; - updated = true; - - mPictQRead = nextIdx; - --mPictQSize; --mPictQPrepSize; - } - if(mMovie.mQuit.load(std::memory_order_relaxed)) - { - if(mEOS) - mFinalUpdate = true; - lock.unlock(); - mPictQCond.notify_all(); - return; - } - lock.unlock(); - if(updated) - mPictQCond.notify_all(); - /* Show the picture! */ - display(screen, renderer, vp); + display(screen, renderer); if(updated) { @@ -1634,7 +1615,7 @@ int main(int argc, char *argv[]) /* Initialize networking protocols */ avformat_network_init(); - if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER)) + if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) { std::cerr<< "Could not initialize SDL - <<"< Date: Sat, 13 Jul 2019 21:58:08 -0700 Subject: Receive frames directly into the picture's AVFrame --- examples/alffplay.cpp | 53 ++++++++++++++++++--------------------------------- 1 file changed, 19 insertions(+), 34 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index c42e1aeb..1a509c92 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -370,7 +370,6 @@ struct VideoState { void display(SDL_Window *screen, SDL_Renderer *renderer); void updateVideo(SDL_Window *screen, SDL_Renderer *renderer); - bool queuePicture(nanoseconds pts, AVFrame *frame); int handler(); }; @@ -1295,29 +1294,6 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) } } -bool VideoState::queuePicture(nanoseconds pts, AVFrame *frame) -{ - /* Wait until we have space for a new pic */ - std::unique_lock lock{mPictQMutex}; - while(mPictQSize >= (mPictQ.size()-1) && !mMovie.mQuit.load(std::memory_order_relaxed)) - mPictQCond.wait(lock); - - if(mMovie.mQuit.load(std::memory_order_relaxed)) - return false; - - /* Put the frame in the queue to be loaded into a texture (and eventually - * displayed) by the rendering thread. - */ - Picture *vp{&mPictQ[mPictQWrite]}; - av_frame_move_ref(vp->mFrame.get(), frame); - vp->mPts = pts; - - mPictQWrite = (mPictQWrite+1)%mPictQ.size(); - ++mPictQSize; - - return true; -} - int VideoState::handler() { { @@ -1329,9 +1305,9 @@ int VideoState::handler() [](Picture &pict) -> void { pict.mFrame = AVFramePtr{av_frame_alloc()}; }); - AVFramePtr decoded_frame{av_frame_alloc()}; while(!mMovie.mQuit.load(std::memory_order_relaxed)) { + Picture *vp{&mPictQ[mPictQWrite]}; { std::unique_lock lock{mPackets.getMutex()}; AVPacket *lastpkt{}; @@ -1345,7 +1321,8 @@ int VideoState::handler() avcodec_send_packet(mCodecCtx.get(), nullptr); } /* Decode video frame */ - int ret{avcodec_receive_frame(mCodecCtx.get(), decoded_frame.get())}; + AVFrame *decoded_frame{vp->mFrame.get()}; + int ret{avcodec_receive_frame(mCodecCtx.get(), decoded_frame)}; if(ret == AVERROR_EOF) break; if(ret < 0) { @@ -1357,19 +1334,27 @@ int VideoState::handler() if(decoded_frame->best_effort_timestamp != AV_NOPTS_VALUE) mCurrentPts = std::chrono::duration_cast( seconds_d64{av_q2d(mStream->time_base)*decoded_frame->best_effort_timestamp}); - nanoseconds pts{mCurrentPts}; + vp->mPts = mCurrentPts; /* Update the video clock to the next expected PTS. */ auto frame_delay = av_q2d(mCodecCtx->time_base); frame_delay += decoded_frame->repeat_pict * (frame_delay * 0.5); mCurrentPts += std::chrono::duration_cast(seconds_d64{frame_delay}); - if(!queuePicture(pts, decoded_frame.get())) - break; + /* Put the frame in the queue to be loaded into a texture and displayed + * by the rendering thread. + */ + std::unique_lock lock{mPictQMutex}; + mPictQWrite = (mPictQWrite+1)%mPictQ.size(); + ++mPictQSize; + + /* Wait until we have space for a new pic */ + while(mPictQSize >= (mPictQ.size()-1) && !mMovie.mQuit.load(std::memory_order_relaxed)) + mPictQCond.wait(lock); } mEOS = true; - std::unique_lock lock(mPictQMutex); + std::unique_lock lock{mPictQMutex}; while(!mFinalUpdate) mPictQCond.wait(lock); @@ -1515,8 +1500,8 @@ int MovieState::parse_handler() mQuit = true; } - /* Set the base time 500ms ahead of the current av time. */ - mClockBase = get_avtime() + milliseconds{500}; + /* Set the base time 750ms ahead of the current av time. */ + mClockBase = get_avtime() + milliseconds{750}; if(audio_index >= 0) mAudioThread = std::thread{std::mem_fn(&AudioState::handler), &mAudio}; @@ -1534,12 +1519,12 @@ int MovieState::parse_handler() if(packet.stream_index == video_index) { while(!mQuit.load(std::memory_order_acquire) && !video_queue.put(&packet)) - std::this_thread::sleep_for(milliseconds{50}); + std::this_thread::sleep_for(milliseconds{100}); } else if(packet.stream_index == audio_index) { while(!mQuit.load(std::memory_order_acquire) && !audio_queue.put(&packet)) - std::this_thread::sleep_for(milliseconds{50}); + std::this_thread::sleep_for(milliseconds{100}); } av_packet_unref(&packet); -- cgit v1.2.3 From ac7eeeae7997b6e75ec82dce610b524df33d6f8b Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 13 Jul 2019 22:50:14 -0700 Subject: Don't use the same mutex for the video clock --- examples/alffplay.cpp | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 1a509c92..625c63a6 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -338,6 +338,7 @@ struct VideoState { */ nanoseconds mDisplayPts{0}; microseconds mDisplayPtsTime{microseconds::min()}; + std::mutex mDispPtsMutex; /* Swscale context for format conversion */ SwsContextPtr mSwscaleCtx; @@ -1104,7 +1105,7 @@ finish: nanoseconds VideoState::getClock() { /* NOTE: This returns incorrect times while not playing. */ - std::lock_guard _{mPictQMutex}; + std::lock_guard _{mDispPtsMutex}; if(mDisplayPtsTime == microseconds::min()) return nanoseconds::zero(); auto delta = get_avtime() - mDisplayPtsTime; @@ -1154,19 +1155,20 @@ void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer) */ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) { - std::unique_lock lock{mPictQMutex}; Picture *vp{&mPictQ[mPictQRead]}; + + std::unique_lock lock{mPictQMutex}; auto clocktime = mMovie.getMasterClock(); bool updated{false}; while(mPictQSize > 0) { size_t nextIdx{(mPictQRead+1)%mPictQ.size()}; - Picture *newvp{&mPictQ[nextIdx]}; - if(clocktime < newvp->mPts) + Picture *nextvp{&mPictQ[nextIdx]}; + if(clocktime < nextvp->mPts) break; - vp = newvp; + vp = nextvp; updated = true; mPictQRead = nextIdx; @@ -1181,6 +1183,7 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) return; } lock.unlock(); + if(updated) { mPictQCond.notify_all(); @@ -1264,7 +1267,6 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) SDL_UnlockTexture(mImage); } } - av_frame_unref(vp->mFrame.get()); } /* Show the picture! */ @@ -1272,17 +1274,13 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) if(updated) { - lock.lock(); + auto disp_time = get_avtime(); + + std::lock_guard _{mDispPtsMutex}; mDisplayPts = vp->mPts; - mDisplayPtsTime = get_avtime(); - if(mEOS.load(std::memory_order_acquire) && mPictQSize == 0) - { - mFinalUpdate = true; - mPictQCond.notify_all(); - } - lock.unlock(); + mDisplayPtsTime = disp_time; } - else if(mEOS.load(std::memory_order_acquire)) + if(mEOS.load(std::memory_order_acquire)) { lock.lock(); if(mPictQSize == 0) @@ -1297,7 +1295,7 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) int VideoState::handler() { { - std::lock_guard _{mPictQMutex}; + std::lock_guard _{mDispPtsMutex}; mDisplayPtsTime = get_avtime(); } -- cgit v1.2.3 From 4ff7bfd2d8c5e94e61fbbb7afe57f98037a5383e Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sun, 14 Jul 2019 01:05:54 -0700 Subject: Use atomics for the picture queue --- examples/alffplay.cpp | 64 ++++++++++++++++++++++++++++----------------------- 1 file changed, 35 insertions(+), 29 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 625c63a6..ccdfd51f 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -348,14 +348,14 @@ struct VideoState { nanoseconds mPts{nanoseconds::min()}; }; std::array mPictQ; - size_t mPictQSize{0u}, mPictQRead{0u}, mPictQWrite{1u}; + std::atomic mPictQRead{0u}, mPictQWrite{1u}; std::mutex mPictQMutex; std::condition_variable mPictQCond; SDL_Texture *mImage{nullptr}; int mWidth{0}, mHeight{0}; /* Logical image size (actual size may be larger) */ - bool mFirstUpdate{true}; + std::atomic mEOS{false}; std::atomic mFinalUpdate{false}; @@ -1155,37 +1155,38 @@ void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer) */ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) { - Picture *vp{&mPictQ[mPictQRead]}; + size_t read_idx{mPictQRead.load(std::memory_order_relaxed)}; + Picture *vp{&mPictQ[read_idx]}; - std::unique_lock lock{mPictQMutex}; auto clocktime = mMovie.getMasterClock(); - bool updated{false}; - while(mPictQSize > 0) + while(1) { - size_t nextIdx{(mPictQRead+1)%mPictQ.size()}; - Picture *nextvp{&mPictQ[nextIdx]}; + size_t next_idx{(read_idx+1)%mPictQ.size()}; + if(next_idx == mPictQWrite.load(std::memory_order_acquire)) + break; + Picture *nextvp{&mPictQ[next_idx]}; if(clocktime < nextvp->mPts) break; vp = nextvp; updated = true; - - mPictQRead = nextIdx; - --mPictQSize; + read_idx = next_idx; } if(mMovie.mQuit.load(std::memory_order_relaxed)) { if(mEOS) mFinalUpdate = true; - lock.unlock(); + mPictQRead.store(read_idx, std::memory_order_release); + std::unique_lock{mPictQMutex}.unlock(); mPictQCond.notify_all(); return; } - lock.unlock(); if(updated) { + mPictQRead.store(read_idx, std::memory_order_release); + std::unique_lock{mPictQMutex}.unlock(); mPictQCond.notify_all(); /* allocate or resize the buffer! */ @@ -1282,13 +1283,12 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) } if(mEOS.load(std::memory_order_acquire)) { - lock.lock(); - if(mPictQSize == 0) + if((read_idx+1)%mPictQ.size() == mPictQWrite.load(std::memory_order_acquire)) { mFinalUpdate = true; + std::unique_lock{mPictQMutex}.unlock(); mPictQCond.notify_all(); } - lock.unlock(); } } @@ -1305,7 +1305,9 @@ int VideoState::handler() while(!mMovie.mQuit.load(std::memory_order_relaxed)) { - Picture *vp{&mPictQ[mPictQWrite]}; + size_t write_idx{mPictQWrite.load(std::memory_order_relaxed)}; + Picture *vp{&mPictQ[write_idx]}; + { std::unique_lock lock{mPackets.getMutex()}; AVPacket *lastpkt{}; @@ -1342,19 +1344,22 @@ int VideoState::handler() /* Put the frame in the queue to be loaded into a texture and displayed * by the rendering thread. */ - std::unique_lock lock{mPictQMutex}; - mPictQWrite = (mPictQWrite+1)%mPictQ.size(); - ++mPictQSize; + write_idx = (write_idx+1)%mPictQ.size(); + mPictQWrite.store(write_idx, std::memory_order_release); - /* Wait until we have space for a new pic */ - while(mPictQSize >= (mPictQ.size()-1) && !mMovie.mQuit.load(std::memory_order_relaxed)) - mPictQCond.wait(lock); + if(write_idx == mPictQRead.load(std::memory_order_acquire)) + { + /* Wait until we have space for a new pic */ + std::unique_lock lock{mPictQMutex}; + while(write_idx == mPictQRead.load(std::memory_order_acquire) && + !mMovie.mQuit.load(std::memory_order_relaxed)) + mPictQCond.wait(lock); + } } mEOS = true; std::unique_lock lock{mPictQMutex}; - while(!mFinalUpdate) - mPictQCond.wait(lock); + while(!mFinalUpdate) mPictQCond.wait(lock); return 0; } @@ -1655,7 +1660,8 @@ int main(int argc, char *argv[]) return 1; } - { auto device = alcGetContextsDevice(alcGetCurrentContext()); + { + auto device = alcGetContextsDevice(alcGetCurrentContext()); if(alcIsExtensionPresent(device, "ALC_SOFT_device_clock")) { std::cout<< "Found ALC_SOFT_device_clock" <(movState->getDuration()); - std::cout<< "\r "< Date: Tue, 16 Jul 2019 20:20:25 -0700 Subject: Receive video frames in a loop --- examples/alffplay.cpp | 90 ++++++++++++++++++++++++++++----------------------- 1 file changed, 50 insertions(+), 40 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index ccdfd51f..466c4576 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -552,19 +552,21 @@ int AudioState::decodeFrame() AVPacket *lastpkt{}; while((lastpkt=mPackets.getPacket(lock)) != nullptr) { - int ret{avcodec_send_packet(mCodecCtx.get(), lastpkt)}; + const int ret{avcodec_send_packet(mCodecCtx.get(), lastpkt)}; if(ret == AVERROR(EAGAIN)) break; + if(ret < 0) + std::cerr<< "Failed to send packet: "<nb_samples <= 0) @@ -1179,7 +1181,7 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) mFinalUpdate = true; mPictQRead.store(read_idx, std::memory_order_release); std::unique_lock{mPictQMutex}.unlock(); - mPictQCond.notify_all(); + mPictQCond.notify_one(); return; } @@ -1187,7 +1189,7 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) { mPictQRead.store(read_idx, std::memory_order_release); std::unique_lock{mPictQMutex}.unlock(); - mPictQCond.notify_all(); + mPictQCond.notify_one(); /* allocate or resize the buffer! */ bool fmt_updated{false}; @@ -1287,7 +1289,7 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) { mFinalUpdate = true; std::unique_lock{mPictQMutex}.unlock(); - mPictQCond.notify_all(); + mPictQCond.notify_one(); } } } @@ -1305,57 +1307,65 @@ int VideoState::handler() while(!mMovie.mQuit.load(std::memory_order_relaxed)) { - size_t write_idx{mPictQWrite.load(std::memory_order_relaxed)}; - Picture *vp{&mPictQ[write_idx]}; - { std::unique_lock lock{mPackets.getMutex()}; AVPacket *lastpkt{}; while((lastpkt=mPackets.getPacket(lock)) != nullptr) { - int ret{avcodec_send_packet(mCodecCtx.get(), lastpkt)}; + const int ret{avcodec_send_packet(mCodecCtx.get(), lastpkt)}; if(ret == AVERROR(EAGAIN)) break; + if(ret < 0) + std::cerr<< "Failed to send packet: "<mFrame.get()}; - int ret{avcodec_receive_frame(mCodecCtx.get(), decoded_frame)}; - if(ret == AVERROR_EOF) break; - if(ret < 0) + + while(!mMovie.mQuit.load(std::memory_order_relaxed)) { - std::cerr<< "Failed to decode frame: "<mFrame.get()}; + const int ret{avcodec_receive_frame(mCodecCtx.get(), decoded_frame)}; + if(ret == AVERROR_EOF) goto finished; + if(ret == AVERROR(EAGAIN)) break; + if(ret < 0) + { + std::cerr<< "Failed to receive frame: "<best_effort_timestamp != AV_NOPTS_VALUE) - mCurrentPts = std::chrono::duration_cast( - seconds_d64{av_q2d(mStream->time_base)*decoded_frame->best_effort_timestamp}); - vp->mPts = mCurrentPts; + /* Get the PTS for this frame. */ + if(decoded_frame->best_effort_timestamp != AV_NOPTS_VALUE) + mCurrentPts = std::chrono::duration_cast( + seconds_d64{av_q2d(mStream->time_base)*decoded_frame->best_effort_timestamp}); + vp->mPts = mCurrentPts; - /* Update the video clock to the next expected PTS. */ - auto frame_delay = av_q2d(mCodecCtx->time_base); - frame_delay += decoded_frame->repeat_pict * (frame_delay * 0.5); - mCurrentPts += std::chrono::duration_cast(seconds_d64{frame_delay}); + /* Update the video clock to the next expected PTS. */ + auto frame_delay = av_q2d(mCodecCtx->time_base); + frame_delay += decoded_frame->repeat_pict * (frame_delay * 0.5); + mCurrentPts += std::chrono::duration_cast(seconds_d64{frame_delay}); - /* Put the frame in the queue to be loaded into a texture and displayed - * by the rendering thread. - */ - write_idx = (write_idx+1)%mPictQ.size(); - mPictQWrite.store(write_idx, std::memory_order_release); + /* Put the frame in the queue to be loaded into a texture and + * displayed by the rendering thread. + */ + write_idx = (write_idx+1)%mPictQ.size(); + mPictQWrite.store(write_idx, std::memory_order_release); - if(write_idx == mPictQRead.load(std::memory_order_acquire)) - { - /* Wait until we have space for a new pic */ - std::unique_lock lock{mPictQMutex}; - while(write_idx == mPictQRead.load(std::memory_order_acquire) && - !mMovie.mQuit.load(std::memory_order_relaxed)) - mPictQCond.wait(lock); + if(write_idx == mPictQRead.load(std::memory_order_acquire)) + { + /* Wait until we have space for a new pic */ + std::unique_lock lock{mPictQMutex}; + while(write_idx == mPictQRead.load(std::memory_order_acquire) && + !mMovie.mQuit.load(std::memory_order_relaxed)) + mPictQCond.wait(lock); + } } } +finished: mEOS = true; std::unique_lock lock{mPictQMutex}; -- cgit v1.2.3 From 9959d661a02b8d140dfc43b2aa1c6bfa40a5af18 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Fri, 19 Jul 2019 22:55:20 -0700 Subject: Restructure codec send/receive calls In particular, after an initial fill of the codec's internal buffer, each receive_frame call is followed by one or more send_packet calls. For asynchronous codecs, this has the effect of letting the codec work while the handler thread is waiting for an AVFrame structure to become available or waiting for more decoded data to be needed. For synchronous codecs, this makes the send_packet calls use up time that would be spent waiting. --- examples/alffplay.cpp | 139 +++++++++++++++++++++++--------------------------- 1 file changed, 64 insertions(+), 75 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 466c4576..1f2c7d6c 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -188,6 +188,21 @@ class PacketQueue { size_t mTotalSize{0}; bool mFinished{false}; + AVPacket *getPacket(std::unique_lock &lock) + { + while(mPackets.empty() && !mFinished) + mCondVar.wait(lock); + return mPackets.empty() ? nullptr : &mPackets.front(); + } + + void pop() + { + AVPacket *pkt = &mPackets.front(); + mTotalSize -= pkt->size; + av_packet_unref(pkt); + mPackets.pop_front(); + } + public: ~PacketQueue() { @@ -197,6 +212,22 @@ public: mTotalSize = 0; } + void sendTo(AVCodecContext *codecctx) + { + std::unique_lock lock{mMutex}; + AVPacket *lastpkt{}; + while((lastpkt=getPacket(lock)) != nullptr) + { + const int ret{avcodec_send_packet(codecctx, lastpkt)}; + if(ret == AVERROR(EAGAIN)) return; + if(ret < 0) + std::cerr<< "Failed to send packet: "< &lock) - { - while(mPackets.empty() && !mFinished) - mCondVar.wait(lock); - return mPackets.empty() ? nullptr : &mPackets.front(); - } - bool put(const AVPacket *pkt) { { @@ -232,16 +256,6 @@ public: mCondVar.notify_one(); return true; } - - void pop() - { - AVPacket *pkt = &mPackets.front(); - mTotalSize -= pkt->size; - av_packet_unref(pkt); - mPackets.pop_front(); - } - - std::mutex &getMutex() noexcept { return mMutex; } }; @@ -547,33 +561,21 @@ int AudioState::decodeFrame() { while(!mMovie.mQuit.load(std::memory_order_relaxed)) { - { - std::unique_lock lock{mPackets.getMutex()}; - AVPacket *lastpkt{}; - while((lastpkt=mPackets.getPacket(lock)) != nullptr) - { - const int ret{avcodec_send_packet(mCodecCtx.get(), lastpkt)}; - if(ret == AVERROR(EAGAIN)) break; - if(ret < 0) - std::cerr<< "Failed to send packet: "<nb_samples <= 0) - { - av_frame_unref(mDecodedFrame.get()); continue; - } /* If provided, update w/ pts */ if(mDecodedFrame->best_effort_timestamp != AV_NOPTS_VALUE) @@ -1006,6 +1008,9 @@ int AudioState::handler() #endif samples = av_malloc(buffer_len); + /* Prefill the codec buffer. */ + mPackets.sendTo(mCodecCtx.get()); + srclock.lock(); while(alGetError() == AL_NO_ERROR && !mMovie.mQuit.load(std::memory_order_relaxed) && mConnected.test_and_set(std::memory_order_relaxed)) @@ -1305,39 +1310,20 @@ int VideoState::handler() [](Picture &pict) -> void { pict.mFrame = AVFramePtr{av_frame_alloc()}; }); + /* Prefill the codec buffer. */ + mPackets.sendTo(mCodecCtx.get()); + while(!mMovie.mQuit.load(std::memory_order_relaxed)) { - { - std::unique_lock lock{mPackets.getMutex()}; - AVPacket *lastpkt{}; - while((lastpkt=mPackets.getPacket(lock)) != nullptr) - { - const int ret{avcodec_send_packet(mCodecCtx.get(), lastpkt)}; - if(ret == AVERROR(EAGAIN)) break; - if(ret < 0) - std::cerr<< "Failed to send packet: "<mFrame.get()}; + const int ret{avcodec_receive_frame(mCodecCtx.get(), decoded_frame)}; + if(ret == AVERROR_EOF) break; + if(ret == 0) { - size_t write_idx{mPictQWrite.load(std::memory_order_relaxed)}; - Picture *vp{&mPictQ[write_idx]}; - - /* Decode video frame. */ - AVFrame *decoded_frame{vp->mFrame.get()}; - const int ret{avcodec_receive_frame(mCodecCtx.get(), decoded_frame)}; - if(ret == AVERROR_EOF) goto finished; - if(ret == AVERROR(EAGAIN)) break; - if(ret < 0) - { - std::cerr<< "Failed to receive frame: "<best_effort_timestamp != AV_NOPTS_VALUE) mCurrentPts = std::chrono::duration_cast( @@ -1354,18 +1340,21 @@ int VideoState::handler() */ write_idx = (write_idx+1)%mPictQ.size(); mPictQWrite.store(write_idx, std::memory_order_release); + } + else if(ret != AVERROR(EAGAIN)) + std::cerr<< "Failed to receive frame: "< lock{mPictQMutex}; - while(write_idx == mPictQRead.load(std::memory_order_acquire) && - !mMovie.mQuit.load(std::memory_order_relaxed)) - mPictQCond.wait(lock); - } + mPackets.sendTo(mCodecCtx.get()); + + if(write_idx == mPictQRead.load(std::memory_order_acquire)) + { + /* Wait until we have space for a new pic */ + std::unique_lock lock{mPictQMutex}; + while(write_idx == mPictQRead.load(std::memory_order_acquire) && + !mMovie.mQuit.load(std::memory_order_relaxed)) + mPictQCond.wait(lock); } } -finished: mEOS = true; std::unique_lock lock{mPictQMutex}; -- cgit v1.2.3 From f0ed35d3d0fb35a9ff0dbcecc90d5c75a7618ca1 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 20 Jul 2019 01:10:14 -0700 Subject: Set the initial clock time closer to starting playback --- examples/alffplay.cpp | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 1f2c7d6c..063ea157 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -748,19 +748,10 @@ void AL_APIENTRY AudioState::EventCallback(ALenum eventType, ALuint object, ALui int AudioState::handler() { - std::unique_lock srclock{mSrcMutex}; + std::unique_lock srclock{mSrcMutex, std::defer_lock}; milliseconds sleep_time{AudioBufferTime / 3}; ALenum fmt; - if(alcGetInteger64vSOFT) - { - int64_t devtime{}; - alcGetInteger64vSOFT(alcGetContextsDevice(alcGetCurrentContext()), ALC_DEVICE_CLOCK_SOFT, - 1, &devtime); - mDeviceStartTime = nanoseconds{devtime} - mCurrentPts; - } - srclock.unlock(); - #ifdef AL_SOFT_events const std::array evt_types{{ AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT, AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT, @@ -1012,6 +1003,13 @@ int AudioState::handler() mPackets.sendTo(mCodecCtx.get()); srclock.lock(); + if(alcGetInteger64vSOFT) + { + int64_t devtime{}; + alcGetInteger64vSOFT(alcGetContextsDevice(alcGetCurrentContext()), ALC_DEVICE_CLOCK_SOFT, + 1, &devtime); + mDeviceStartTime = nanoseconds{devtime} - mCurrentPts; + } while(alGetError() == AL_NO_ERROR && !mMovie.mQuit.load(std::memory_order_relaxed) && mConnected.test_and_set(std::memory_order_relaxed)) { @@ -1301,11 +1299,6 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) int VideoState::handler() { - { - std::lock_guard _{mDispPtsMutex}; - mDisplayPtsTime = get_avtime(); - } - std::for_each(mPictQ.begin(), mPictQ.end(), [](Picture &pict) -> void { pict.mFrame = AVFramePtr{av_frame_alloc()}; }); @@ -1313,6 +1306,11 @@ int VideoState::handler() /* Prefill the codec buffer. */ mPackets.sendTo(mCodecCtx.get()); + { + std::lock_guard _{mDispPtsMutex}; + mDisplayPtsTime = get_avtime(); + } + while(!mMovie.mQuit.load(std::memory_order_relaxed)) { size_t write_idx{mPictQWrite.load(std::memory_order_relaxed)}; -- cgit v1.2.3 From 8a9434c6238344e676e6defb74cea6bf6d62d401 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 20 Jul 2019 18:46:43 -0700 Subject: Use a local variable to track the decoded pts --- examples/alffplay.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 063ea157..62c1a908 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -345,8 +345,6 @@ struct VideoState { PacketQueue<14*1024*1024> mPackets; - /* The expected pts of the next frame to decode. */ - nanoseconds mCurrentPts{0}; /* The pts of the currently displayed frame, and the time (av_gettime) it * was last updated - used to have running video pts */ @@ -1311,12 +1309,13 @@ int VideoState::handler() mDisplayPtsTime = get_avtime(); } + auto current_pts = nanoseconds::zero(); while(!mMovie.mQuit.load(std::memory_order_relaxed)) { size_t write_idx{mPictQWrite.load(std::memory_order_relaxed)}; Picture *vp{&mPictQ[write_idx]}; - /* Decode video frame. */ + /* Retrieve video frame. */ AVFrame *decoded_frame{vp->mFrame.get()}; const int ret{avcodec_receive_frame(mCodecCtx.get(), decoded_frame)}; if(ret == AVERROR_EOF) break; @@ -1324,14 +1323,14 @@ int VideoState::handler() { /* Get the PTS for this frame. */ if(decoded_frame->best_effort_timestamp != AV_NOPTS_VALUE) - mCurrentPts = std::chrono::duration_cast( + current_pts = std::chrono::duration_cast( seconds_d64{av_q2d(mStream->time_base)*decoded_frame->best_effort_timestamp}); - vp->mPts = mCurrentPts; + vp->mPts = current_pts; /* Update the video clock to the next expected PTS. */ auto frame_delay = av_q2d(mCodecCtx->time_base); frame_delay += decoded_frame->repeat_pict * (frame_delay * 0.5); - mCurrentPts += std::chrono::duration_cast(seconds_d64{frame_delay}); + current_pts += std::chrono::duration_cast(seconds_d64{frame_delay}); /* Put the frame in the queue to be loaded into a texture and * displayed by the rendering thread. -- cgit v1.2.3 From b8ac4b79e43d3ae60926f5aad7125d10b2d78ea7 Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 23 Jul 2019 02:19:02 -0700 Subject: Only send packets as needed --- examples/alffplay.cpp | 88 ++++++++++++++++++++++++++++----------------------- 1 file changed, 49 insertions(+), 39 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index 62c1a908..fbbbdf89 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -212,20 +212,21 @@ public: mTotalSize = 0; } - void sendTo(AVCodecContext *codecctx) + int sendTo(AVCodecContext *codecctx) { std::unique_lock lock{mMutex}; - AVPacket *lastpkt{}; - while((lastpkt=getPacket(lock)) != nullptr) + + AVPacket *pkt{getPacket(lock)}; + if(!pkt) return avcodec_send_packet(codecctx, nullptr); + + const int ret{avcodec_send_packet(codecctx, pkt)}; + if(ret != AVERROR(EAGAIN)) { - const int ret{avcodec_send_packet(codecctx, lastpkt)}; - if(ret == AVERROR(EAGAIN)) return; if(ret < 0) std::cerr<< "Failed to send packet: "<nb_samples <= 0) continue; @@ -998,7 +996,11 @@ int AudioState::handler() samples = av_malloc(buffer_len); /* Prefill the codec buffer. */ - mPackets.sendTo(mCodecCtx.get()); + do { + const int ret{mPackets.sendTo(mCodecCtx.get())}; + if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) + break; + } while(1); srclock.lock(); if(alcGetInteger64vSOFT) @@ -1302,7 +1304,11 @@ int VideoState::handler() { pict.mFrame = AVFramePtr{av_frame_alloc()}; }); /* Prefill the codec buffer. */ - mPackets.sendTo(mCodecCtx.get()); + do { + const int ret{mPackets.sendTo(mCodecCtx.get())}; + if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) + break; + } while(1); { std::lock_guard _{mDispPtsMutex}; @@ -1317,30 +1323,34 @@ int VideoState::handler() /* Retrieve video frame. */ AVFrame *decoded_frame{vp->mFrame.get()}; - const int ret{avcodec_receive_frame(mCodecCtx.get(), decoded_frame)}; - if(ret == AVERROR_EOF) break; - if(ret == 0) + int ret; + while((ret=avcodec_receive_frame(mCodecCtx.get(), decoded_frame)) == AVERROR(EAGAIN)) + mPackets.sendTo(mCodecCtx.get()); + if(ret != 0) { - /* Get the PTS for this frame. */ - if(decoded_frame->best_effort_timestamp != AV_NOPTS_VALUE) - current_pts = std::chrono::duration_cast( - seconds_d64{av_q2d(mStream->time_base)*decoded_frame->best_effort_timestamp}); - vp->mPts = current_pts; - - /* Update the video clock to the next expected PTS. */ - auto frame_delay = av_q2d(mCodecCtx->time_base); - frame_delay += decoded_frame->repeat_pict * (frame_delay * 0.5); - current_pts += std::chrono::duration_cast(seconds_d64{frame_delay}); - - /* Put the frame in the queue to be loaded into a texture and - * displayed by the rendering thread. - */ - write_idx = (write_idx+1)%mPictQ.size(); - mPictQWrite.store(write_idx, std::memory_order_release); - } - else if(ret != AVERROR(EAGAIN)) + if(ret == AVERROR_EOF) break; std::cerr<< "Failed to receive frame: "<best_effort_timestamp != AV_NOPTS_VALUE) + current_pts = std::chrono::duration_cast( + seconds_d64{av_q2d(mStream->time_base)*decoded_frame->best_effort_timestamp}); + vp->mPts = current_pts; + + /* Update the video clock to the next expected PTS. */ + auto frame_delay = av_q2d(mCodecCtx->time_base); + frame_delay += decoded_frame->repeat_pict * (frame_delay * 0.5); + current_pts += std::chrono::duration_cast(seconds_d64{frame_delay}); + + /* Put the frame in the queue to be loaded into a texture and displayed + * by the rendering thread. + */ + write_idx = (write_idx+1)%mPictQ.size(); + mPictQWrite.store(write_idx, std::memory_order_release); + /* Send a packet now so it's hopefully ready by the time it's needed. */ mPackets.sendTo(mCodecCtx.get()); if(write_idx == mPictQRead.load(std::memory_order_acquire)) -- cgit v1.2.3 From 18f1139de86a5e961e65ae562b0a1106828b21ab Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Tue, 23 Jul 2019 12:51:14 -0700 Subject: Only redraw the image when necessary --- examples/alffplay.cpp | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index fbbbdf89..b532d8cd 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -383,7 +383,7 @@ struct VideoState { nanoseconds getClock(); void display(SDL_Window *screen, SDL_Renderer *renderer); - void updateVideo(SDL_Window *screen, SDL_Renderer *renderer); + void updateVideo(SDL_Window *screen, SDL_Renderer *renderer, bool redraw); int handler(); }; @@ -1158,7 +1158,7 @@ void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer) * handles updating the textures of decoded frames and displaying the latest * frame. */ -void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) +void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer, bool redraw) { size_t read_idx{mPictQRead.load(std::memory_order_relaxed)}; Picture *vp{&mPictQ[read_idx]}; @@ -1273,10 +1273,15 @@ void VideoState::updateVideo(SDL_Window *screen, SDL_Renderer *renderer) SDL_UnlockTexture(mImage); } } + + redraw = true; } - /* Show the picture! */ - display(screen, renderer); + if(redraw) + { + /* Show the picture! */ + display(screen, renderer); + } if(updated) { @@ -1766,6 +1771,7 @@ int main(int argc, char *argv[]) last_time = cur_time; } + bool force_redraw{false}; if(have_evt) do { switch(event.type) { @@ -1793,6 +1799,11 @@ int main(int argc, char *argv[]) case SDL_WINDOWEVENT_RESIZED: SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderFillRect(renderer, nullptr); + force_redraw = true; + break; + + case SDL_WINDOWEVENT_EXPOSED: + force_redraw = true; break; default: @@ -1841,7 +1852,7 @@ int main(int argc, char *argv[]) } } while(SDL_PollEvent(&event)); - movState->mVideo.updateVideo(screen, renderer); + movState->mVideo.updateVideo(screen, renderer, force_redraw); } std::cerr<< "SDL_WaitEvent error - "< Date: Fri, 26 Jul 2019 03:44:46 -0700 Subject: Increase the video picture queue size to 24 --- examples/alffplay.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index b532d8cd..eb5004c6 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -120,7 +120,7 @@ LPALEVENTCALLBACKSOFT alEventCallbackSOFT; const seconds AVNoSyncThreshold{10}; const milliseconds VideoSyncThreshold{10}; -#define VIDEO_PICTURE_QUEUE_SIZE 16 +#define VIDEO_PICTURE_QUEUE_SIZE 24 const seconds_d64 AudioSyncThreshold{0.03}; const milliseconds AudioSampleCorrectionMax{50}; -- cgit v1.2.3 From 40e937c63a2a74ef2ff94ba8a056cce0a07832ed Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Mon, 29 Jul 2019 08:16:39 -0700 Subject: Cleanup the examples' includes --- examples/alffplay.cpp | 31 +++++++++++++++++++++++-------- examples/alhrtf.c | 7 +++++-- examples/allatency.c | 5 +++-- examples/alloopback.c | 7 +++++-- examples/almultireverb.c | 9 ++++++--- examples/alplay.c | 5 +++-- examples/alrecord.c | 1 - examples/alreverb.c | 6 ++++-- examples/alstream.c | 7 +++---- examples/common/alhelpers.c | 6 ++---- examples/common/alhelpers.h | 2 -- 11 files changed, 54 insertions(+), 32 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index eb5004c6..cdb228e1 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -8,29 +8,44 @@ #include #include #include +#include #include +#include #include -#include -#include -#include +#include #include +#include +#include +#include +#include +#include +#include #include -#include -#include #include #include -#include +#include +#include +#include extern "C" { #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #include "libavformat/avio.h" -#include "libavutil/time.h" +#include "libavformat/version.h" +#include "libavutil/avutil.h" +#include "libavutil/error.h" +#include "libavutil/frame.h" +#include "libavutil/mem.h" #include "libavutil/pixfmt.h" -#include "libavutil/avstring.h" +#include "libavutil/rational.h" +#include "libavutil/samplefmt.h" +#include "libavutil/time.h" +#include "libavutil/version.h" #include "libavutil/channel_layout.h" #include "libswscale/swscale.h" #include "libswresample/swresample.h" + +struct SwsContext; } #include "SDL.h" diff --git a/examples/alhrtf.c b/examples/alhrtf.c index f9150ae1..96cf0255 100644 --- a/examples/alhrtf.c +++ b/examples/alhrtf.c @@ -24,11 +24,14 @@ /* This file contains an example for selecting an HRTF. */ -#include #include #include +#include +#include -#include +#include "SDL_sound.h" +#include "SDL_audio.h" +#include "SDL_stdinc.h" #include "AL/al.h" #include "AL/alc.h" diff --git a/examples/allatency.c b/examples/allatency.c index d561373f..2bc76289 100644 --- a/examples/allatency.c +++ b/examples/allatency.c @@ -27,10 +27,11 @@ #include #include -#include +#include "SDL_sound.h" +#include "SDL_audio.h" +#include "SDL_stdinc.h" #include "AL/al.h" -#include "AL/alc.h" #include "AL/alext.h" #include "common/alhelpers.h" diff --git a/examples/alloopback.c b/examples/alloopback.c index 16553f9b..313b89d5 100644 --- a/examples/alloopback.c +++ b/examples/alloopback.c @@ -26,11 +26,14 @@ * output handling. */ -#include #include #include +#include -#include +#include "SDL.h" +#include "SDL_audio.h" +#include "SDL_error.h" +#include "SDL_stdinc.h" #include "AL/al.h" #include "AL/alc.h" diff --git a/examples/almultireverb.c b/examples/almultireverb.c index f1b1872f..efd3bf16 100644 --- a/examples/almultireverb.c +++ b/examples/almultireverb.c @@ -29,15 +29,18 @@ * listener. */ -#include #include #include +#include +#include -#include +#include "SDL_sound.h" +#include "SDL_audio.h" +#include "SDL_stdinc.h" #include "AL/al.h" #include "AL/alc.h" -#include "AL/alext.h" +#include "AL/efx.h" #include "AL/efx-presets.h" #include "common/alhelpers.h" diff --git a/examples/alplay.c b/examples/alplay.c index 81cb56d5..4ff8fb7f 100644 --- a/examples/alplay.c +++ b/examples/alplay.c @@ -27,10 +27,11 @@ #include #include -#include +#include "SDL_sound.h" +#include "SDL_audio.h" +#include "SDL_stdinc.h" #include "AL/al.h" -#include "AL/alc.h" #include "common/alhelpers.h" diff --git a/examples/alrecord.c b/examples/alrecord.c index c4984f99..d65414c9 100644 --- a/examples/alrecord.c +++ b/examples/alrecord.c @@ -28,7 +28,6 @@ #include #include #include -#include #include "AL/al.h" #include "AL/alc.h" diff --git a/examples/alreverb.c b/examples/alreverb.c index e6c9e606..e1d3c207 100644 --- a/examples/alreverb.c +++ b/examples/alreverb.c @@ -27,11 +27,13 @@ #include #include -#include +#include "SDL_sound.h" +#include "SDL_audio.h" +#include "SDL_stdinc.h" #include "AL/al.h" #include "AL/alc.h" -#include "AL/alext.h" +#include "AL/efx.h" #include "AL/efx-presets.h" #include "common/alhelpers.h" diff --git a/examples/alstream.c b/examples/alstream.c index 68115e8d..cb447355 100644 --- a/examples/alstream.c +++ b/examples/alstream.c @@ -27,14 +27,13 @@ #include #include #include -#include #include -#include +#include "SDL_sound.h" +#include "SDL_audio.h" +#include "SDL_stdinc.h" #include "AL/al.h" -#include "AL/alc.h" -#include "AL/alext.h" #include "common/alhelpers.h" diff --git a/examples/common/alhelpers.c b/examples/common/alhelpers.c index 3077d0b7..b387fd2d 100644 --- a/examples/common/alhelpers.c +++ b/examples/common/alhelpers.c @@ -28,16 +28,14 @@ * finding an appropriate buffer format, and getting readable strings for * channel configs and sample types. */ -#include +#include "alhelpers.h" + #include #include #include #include "AL/al.h" #include "AL/alc.h" -#include "AL/alext.h" - -#include "alhelpers.h" /* InitAL opens a device and sets up a context using default attributes, making diff --git a/examples/common/alhelpers.h b/examples/common/alhelpers.h index 5caeda38..3752d218 100644 --- a/examples/common/alhelpers.h +++ b/examples/common/alhelpers.h @@ -1,9 +1,7 @@ #ifndef ALHELPERS_H #define ALHELPERS_H -#include "AL/alc.h" #include "AL/al.h" -#include "AL/alext.h" #ifdef __cplusplus extern "C" { -- cgit v1.2.3 From 4c76f32ddac5145231609b1cb4f28028abed814b Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Thu, 12 Sep 2019 03:14:01 -0700 Subject: Avoid implicit conversions with the examples and utils --- examples/alffplay.cpp | 86 +++++++++++++++++++++++---------------------- examples/alhrtf.c | 13 ++++--- examples/allatency.c | 4 +-- examples/alloopback.c | 2 +- examples/almultireverb.c | 18 +++++----- examples/alplay.c | 4 +-- examples/alrecord.c | 24 ++++++------- examples/alreverb.c | 8 ++--- examples/alstream.c | 17 +++++---- examples/altonegen.c | 8 ++--- examples/common/alhelpers.c | 4 +-- utils/makemhr/loadsofa.cpp | 2 +- utils/openal-info.c | 2 +- 13 files changed, 99 insertions(+), 93 deletions(-) (limited to 'examples') diff --git a/examples/alffplay.cpp b/examples/alffplay.cpp index cdb228e1..655ffc96 100644 --- a/examples/alffplay.cpp +++ b/examples/alffplay.cpp @@ -213,7 +213,7 @@ class PacketQueue { void pop() { AVPacket *pkt = &mPackets.front(); - mTotalSize -= pkt->size; + mTotalSize -= static_cast(pkt->size); av_packet_unref(pkt); mPackets.pop_front(); } @@ -267,7 +267,7 @@ public: return true; } - mTotalSize += mPackets.back().size; + mTotalSize += static_cast(mPackets.back().size); } mCondVar.notify_one(); return true; @@ -299,7 +299,7 @@ struct AudioState { SwrContextPtr mSwresCtx; /* Conversion format, for what gets fed to OpenAL */ - int mDstChanLayout{0}; + uint64_t mDstChanLayout{0}; AVSampleFormat mDstSampleFmt{AV_SAMPLE_FMT_NONE}; /* Storage of converted samples */ @@ -310,14 +310,14 @@ struct AudioState { /* OpenAL format */ ALenum mFormat{AL_NONE}; - ALsizei mFrameSize{0}; + ALuint mFrameSize{0}; std::mutex mSrcMutex; std::condition_variable mSrcCond; std::atomic_flag mConnected; ALuint mSource{0}; std::vector mBuffers; - ALsizei mBufferIdx{0}; + ALuint mBufferIdx{0}; AudioState(MovieState &movie) : mMovie(movie) { mConnected.test_and_set(std::memory_order_relaxed); } @@ -326,7 +326,7 @@ struct AudioState { if(mSource) alDeleteSources(1, &mSource); if(!mBuffers.empty()) - alDeleteBuffers(mBuffers.size(), mBuffers.data()); + alDeleteBuffers(static_cast(mBuffers.size()), mBuffers.data()); av_freep(&mSamples); } @@ -348,7 +348,7 @@ struct AudioState { int getSync(); int decodeFrame(); - bool readAudio(uint8_t *samples, int length); + bool readAudio(uint8_t *samples, unsigned int length); int handler(); }; @@ -441,7 +441,7 @@ struct MovieState { nanoseconds getDuration(); - int streamComponentOpen(int stream_index); + int streamComponentOpen(unsigned int stream_index); int parse_handler(); }; @@ -618,17 +618,17 @@ int AudioState::decodeFrame() * multiple of the template type size. */ template -static void sample_dup(uint8_t *out, const uint8_t *in, int count, int frame_size) +static void sample_dup(uint8_t *out, const uint8_t *in, unsigned int count, size_t frame_size) { - const T *sample = reinterpret_cast(in); - T *dst = reinterpret_cast(out); + auto *sample = reinterpret_cast(in); + auto *dst = reinterpret_cast(out); if(frame_size == sizeof(T)) std::fill_n(dst, count, *sample); else { /* NOTE: frame_size is a multiple of sizeof(T). */ - int type_mult = frame_size / sizeof(T); - int i = 0; + size_t type_mult{frame_size / sizeof(T)}; + size_t i{0}; std::generate_n(dst, count*type_mult, [sample,type_mult,&i]() -> T { @@ -641,10 +641,10 @@ static void sample_dup(uint8_t *out, const uint8_t *in, int count, int frame_siz } -bool AudioState::readAudio(uint8_t *samples, int length) +bool AudioState::readAudio(uint8_t *samples, unsigned int length) { - int sample_skip = getSync(); - int audio_size = 0; + int sample_skip{getSync()}; + unsigned int audio_size{0}; /* Read the next chunk of data, refill the buffer, and queue it * on the source */ @@ -669,16 +669,17 @@ bool AudioState::readAudio(uint8_t *samples, int length) continue; } - int rem = length - audio_size; + unsigned int rem{length - audio_size}; if(mSamplesPos >= 0) { - int len = mSamplesLen - mSamplesPos; + const auto len = static_cast(mSamplesLen - mSamplesPos); if(rem > len) rem = len; - memcpy(samples, mSamples + mSamplesPos*mFrameSize, rem*mFrameSize); + std::copy_n(mSamples + static_cast(mSamplesPos)*mFrameSize, + rem*mFrameSize, samples); } else { - rem = std::min(rem, -mSamplesPos); + rem = std::min(rem, static_cast(-mSamplesPos)); /* Add samples by copying the first sample */ if((mFrameSize&7) == 0) @@ -692,7 +693,7 @@ bool AudioState::readAudio(uint8_t *samples, int length) } mSamplesPos += rem; - mCurrentPts += nanoseconds(seconds(rem)) / mCodecCtx->sample_rate; + mCurrentPts += nanoseconds{seconds{rem}} / mCodecCtx->sample_rate; samples += rem*mFrameSize; audio_size += rem; } @@ -701,10 +702,10 @@ bool AudioState::readAudio(uint8_t *samples, int length) if(audio_size < length) { - int rem = length - audio_size; + const unsigned int rem{length - audio_size}; std::fill_n(samples, rem*mFrameSize, (mDstSampleFmt == AV_SAMPLE_FMT_U8) ? 0x80 : 0x00); - mCurrentPts += nanoseconds(seconds(rem)) / mCodecCtx->sample_rate; + mCurrentPts += nanoseconds{seconds{rem}} / mCodecCtx->sample_rate; audio_size += rem; } return true; @@ -928,8 +929,8 @@ int AudioState::handler() } } void *samples{nullptr}; - ALsizei buffer_len = std::chrono::duration_cast>( - mCodecCtx->sample_rate * AudioBufferTime).count() * mFrameSize; + ALsizei buffer_len = static_cast(std::chrono::duration_cast( + mCodecCtx->sample_rate * AudioBufferTime).count() * mFrameSize); mSamples = nullptr; mSamplesMax = 0; @@ -968,9 +969,9 @@ int AudioState::handler() } else mSwresCtx.reset(swr_alloc_set_opts(nullptr, - mDstChanLayout, mDstSampleFmt, mCodecCtx->sample_rate, - mCodecCtx->channel_layout ? mCodecCtx->channel_layout : - static_cast(av_get_default_channel_layout(mCodecCtx->channels)), + static_cast(mDstChanLayout), mDstSampleFmt, mCodecCtx->sample_rate, + mCodecCtx->channel_layout ? static_cast(mCodecCtx->channel_layout) : + av_get_default_channel_layout(mCodecCtx->channels), mCodecCtx->sample_fmt, mCodecCtx->sample_rate, 0, nullptr)); if(!mSwresCtx || swr_init(mSwresCtx.get()) != 0) @@ -980,7 +981,7 @@ int AudioState::handler() } mBuffers.assign(AudioBufferTotalTime / AudioBufferTime, 0); - alGenBuffers(mBuffers.size(), mBuffers.data()); + alGenBuffers(static_cast(mBuffers.size()), mBuffers.data()); alGenSources(1, &mSource); if(EnableDirectOut) @@ -1003,12 +1004,12 @@ int AudioState::handler() if(alGetError() != AL_NO_ERROR) { fprintf(stderr, "Failed to use mapped buffers\n"); - samples = av_malloc(buffer_len); + samples = av_malloc(static_cast(buffer_len)); } } else #endif - samples = av_malloc(buffer_len); + samples = av_malloc(static_cast(buffer_len)); /* Prefill the codec buffer. */ do { @@ -1053,14 +1054,15 @@ int AudioState::handler() { auto ptr = static_cast(alMapBufferSOFT(bufid, 0, buffer_len, AL_MAP_WRITE_BIT_SOFT)); - bool got_audio{readAudio(ptr, buffer_len)}; + bool got_audio{readAudio(ptr, static_cast(buffer_len))}; alUnmapBufferSOFT(bufid); if(!got_audio) break; } else #endif { - if(!readAudio(static_cast(samples), buffer_len)) + auto ptr = static_cast(samples); + if(!readAudio(ptr, static_cast(buffer_len))) break; alBufferData(bufid, mFormat, samples, buffer_len, mCodecCtx->sample_rate); } @@ -1138,27 +1140,27 @@ void VideoState::display(SDL_Window *screen, SDL_Renderer *renderer) if(!mImage) return; - float aspect_ratio; + double aspect_ratio; int win_w, win_h; int w, h, x, y; if(mCodecCtx->sample_aspect_ratio.num == 0) - aspect_ratio = 0.0f; + aspect_ratio = 0.0; else { aspect_ratio = av_q2d(mCodecCtx->sample_aspect_ratio) * mCodecCtx->width / mCodecCtx->height; } - if(aspect_ratio <= 0.0f) - aspect_ratio = static_cast(mCodecCtx->width) / static_cast(mCodecCtx->height); + if(aspect_ratio <= 0.0) + aspect_ratio = static_cast(mCodecCtx->width) / mCodecCtx->height; SDL_GetWindowSize(screen, &win_w, &win_h); h = win_h; - w = (static_cast(rint(h * aspect_ratio)) + 3) & ~3; + w = (static_cast(std::rint(h * aspect_ratio)) + 3) & ~3; if(w > win_w) { w = win_w; - h = (static_cast(rint(w / aspect_ratio)) + 3) & ~3; + h = (static_cast(std::rint(w / aspect_ratio)) + 3) & ~3; } x = (win_w - w) / 2; y = (win_h - h) / 2; @@ -1460,9 +1462,9 @@ nanoseconds MovieState::getMasterClock() nanoseconds MovieState::getDuration() { return std::chrono::duration>(mFormatCtx->duration); } -int MovieState::streamComponentOpen(int stream_index) +int MovieState::streamComponentOpen(unsigned int stream_index) { - if(stream_index < 0 || static_cast(stream_index) >= mFormatCtx->nb_streams) + if(stream_index >= mFormatCtx->nb_streams) return -1; /* Get a pointer to the codec context for the stream, and open the @@ -1499,7 +1501,7 @@ int MovieState::streamComponentOpen(int stream_index) return -1; } - return stream_index; + return static_cast(stream_index); } int MovieState::parse_handler() diff --git a/examples/alhrtf.c b/examples/alhrtf.c index 96cf0255..f09f3e99 100644 --- a/examples/alhrtf.c +++ b/examples/alhrtf.c @@ -112,7 +112,7 @@ static ALuint LoadSound(const char *filename) * close the file. */ buffer = 0; alGenBuffers(1, &buffer); - alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate); + alBufferData(buffer, format, sample->buffer, (ALsizei)slen, (ALsizei)sample->actual.rate); Sound_FreeSample(sample); /* Check if an error occured, and clean up if so. */ @@ -132,6 +132,7 @@ static ALuint LoadSound(const char *filename) int main(int argc, char **argv) { ALCdevice *device; + ALCcontext *context; ALboolean has_angle_ext; ALuint source, buffer; const char *soundname; @@ -153,7 +154,8 @@ int main(int argc, char **argv) if(InitAL(&argv, &argc) != 0) return 1; - device = alcGetContextsDevice(alcGetCurrentContext()); + context = alcGetCurrentContext(); + device = alcGetContextsDevice(context); if(!alcIsExtensionPresent(device, "ALC_SOFT_HRTF")) { fprintf(stderr, "Error: ALC_SOFT_HRTF not supported\n"); @@ -171,7 +173,7 @@ int main(int argc, char **argv) * stereo sources. */ has_angle_ext = alIsExtensionPresent("AL_EXT_STEREO_ANGLES"); - printf("AL_EXT_STEREO_ANGLES%s found\n", has_angle_ext?"":" not"); + printf("AL_EXT_STEREO_ANGLES %sfound\n", has_angle_ext?"":"not "); /* Check for user-preferred HRTF */ if(strcmp(argv[0], "-hrtf") == 0) @@ -255,7 +257,7 @@ int main(int argc, char **argv) alGenSources(1, &source); alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE); alSource3f(source, AL_POSITION, 0.0f, 0.0f, -1.0f); - alSourcei(source, AL_BUFFER, buffer); + alSourcei(source, AL_BUFFER, (ALint)buffer); assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); /* Play the sound until it finishes. */ @@ -264,6 +266,8 @@ int main(int argc, char **argv) do { al_nssleep(10000000); + alcSuspendContext(context); + /* Rotate the source around the listener by about 1/4 cycle per second, * and keep it within -pi...+pi. */ @@ -282,6 +286,7 @@ int main(int argc, char **argv) ALfloat angles[2] = { (ALfloat)(M_PI/6.0 - angle), (ALfloat)(-M_PI/6.0 - angle) }; alSourcefv(source, AL_STEREO_ANGLES, angles); } + alcProcessContext(context); alGetSourcei(source, AL_SOURCE_STATE, &state); } while(alGetError() == AL_NO_ERROR && state == AL_PLAYING); diff --git a/examples/allatency.c b/examples/allatency.c index 2bc76289..ad700cc1 100644 --- a/examples/allatency.c +++ b/examples/allatency.c @@ -115,7 +115,7 @@ static ALuint LoadSound(const char *filename) * close the file. */ buffer = 0; alGenBuffers(1, &buffer); - alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate); + alBufferData(buffer, format, sample->buffer, (ALsizei)slen, (ALsizei)sample->actual.rate); Sound_FreeSample(sample); /* Check if an error occured, and clean up if so. */ @@ -188,7 +188,7 @@ int main(int argc, char **argv) /* Create the source to play the sound with. */ source = 0; alGenSources(1, &source); - alSourcei(source, AL_BUFFER, buffer); + alSourcei(source, AL_BUFFER, (ALint)buffer); assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); /* Play the sound until it finishes. */ diff --git a/examples/alloopback.c b/examples/alloopback.c index 313b89d5..426a2af9 100644 --- a/examples/alloopback.c +++ b/examples/alloopback.c @@ -249,7 +249,7 @@ int main(int argc, char *argv[]) /* Create the source to play the sound with. */ source = 0; alGenSources(1, &source); - alSourcei(source, AL_BUFFER, buffer); + alSourcei(source, AL_BUFFER, (ALint)buffer); assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); /* Play the sound until it finishes. */ diff --git a/examples/almultireverb.c b/examples/almultireverb.c index efd3bf16..b967a050 100644 --- a/examples/almultireverb.c +++ b/examples/almultireverb.c @@ -211,7 +211,7 @@ static ALuint LoadSound(const char *filename) * close the file. */ buffer = 0; alGenBuffers(1, &buffer); - alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate); + alBufferData(buffer, format, sample->buffer, (ALsizei)slen, (ALsizei)sample->actual.rate); Sound_FreeSample(sample); /* Check if an error occured, and clean up if so. */ @@ -443,8 +443,8 @@ static void UpdateListenerAndEffects(float timediff, const ALuint slots[2], cons } /* Finally, update the effect slots with the updated effect parameters. */ - alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, effects[0]); - alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, effects[1]); + alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]); + alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]); } @@ -598,8 +598,8 @@ int main(int argc, char **argv) * effect properties. Modifying or deleting the effect object afterward * won't directly affect the effect slot until they're reapplied like this. */ - alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, effects[0]); - alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, effects[1]); + alAuxiliaryEffectSloti(slots[0], AL_EFFECTSLOT_EFFECT, (ALint)effects[0]); + alAuxiliaryEffectSloti(slots[1], AL_EFFECTSLOT_EFFECT, (ALint)effects[1]); assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot"); /* For the purposes of this example, prepare a filter that optionally @@ -621,8 +621,8 @@ int main(int argc, char **argv) alGenSources(1, &source); alSourcei(source, AL_LOOPING, AL_TRUE); alSource3f(source, AL_POSITION, -5.0f, 0.0f, -2.0f); - alSourcei(source, AL_DIRECT_FILTER, direct_filter); - alSourcei(source, AL_BUFFER, buffer); + alSourcei(source, AL_DIRECT_FILTER, (ALint)direct_filter); + alSourcei(source, AL_BUFFER, (ALint)buffer); /* Connect the source to the effect slots. Here, we connect source send 0 * to Zone 0's slot, and send 1 to Zone 1's slot. Filters can be specified @@ -631,8 +631,8 @@ int main(int argc, char **argv) * can only see a zone through a window or thin wall may be attenuated for * that zone. */ - alSource3i(source, AL_AUXILIARY_SEND_FILTER, slots[0], 0, AL_FILTER_NULL); - alSource3i(source, AL_AUXILIARY_SEND_FILTER, slots[1], 1, AL_FILTER_NULL); + alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[0], 0, AL_FILTER_NULL); + alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slots[1], 1, AL_FILTER_NULL); assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); /* Get the current time as the base for timing in the main loop. */ diff --git a/examples/alplay.c b/examples/alplay.c index 4ff8fb7f..09ad96b4 100644 --- a/examples/alplay.c +++ b/examples/alplay.c @@ -101,7 +101,7 @@ static ALuint LoadSound(const char *filename) * close the file. */ buffer = 0; alGenBuffers(1, &buffer); - alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate); + alBufferData(buffer, format, sample->buffer, (ALsizei)slen, (ALsizei)sample->actual.rate); Sound_FreeSample(sample); /* Check if an error occured, and clean up if so. */ @@ -151,7 +151,7 @@ int main(int argc, char **argv) /* Create the source to play the sound with. */ source = 0; alGenSources(1, &source); - alSourcei(source, AL_BUFFER, buffer); + alSourcei(source, AL_BUFFER, (ALint)buffer); assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); /* Play the sound until it finishes. */ diff --git a/examples/alrecord.c b/examples/alrecord.c index d65414c9..627f8540 100644 --- a/examples/alrecord.c +++ b/examples/alrecord.c @@ -73,9 +73,9 @@ typedef struct Recorder { ALuint mDataSize; float mRecTime; - int mChannels; - int mBits; - int mSampleRate; + ALuint mChannels; + ALuint mBits; + ALuint mSampleRate; ALuint mFrameSize; ALbyte *mBuffer; ALsizei mBufferSize; @@ -139,7 +139,7 @@ int main(int argc, char **argv) return 1; } - recorder.mChannels = strtol(argv[1], &end, 0); + recorder.mChannels = (ALuint)strtoul(argv[1], &end, 0); if((recorder.mChannels != 1 && recorder.mChannels != 2) || (end && *end != '\0')) { fprintf(stderr, "Invalid channels: %s\n", argv[1]); @@ -156,7 +156,7 @@ int main(int argc, char **argv) return 1; } - recorder.mBits = strtol(argv[1], &end, 0); + recorder.mBits = (ALuint)strtoul(argv[1], &end, 0); if((recorder.mBits != 8 && recorder.mBits != 16 && recorder.mBits != 32) || (end && *end != '\0')) { @@ -174,7 +174,7 @@ int main(int argc, char **argv) return 1; } - recorder.mSampleRate = strtol(argv[1], &end, 0); + recorder.mSampleRate = (ALuint)strtoul(argv[1], &end, 0); if(!(recorder.mSampleRate >= 8000 && recorder.mSampleRate <= 96000) || (end && *end != '\0')) { fprintf(stderr, "Invalid sample rate: %s\n", argv[1]); @@ -285,15 +285,15 @@ int main(int argc, char **argv) // 16-bit val, format type id (1 = integer PCM, 3 = float PCM) fwrite16le((recorder.mBits == 32) ? 0x0003 : 0x0001, recorder.mFile); // 16-bit val, channel count - fwrite16le(recorder.mChannels, recorder.mFile); + fwrite16le((ALushort)recorder.mChannels, recorder.mFile); // 32-bit val, frequency fwrite32le(recorder.mSampleRate, recorder.mFile); // 32-bit val, bytes per second fwrite32le(recorder.mSampleRate * recorder.mFrameSize, recorder.mFile); // 16-bit val, frame size - fwrite16le(recorder.mFrameSize, recorder.mFile); + fwrite16le((ALushort)recorder.mFrameSize, recorder.mFile); // 16-bit val, bits per sample - fwrite16le(recorder.mBits, recorder.mFile); + fwrite16le((ALushort)recorder.mBits, recorder.mFile); // 16-bit val, extra byte count fwrite16le(0, recorder.mFile); @@ -331,7 +331,7 @@ int main(int argc, char **argv) } if(count > recorder.mBufferSize) { - ALbyte *data = calloc(recorder.mFrameSize, count); + ALbyte *data = calloc(recorder.mFrameSize, (ALuint)count); free(recorder.mBuffer); recorder.mBuffer = data; recorder.mBufferSize = count; @@ -365,7 +365,7 @@ int main(int argc, char **argv) } } #endif - recorder.mDataSize += (ALuint)fwrite(recorder.mBuffer, recorder.mFrameSize, count, + recorder.mDataSize += (ALuint)fwrite(recorder.mBuffer, recorder.mFrameSize, (ALuint)count, recorder.mFile); } alcCaptureStop(recorder.mDevice); @@ -385,7 +385,7 @@ int main(int argc, char **argv) { fwrite32le(recorder.mDataSize*recorder.mFrameSize, recorder.mFile); if(fseek(recorder.mFile, 4, SEEK_SET) == 0) - fwrite32le(total_size - 8, recorder.mFile); + fwrite32le((ALuint)total_size - 8, recorder.mFile); } fclose(recorder.mFile); diff --git a/examples/alreverb.c b/examples/alreverb.c index e1d3c207..68f0269f 100644 --- a/examples/alreverb.c +++ b/examples/alreverb.c @@ -209,7 +209,7 @@ static ALuint LoadSound(const char *filename) * close the file. */ buffer = 0; alGenBuffers(1, &buffer); - alBufferData(buffer, format, sample->buffer, slen, sample->actual.rate); + alBufferData(buffer, format, sample->buffer, (ALsizei)slen, (ALsizei)sample->actual.rate); Sound_FreeSample(sample); /* Check if an error occured, and clean up if so. */ @@ -309,18 +309,18 @@ int main(int argc, char **argv) * effectively copies the effect properties. You can modify or delete the * effect object afterward without affecting the effect slot. */ - alAuxiliaryEffectSloti(slot, AL_EFFECTSLOT_EFFECT, effect); + alAuxiliaryEffectSloti(slot, AL_EFFECTSLOT_EFFECT, (ALint)effect); assert(alGetError()==AL_NO_ERROR && "Failed to set effect slot"); /* Create the source to play the sound with. */ source = 0; alGenSources(1, &source); - alSourcei(source, AL_BUFFER, buffer); + alSourcei(source, AL_BUFFER, (ALint)buffer); /* Connect the source to the effect slot. This tells the source to use the * effect slot 'slot', on send #0 with the AL_FILTER_NULL filter object. */ - alSource3i(source, AL_AUXILIARY_SEND_FILTER, slot, 0, AL_FILTER_NULL); + alSource3i(source, AL_AUXILIARY_SEND_FILTER, (ALint)slot, 0, AL_FILTER_NULL); assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); /* Play the sound until it finishes. */ diff --git a/examples/alstream.c b/examples/alstream.c index cb447355..56505ddb 100644 --- a/examples/alstream.c +++ b/examples/alstream.c @@ -160,10 +160,10 @@ static int OpenPlayerFile(StreamPlayer *player, const char *filename) fprintf(stderr, "Unsupported channel count: %d\n", player->sample->actual.channels); goto error; } - player->srate = player->sample->actual.rate; + player->srate = (ALsizei)player->sample->actual.rate; frame_size = player->sample->actual.channels * - SDL_AUDIO_BITSIZE(player->sample->actual.format) / 8; + SDL_AUDIO_BITSIZE(player->sample->actual.format) / 8; /* Set the buffer size, given the desired millisecond length. */ Sound_SetBufferSize(player->sample, (Uint32)((Uint64)player->srate*BUFFER_TIME_MS/1000) * @@ -191,7 +191,7 @@ static void ClosePlayerFile(StreamPlayer *player) /* Prebuffers some audio from the file, and starts playing the source */ static int StartPlayer(StreamPlayer *player) { - size_t i; + ALsizei i; /* Rewind the source position and clear the buffer queue */ alSourceRewind(player->source); @@ -204,8 +204,8 @@ static int StartPlayer(StreamPlayer *player) Uint32 slen = Sound_Decode(player->sample); if(slen == 0) break; - alBufferData(player->buffers[i], player->format, - player->sample->buffer, slen, player->srate); + alBufferData(player->buffers[i], player->format, player->sample->buffer, (ALsizei)slen, + player->srate); } if(alGetError() != AL_NO_ERROR) { @@ -255,8 +255,8 @@ static int UpdatePlayer(StreamPlayer *player) slen = Sound_Decode(player->sample); if(slen > 0) { - alBufferData(bufid, player->format, player->sample->buffer, slen, - player->srate); + alBufferData(bufid, player->format, player->sample->buffer, (ALsizei)slen, + player->srate); alSourceQueueBuffers(player->source, 1, &bufid); } if(alGetError() != AL_NO_ERROR) @@ -323,8 +323,7 @@ int main(int argc, char **argv) else namepart = argv[i]; - printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format), - player->srate); + printf("Playing: %s (%s, %dhz)\n", namepart, FormatName(player->format), player->srate); fflush(stdout); if(!StartPlayer(player)) diff --git a/examples/altonegen.c b/examples/altonegen.c index 628e695d..aacc3496 100644 --- a/examples/altonegen.c +++ b/examples/altonegen.c @@ -91,7 +91,7 @@ static void ApplySin(ALfloat *data, ALdouble g, ALuint srate, ALuint freq) static ALuint CreateWave(enum WaveType type, ALuint freq, ALuint srate) { ALuint seed = 22222; - ALint data_size; + ALuint data_size; ALfloat *data; ALuint buffer; ALenum err; @@ -142,7 +142,7 @@ static ALuint CreateWave(enum WaveType type, ALuint freq, ALuint srate) /* Buffer the audio data into a new buffer object. */ buffer = 0; alGenBuffers(1, &buffer); - alBufferData(buffer, AL_FORMAT_MONO_FLOAT32, data, data_size, srate); + alBufferData(buffer, AL_FORMAT_MONO_FLOAT32, data, (ALsizei)data_size, (ALsizei)srate); free(data); /* Check if an error occured, and clean up if so. */ @@ -257,7 +257,7 @@ int main(int argc, char *argv[]) srate = dev_rate; /* Load the sound into a buffer. */ - buffer = CreateWave(wavetype, tone_freq, srate); + buffer = CreateWave(wavetype, (ALuint)tone_freq, (ALuint)srate); if(!buffer) { CloseAL(); @@ -271,7 +271,7 @@ int main(int argc, char *argv[]) /* Create the source to play the sound with. */ source = 0; alGenSources(1, &source); - alSourcei(source, AL_BUFFER, buffer); + alSourcei(source, AL_BUFFER, (ALint)buffer); assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source"); /* Play the sound for a while. */ diff --git a/examples/common/alhelpers.c b/examples/common/alhelpers.c index b387fd2d..730d2e13 100644 --- a/examples/common/alhelpers.c +++ b/examples/common/alhelpers.c @@ -159,12 +159,12 @@ int altime_get(void) struct timespec ts; int ret = clock_gettime(CLOCK_REALTIME, &ts); if(ret != 0) return 0; - cur_time = ts.tv_sec*1000 + ts.tv_nsec/1000000; + cur_time = (int)(ts.tv_sec*1000 + ts.tv_nsec/1000000); #else /* _POSIX_TIMERS > 0 */ struct timeval tv; int ret = gettimeofday(&tv, NULL); if(ret != 0) return 0; - cur_time = tv.tv_sec*1000 + tv.tv_usec/1000; + cur_time = (int)(tv.tv_sec*1000 + tv.tv_usec/1000); #endif if(!start_time) diff --git a/utils/makemhr/loadsofa.cpp b/utils/makemhr/loadsofa.cpp index e82376aa..02911e12 100644 --- a/utils/makemhr/loadsofa.cpp +++ b/utils/makemhr/loadsofa.cpp @@ -50,7 +50,7 @@ static const char *SofaErrorStr(int err) * of other axes as necessary. The epsilons are used to constrain the * equality of unique elements. */ -static uint GetUniquelySortedElems(const uint m, const float *triplets, const int axis, +static uint GetUniquelySortedElems(const uint m, const float *triplets, const uint axis, const double *const (&filters)[3], const double (&epsilons)[3], float *elems) { uint count{0u}; diff --git a/utils/openal-info.c b/utils/openal-info.c index 12dc6311..cc628b6e 100644 --- a/utils/openal-info.c +++ b/utils/openal-info.c @@ -124,7 +124,7 @@ static void printList(const char *list, char separator) next = strchr(list, separator); if(next) { - len = next-list; + len = (size_t)(next-list); do { next++; } while(*next == separator); -- cgit v1.2.3 From 2c348cecb68bd3a71d388547d6b3330f9cebbfad Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 14 Sep 2019 16:55:28 -0700 Subject: Fix some more implicit conversions noted by GCC --- al/source.cpp | 6 +++--- alc/alc.cpp | 34 +++++++++++++++++-------------- alc/alu.cpp | 10 ++++----- alc/backends/alsa.cpp | 2 +- alc/backends/coreaudio.cpp | 17 ++++++++-------- alc/backends/opensl.cpp | 6 +++--- alc/backends/pulseaudio.cpp | 2 +- alc/bs2b.cpp | 4 ++-- alc/converter.cpp | 2 +- alc/effects/autowah.cpp | 9 +++++---- alc/effects/chorus.cpp | 32 +++++++++++++++-------------- alc/effects/echo.cpp | 6 ++++-- alc/effects/fshifter.cpp | 3 ++- alc/effects/modulator.cpp | 2 +- alc/effects/pshifter.cpp | 19 +++++++++--------- alc/effects/vmorpher.cpp | 14 +++++++------ alc/hrtf.cpp | 49 ++++++++++++++++++++++++--------------------- alc/mastering.cpp | 3 +-- alc/mastering.h | 3 +-- alc/mixer/mixer_c.cpp | 9 +++++---- alc/mixer/mixer_neon.cpp | 13 ++++++------ alc/mixer/mixer_sse.cpp | 7 ++++--- alc/mixer/mixer_sse2.cpp | 2 +- alc/mixer/mixer_sse41.cpp | 2 +- alc/mixvoice.cpp | 18 +++++++++-------- common/almalloc.cpp | 6 +++--- examples/alrecord.c | 5 +++-- examples/altonegen.c | 2 +- examples/common/alhelpers.c | 4 ++-- 29 files changed, 156 insertions(+), 135 deletions(-) (limited to 'examples') diff --git a/al/source.cpp b/al/source.cpp index 478ee3d2..733758f7 100644 --- a/al/source.cpp +++ b/al/source.cpp @@ -310,8 +310,8 @@ ALdouble GetSourceOffset(ALsource *Source, ALenum name, ALCcontext *context) const ALbufferlistitem *BufferList{Source->queue}; const ALbuffer *BufferFmt{nullptr}; - ALboolean readFin{AL_FALSE}; ALuint totalBufferLen{0u}; + bool readFin{false}; while(BufferList) { @@ -1662,7 +1662,7 @@ bool GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, const a case AL_SEC_OFFSET_CLOCK_SOFT: CHECKSIZE(values, 2); values[0] = GetSourceSecOffset(Source, Context, &srcclock); - values[1] = srcclock.count() / 1000000000.0; + values[1] = static_cast(srcclock.count()) / 1000000000.0; return true; case AL_POSITION: @@ -2851,7 +2851,7 @@ START_API_FUNC if(device->AvgSpeakerDist > 0.0f) { const ALfloat w1{SPEEDOFSOUNDMETRESPERSEC / - (device->AvgSpeakerDist * device->Frequency)}; + (device->AvgSpeakerDist * static_cast(device->Frequency))}; auto init_nfc = [w1](ALvoice::ChannelData &chandata) -> void { chandata.mDryParams.NFCtrlFilter.init(w1); }; std::for_each(voice->mChans.begin(), voice->mChans.begin()+voice->mNumChannels, diff --git a/alc/alc.cpp b/alc/alc.cpp index 408b3ca3..8e9d3963 100644 --- a/alc/alc.cpp +++ b/alc/alc.cpp @@ -1587,9 +1587,9 @@ static void alcSetError(ALCdevice *device, ALCenum errorCode) static std::unique_ptr CreateDeviceLimiter(const ALCdevice *device, const ALfloat threshold) { - return CompressorInit(static_cast(device->RealOut.Buffer.size()), device->Frequency, - AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, 0.001f, 0.002f, 0.0f, 0.0f, threshold, - INFINITY, 0.0f, 0.020f, 0.200f); + return CompressorInit(static_cast(device->RealOut.Buffer.size()), + static_cast(device->Frequency), AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, 0.001f, + 0.002f, 0.0f, 0.0f, threshold, INFINITY, 0.0f, 0.020f, 0.200f); } /* UpdateClockBase @@ -2145,17 +2145,21 @@ static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList) if(old_sends != device->NumAuxSends) { - if(source->Send.size() > static_cast(device->NumAuxSends)) - std::for_each(source->Send.begin()+device->NumAuxSends, source->Send.end(), - [](ALsource::SendData &send) -> void - { - if(send.Slot) - DecrementRef(send.Slot->ref); - send.Slot = nullptr; - }); - - source->Send.resize(static_cast(device->NumAuxSends), - ALsource::SendData{nullptr, 1.0f, 1.0f, LOWPASSFREQREF, 1.0f, HIGHPASSFREQREF}); + if(source->Send.size() > device->NumAuxSends) + { + auto clear_send = [](ALsource::SendData &send) -> void + { + if(send.Slot) + DecrementRef(send.Slot->ref); + send.Slot = nullptr; + }; + auto send_begin = source->Send.begin() + + static_cast(device->NumAuxSends); + std::for_each(send_begin, source->Send.end(), clear_send); + } + + source->Send.resize(device->NumAuxSends, + {nullptr, 1.0f, 1.0f, LOWPASSFREQREF, 1.0f, HIGHPASSFREQREF}); source->Send.shrink_to_fit(); } @@ -2209,7 +2213,7 @@ static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList) { /* Reinitialize the NFC filters for new parameters. */ const ALfloat w1{SPEEDOFSOUNDMETRESPERSEC / - (device->AvgSpeakerDist * device->Frequency)}; + (device->AvgSpeakerDist * static_cast(device->Frequency))}; auto init_nfc = [w1](ALvoice::ChannelData &chandata) -> void { chandata.mDryParams.NFCtrlFilter.init(w1); }; std::for_each(voice.mChans.begin(), voice.mChans.begin()+voice.mNumChannels, diff --git a/alc/alu.cpp b/alc/alu.cpp index 0def577e..d7acf8d3 100644 --- a/alc/alu.cpp +++ b/alc/alu.cpp @@ -201,19 +201,19 @@ void ALCdevice::ProcessBs2b(const size_t SamplesToDo) */ void BsincPrepare(const ALuint increment, BsincState *state, const BSincTable *table) { - ALsizei si{BSINC_SCALE_COUNT - 1}; - ALfloat sf{0.0f}; + size_t si{BSINC_SCALE_COUNT - 1}; + float sf{0.0f}; if(increment > FRACTIONONE) { - sf = static_castFRACTIONONE / increment; + sf = FRACTIONONE / static_cast(increment); sf = maxf(0.0f, (BSINC_SCALE_COUNT-1) * (sf-table->scaleBase) * table->scaleRange); - si = float2int(sf); + si = float2uint(sf); /* The interpolation factor is fit to this diagonally-symmetric curve * to reduce the transition ripple caused by interpolating different * scales of the sinc function. */ - sf = 1.0f - std::cos(std::asin(sf - si)); + sf = 1.0f - std::cos(std::asin(sf - static_cast(si))); } state->sf = sf; diff --git a/alc/backends/alsa.cpp b/alc/backends/alsa.cpp index cd85afaf..b797c768 100644 --- a/alc/backends/alsa.cpp +++ b/alc/backends/alsa.cpp @@ -1112,7 +1112,7 @@ ALCenum AlsaCapture::captureSamples(ALCvoid *buffer, ALCuint samples) } buffer = static_cast(buffer) + amt; - samples -= amt; + samples -= static_cast(amt); } if(samples > 0) std::fill_n(static_cast(buffer), snd_pcm_frames_to_bytes(mPcmHandle, samples), diff --git a/alc/backends/coreaudio.cpp b/alc/backends/coreaudio.cpp index 39f6241a..99b06b7a 100644 --- a/alc/backends/coreaudio.cpp +++ b/alc/backends/coreaudio.cpp @@ -177,7 +177,7 @@ ALCboolean CoreAudioPlayback::reset() { mDevice->BufferSize = static_cast(uint64_t{mDevice->BufferSize} * streamFormat.mSampleRate / mDevice->Frequency); - mDevice->Frequency = streamFormat.mSampleRate; + mDevice->Frequency = static_cast(streamFormat.mSampleRate); } /* FIXME: How to tell what channels are what in the output device, and how @@ -357,7 +357,8 @@ OSStatus CoreAudioCapture::RecordProc(AudioUnitRenderActionFlags*, } audiobuf = { { 0 } }; auto rec_vec = mRing->getWriteVector(); - inNumberFrames = minz(inNumberFrames, rec_vec.first.len+rec_vec.second.len); + inNumberFrames = static_cast(minz(inNumberFrames, + rec_vec.first.len+rec_vec.second.len)); // Fill the ringbuffer's two segments with data from the input device if(rec_vec.first.len >= inNumberFrames) @@ -369,7 +370,7 @@ OSStatus CoreAudioCapture::RecordProc(AudioUnitRenderActionFlags*, } else { - const size_t remaining{inNumberFrames-rec_vec.first.len}; + const auto remaining = static_cast(inNumberFrames - rec_vec.first.len); audiobuf.list.mNumberBuffers = 2; audiobuf.list.mBuffers[0].mNumberChannels = mFormat.mChannelsPerFrame; audiobuf.list.mBuffers[0].mData = rec_vec.first.buf; @@ -594,7 +595,7 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) // Set the AudioUnit output format frame count uint64_t FrameCount64{mDevice->UpdateSize}; - FrameCount64 = (FrameCount64*outputFormat.mSampleRate + mDevice->Frequency-1) / + FrameCount64 = static_cast(FrameCount64*outputFormat.mSampleRate + mDevice->Frequency-1) / mDevice->Frequency; FrameCount64 += MAX_RESAMPLE_PADDING*2; if(FrameCount64 > std::numeric_limits::max()/2) @@ -615,8 +616,8 @@ ALCenum CoreAudioCapture::open(const ALCchar *name) // Set up sample converter if needed if(outputFormat.mSampleRate != mDevice->Frequency) mConverter = CreateSampleConverter(mDevice->FmtType, mDevice->FmtType, - mFormat.mChannelsPerFrame, hardwareFormat.mSampleRate, mDevice->Frequency, - BSinc24Resampler); + mFormat.mChannelsPerFrame, static_cast(hardwareFormat.mSampleRate), + mDevice->Frequency, BSinc24Resampler); mRing = CreateRingBuffer(outputFrameCount, mFrameSize, false); if(!mRing) return ALC_INVALID_VALUE; @@ -671,8 +672,8 @@ ALCenum CoreAudioCapture::captureSamples(void *buffer, ALCuint samples) ALCuint CoreAudioCapture::availableSamples() { - if(!mConverter) return mRing->readSpace(); - return mConverter->availableOut(mRing->readSpace()); + if(!mConverter) return static_cast(mRing->readSpace()); + return mConverter->availableOut(static_cast(mRing->readSpace())); } } // namespace diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp index 3ec2177f..06d5cd40 100644 --- a/alc/backends/opensl.cpp +++ b/alc/backends/opensl.cpp @@ -170,7 +170,7 @@ struct OpenSLPlayback final : public BackendBase { RingBufferPtr mRing{nullptr}; al::semaphore mSem; - ALsizei mFrameSize{0}; + ALuint mFrameSize{0}; std::atomic mKillNow{true}; std::thread mThread; @@ -630,7 +630,7 @@ struct OpenSLCapture final : public BackendBase { RingBufferPtr mRing{nullptr}; ALCuint mSplOffset{0u}; - ALsizei mFrameSize{0}; + ALuint mFrameSize{0}; DEF_NEWDEL(OpenSLCapture) }; @@ -851,7 +851,7 @@ void OpenSLCapture::stop() ALCenum OpenSLCapture::captureSamples(void *buffer, ALCuint samples) { - ALsizei chunk_size = mDevice->UpdateSize * mFrameSize; + ALuint chunk_size{mDevice->UpdateSize * mFrameSize}; SLAndroidSimpleBufferQueueItf bufferQueue; SLresult result; ALCuint i; diff --git a/alc/backends/pulseaudio.cpp b/alc/backends/pulseaudio.cpp index 08420748..30c13a69 100644 --- a/alc/backends/pulseaudio.cpp +++ b/alc/backends/pulseaudio.cpp @@ -1324,7 +1324,7 @@ ALCenum PulseCapture::captureSamples(ALCvoid *buffer, ALCuint samples) /* Capture is done in fragment-sized chunks, so we loop until we get all * that's available */ - mLastReadable -= dstbuf.size(); + mLastReadable -= static_cast(dstbuf.size()); std::lock_guard _{pulse_lock}; while(!dstbuf.empty()) { diff --git a/alc/bs2b.cpp b/alc/bs2b.cpp index fb75188c..00207bc0 100644 --- a/alc/bs2b.cpp +++ b/alc/bs2b.cpp @@ -91,11 +91,11 @@ static void init(struct bs2b *bs2b) * $d = 1 / 2 / pi / $fc; * $x = exp(-1 / $d); */ - x = std::exp(-al::MathDefs::Tau() * Fc_lo / bs2b->srate); + x = std::exp(-al::MathDefs::Tau() * Fc_lo / static_cast(bs2b->srate)); bs2b->b1_lo = x; bs2b->a0_lo = G_lo * (1.0f - x) * g; - x = std::exp(-al::MathDefs::Tau() * Fc_hi / bs2b->srate); + x = std::exp(-al::MathDefs::Tau() * Fc_hi / static_cast(bs2b->srate)); bs2b->b1_hi = x; bs2b->a0_hi = (1.0f - G_hi * (1.0f - x)) * g; bs2b->a1_hi = -x * g; diff --git a/alc/converter.cpp b/alc/converter.cpp index 2913f533..2ad2ac3b 100644 --- a/alc/converter.cpp +++ b/alc/converter.cpp @@ -27,7 +27,7 @@ template<> inline ALfloat LoadSample(DevFmtTypeTraits::T template<> inline ALfloat LoadSample(DevFmtTypeTraits::Type val) noexcept { return val * (1.0f/32768.0f); } template<> inline ALfloat LoadSample(DevFmtTypeTraits::Type val) noexcept -{ return val * (1.0f/2147483648.0f); } +{ return static_cast(val) * (1.0f/2147483648.0f); } template<> inline ALfloat LoadSample(DevFmtTypeTraits::Type val) noexcept { return val; } diff --git a/alc/effects/autowah.cpp b/alc/effects/autowah.cpp index f28cfd54..5e396d0c 100644 --- a/alc/effects/autowah.cpp +++ b/alc/effects/autowah.cpp @@ -107,16 +107,17 @@ ALboolean ALautowahState::deviceUpdate(const ALCdevice*) void ALautowahState::update(const ALCcontext *context, const ALeffectslot *slot, const EffectProps *props, const EffectTarget target) { const ALCdevice *device{context->mDevice.get()}; + const auto frequency = static_cast(device->Frequency); const ALfloat ReleaseTime{clampf(props->Autowah.ReleaseTime, 0.001f, 1.0f)}; - mAttackRate = expf(-1.0f / (props->Autowah.AttackTime*device->Frequency)); - mReleaseRate = expf(-1.0f / (ReleaseTime*device->Frequency)); + mAttackRate = std::exp(-1.0f / (props->Autowah.AttackTime*frequency)); + mReleaseRate = std::exp(-1.0f / (ReleaseTime*frequency)); /* 0-20dB Resonance Peak gain */ mResonanceGain = std::sqrt(std::log10(props->Autowah.Resonance)*10.0f / 3.0f); mPeakGain = 1.0f - std::log10(props->Autowah.PeakGain/AL_AUTOWAH_MAX_PEAK_GAIN); - mFreqMinNorm = MIN_FREQ / device->Frequency; - mBandwidthNorm = (MAX_FREQ-MIN_FREQ) / device->Frequency; + mFreqMinNorm = MIN_FREQ / frequency; + mBandwidthNorm = (MAX_FREQ-MIN_FREQ) / frequency; mOutTarget = target.Main->Buffer; for(size_t i{0u};i < slot->Wet.Buffer.size();++i) diff --git a/alc/effects/chorus.cpp b/alc/effects/chorus.cpp index 6e73f1f0..0e3c9d89 100644 --- a/alc/effects/chorus.cpp +++ b/alc/effects/chorus.cpp @@ -64,8 +64,8 @@ void GetTriangleDelays(ALuint *delays, const ALuint start_offset, const ALuint l auto gen_lfo = [&offset,lfo_range,lfo_scale,depth,delay]() -> ALuint { offset = (offset+1)%lfo_range; - return static_cast( - fastf2i((1.0f - std::abs(2.0f - lfo_scale*offset)) * depth) + delay); + const float offset_norm{static_cast(offset) * lfo_scale}; + return static_cast(fastf2i((1.0f-std::abs(2.0f-offset_norm)) * depth) + delay); }; std::generate_n(delays, todo, gen_lfo); } @@ -80,7 +80,8 @@ void GetSinusoidDelays(ALuint *delays, const ALuint start_offset, const ALuint l auto gen_lfo = [&offset,lfo_range,lfo_scale,depth,delay]() -> ALuint { offset = (offset+1)%lfo_range; - return static_cast(fastf2i(std::sin(lfo_scale*offset) * depth) + delay); + const float offset_norm{static_cast(offset) * lfo_scale}; + return static_cast(fastf2i(std::sin(offset_norm)*depth) + delay); }; std::generate_n(delays, todo, gen_lfo); } @@ -118,7 +119,8 @@ ALboolean ChorusState::deviceUpdate(const ALCdevice *Device) { constexpr ALfloat max_delay{maxf(AL_CHORUS_MAX_DELAY, AL_FLANGER_MAX_DELAY)}; - const size_t maxlen{NextPowerOf2(float2uint(max_delay*2.0f*Device->Frequency) + 1u)}; + const auto frequency = static_cast(Device->Frequency); + const size_t maxlen{NextPowerOf2(float2uint(max_delay*2.0f*frequency) + 1u)}; if(maxlen != mSampleBuffer.size()) { mSampleBuffer.resize(maxlen); @@ -153,9 +155,11 @@ void ChorusState::update(const ALCcontext *Context, const ALeffectslot *Slot, co * delay and depth to allow enough padding for resampling. */ const ALCdevice *device{Context->mDevice.get()}; - const auto frequency = static_cast(device->Frequency); + const auto frequency = static_cast(device->Frequency); + mDelay = maxi(float2int(props->Chorus.Delay*frequency*FRACTIONONE + 0.5f), mindelay); - mDepth = minf(props->Chorus.Depth * mDelay, static_cast(mDelay - mindelay)); + mDepth = minf(props->Chorus.Depth * static_cast(mDelay), + static_cast(mDelay - mindelay)); mFeedback = props->Chorus.Feedback; @@ -188,10 +192,10 @@ void ChorusState::update(const ALCcontext *Context, const ALeffectslot *Slot, co switch(mWaveform) { case WaveForm::Triangle: - mLfoScale = 4.0f / mLfoRange; + mLfoScale = 4.0f / static_cast(mLfoRange); break; case WaveForm::Sinusoid: - mLfoScale = al::MathDefs::Tau() / mLfoRange; + mLfoScale = al::MathDefs::Tau() / static_cast(mLfoRange); break; } @@ -229,7 +233,7 @@ void ChorusState::process(const size_t samplesToDo, const al::span(todo)) % mLfoRange; alignas(16) ALfloat temps[2][256]; for(size_t i{0u};i < todo;i++) @@ -239,17 +243,15 @@ void ChorusState::process(const size_t samplesToDo, const al::span>FRACTIONBITS)}; - ALfloat mu{(moddelays[0][i]&FRACTIONMASK) * (1.0f/FRACTIONONE)}; + ALfloat mu{static_cast(moddelays[0][i]&FRACTIONMASK) * (1.0f/FRACTIONONE)}; temps[0][i] = cubic(delaybuf[(delay+1) & bufmask], delaybuf[(delay ) & bufmask], - delaybuf[(delay-1) & bufmask], delaybuf[(delay-2) & bufmask], - mu); + delaybuf[(delay-1) & bufmask], delaybuf[(delay-2) & bufmask], mu); // Tap for the right output. delay = offset - (moddelays[1][i]>>FRACTIONBITS); - mu = (moddelays[1][i]&FRACTIONMASK) * (1.0f/FRACTIONONE); + mu = static_cast(moddelays[1][i]&FRACTIONMASK) * (1.0f/FRACTIONONE); temps[1][i] = cubic(delaybuf[(delay+1) & bufmask], delaybuf[(delay ) & bufmask], - delaybuf[(delay-1) & bufmask], delaybuf[(delay-2) & bufmask], - mu); + delaybuf[(delay-1) & bufmask], delaybuf[(delay-2) & bufmask], mu); // Accumulate feedback from the average delay of the taps. delaybuf[offset&bufmask] += delaybuf[(offset-avgdelay) & bufmask] * feedback; diff --git a/alc/effects/echo.cpp b/alc/effects/echo.cpp index 47c0fedb..a9213df5 100644 --- a/alc/effects/echo.cpp +++ b/alc/effects/echo.cpp @@ -66,10 +66,12 @@ struct EchoState final : public EffectState { ALboolean EchoState::deviceUpdate(const ALCdevice *Device) { + const auto frequency = static_cast(Device->Frequency); + // Use the next power of 2 for the buffer length, so the tap offsets can be // wrapped using a mask instead of a modulo - const ALuint maxlen{NextPowerOf2(float2uint(AL_ECHO_MAX_DELAY*Device->Frequency + 0.5f) + - float2uint(AL_ECHO_MAX_LRDELAY*Device->Frequency + 0.5f))}; + const ALuint maxlen{NextPowerOf2(float2uint(AL_ECHO_MAX_DELAY*frequency + 0.5f) + + float2uint(AL_ECHO_MAX_LRDELAY*frequency + 0.5f))}; if(maxlen != mSampleBuffer.size()) { mSampleBuffer.resize(maxlen); diff --git a/alc/effects/fshifter.cpp b/alc/effects/fshifter.cpp index c015831c..1b935047 100644 --- a/alc/effects/fshifter.cpp +++ b/alc/effects/fshifter.cpp @@ -51,7 +51,8 @@ std::array InitHannWindow() /* Create lookup table of the Hann window for the desired size, i.e. HIL_SIZE */ for(size_t i{0};i < HIL_SIZE>>1;i++) { - const double val{std::sin(al::MathDefs::Pi() * i / double{HIL_SIZE-1})}; + constexpr double scale{al::MathDefs::Pi() / double{HIL_SIZE-1}}; + const double val{std::sin(static_cast(i) * scale)}; ret[i] = ret[HIL_SIZE-1-i] = val * val; } return ret; diff --git a/alc/effects/modulator.cpp b/alc/effects/modulator.cpp index fbc6377c..8042378a 100644 --- a/alc/effects/modulator.cpp +++ b/alc/effects/modulator.cpp @@ -146,7 +146,7 @@ void ModulatorState::process(const size_t samplesToDo, const al::span(mStep * td); mIndex &= WAVEFORM_FRACMASK; auto chandata = std::addressof(mChans[0]); diff --git a/alc/effects/pshifter.cpp b/alc/effects/pshifter.cpp index a4d66706..d7ba072e 100644 --- a/alc/effects/pshifter.cpp +++ b/alc/effects/pshifter.cpp @@ -57,7 +57,8 @@ std::array InitHannWindow() /* Create lookup table of the Hann window for the desired size, i.e. HIL_SIZE */ for(size_t i{0};i < STFT_SIZE>>1;i++) { - const double val{std::sin(al::MathDefs::Pi() * i / ALdouble{STFT_SIZE-1})}; + constexpr double scale{al::MathDefs::Pi() / double{STFT_SIZE-1}}; + const double val{std::sin(static_cast(i) * scale)}; ret[i] = ret[STFT_SIZE-1-i] = val * val; } return ret; @@ -129,7 +130,7 @@ ALboolean PshifterState::deviceUpdate(const ALCdevice *device) mCount = FIFO_LATENCY; mPitchShiftI = FRACTIONONE; mPitchShift = 1.0f; - mFreqPerBin = device->Frequency / static_cast(STFT_SIZE); + mFreqPerBin = static_cast(device->Frequency) / float{STFT_SIZE}; std::fill(std::begin(mInFIFO), std::end(mInFIFO), 0.0f); std::fill(std::begin(mOutFIFO), std::end(mOutFIFO), 0.0f); @@ -152,7 +153,7 @@ void PshifterState::update(const ALCcontext*, const ALeffectslot *slot, const Ef static_cast(props->Pshifter.CoarseTune*100 + props->Pshifter.FineTune) / 1200.0f )}; mPitchShiftI = fastf2u(pitch*FRACTIONONE); - mPitchShift = mPitchShiftI * (1.0f/FRACTIONONE); + mPitchShift = static_cast(mPitchShiftI) * (1.0f/FRACTIONONE); ALfloat coeffs[MAX_AMBI_CHANNELS]; CalcDirectionCoeffs({0.0f, 0.0f, -1.0f}, 0.0f, coeffs); @@ -187,7 +188,7 @@ void PshifterState::process(const size_t samplesToDo, const al::spanVmorpher.Waveform == AL_VOCAL_MORPHER_WAVEFORM_TRIANGLE)*/ mGetSamples = Oscillate; - const ALfloat pitchA{std::pow(2.0f, props->Vmorpher.PhonemeACoarseTuning / 12.0f)}; - const ALfloat pitchB{std::pow(2.0f, props->Vmorpher.PhonemeBCoarseTuning / 12.0f)}; + const ALfloat pitchA{std::pow(2.0f, + static_cast(props->Vmorpher.PhonemeACoarseTuning) / 12.0f)}; + const ALfloat pitchB{std::pow(2.0f, + static_cast(props->Vmorpher.PhonemeBCoarseTuning) / 12.0f)}; auto vowelA = getFiltersByPhoneme(props->Vmorpher.PhonemeA, frequency, pitchA); auto vowelB = getFiltersByPhoneme(props->Vmorpher.PhonemeB, frequency, pitchB); @@ -255,7 +257,7 @@ void VmorpherState::process(const size_t samplesToDo, const al::span(mStep * td); mIndex &= WAVEFORM_FRACMASK; auto chandata = std::addressof(mChans[0]); diff --git a/alc/hrtf.cpp b/alc/hrtf.cpp index bd6ecb3a..e20bf0a9 100644 --- a/alc/hrtf.cpp +++ b/alc/hrtf.cpp @@ -182,10 +182,11 @@ struct IdxBlend { ALsizei idx; ALfloat blend; }; */ IdxBlend CalcEvIndex(ALsizei evcount, ALfloat ev) { - ev = (al::MathDefs::Pi()*0.5f + ev) * (evcount-1) / al::MathDefs::Pi(); + ev = (al::MathDefs::Pi()*0.5f + ev) * static_cast(evcount-1) / + al::MathDefs::Pi(); ALsizei idx{float2int(ev)}; - return IdxBlend{mini(idx, evcount-1), ev-idx}; + return IdxBlend{mini(idx, evcount-1), ev-static_cast(idx)}; } /* Calculate the azimuth index given the polar azimuth in radians. This will @@ -193,10 +194,11 @@ IdxBlend CalcEvIndex(ALsizei evcount, ALfloat ev) */ IdxBlend CalcAzIndex(ALsizei azcount, ALfloat az) { - az = (al::MathDefs::Tau()+az) * azcount / al::MathDefs::Tau(); + az = (al::MathDefs::Tau()+az) * static_cast(azcount) / + al::MathDefs::Tau(); ALsizei idx{float2int(az)}; - return IdxBlend{idx%azcount, az-idx}; + return IdxBlend{idx%azcount, az-static_cast(idx)}; } } // namespace @@ -303,24 +305,25 @@ void BuildBFormatHrtf(const HrtfEntry *Hrtf, DirectHrtfState *state, const ALuin ASSUME(NumChannels > 0); ASSUME(AmbiCount > 0); - auto &field = Hrtf->field[0]; ALuint min_delay{HRTF_HISTORY_LENGTH}; ALuint max_delay{0}; auto idx = al::vector(AmbiCount); - auto calc_idxs = [Hrtf,&field,&max_delay,&min_delay](const AngularPoint &pt) noexcept -> ALuint + auto calc_idxs = [Hrtf,&max_delay,&min_delay](const AngularPoint &pt) noexcept -> ALuint { + auto &field = Hrtf->field[0]; /* Calculate elevation index. */ - const auto evidx = clampi(float2int((90.0f+pt.Elev)*(field.evCount-1)/180.0f + 0.5f), - 0, field.evCount-1); + const auto ev_limit = static_cast(field.evCount-1); + const ALuint evidx{float2uint(clampf((90.0f+pt.Elev)/180.0f, 0.0f, 1.0f)*ev_limit + 0.5f)}; const ALuint azcount{Hrtf->elev[evidx].azCount}; const ALuint iroffset{Hrtf->elev[evidx].irOffset}; /* Calculate azimuth index for this elevation. */ - const auto azidx = static_cast((360.0f+pt.Azim)*azcount/360.0f + 0.5f) % azcount; + const float az_norm{(360.0f*pt.Azim) / 360.0f}; + const ALuint azidx{float2uint(az_norm*static_cast(azcount) + 0.5f) % azcount}; /* Calculate the index for the impulse response. */ - ALuint idx{iroffset + azidx}; + const ALuint idx{iroffset + azidx}; min_delay = minu(min_delay, minu(Hrtf->delays[idx][0], Hrtf->delays[idx][1])); max_delay = maxu(max_delay, maxu(Hrtf->delays[idx][0], Hrtf->delays[idx][1])); @@ -594,7 +597,7 @@ std::unique_ptr LoadHrtf00(std::istream &data, const char *filename) if(failed) return nullptr; - al::vector evOffset(evCount); + auto evOffset = al::vector(evCount); for(auto &val : evOffset) val = GetLE_ALushort(data); if(!data || data.eof()) @@ -619,10 +622,10 @@ std::unique_ptr LoadHrtf00(std::istream &data, const char *filename) if(failed) return nullptr; - al::vector azCount(evCount); + auto azCount = al::vector(evCount); for(size_t i{1};i < evCount;i++) { - azCount[i-1] = evOffset[i] - evOffset[i-1]; + azCount[i-1] = static_cast(evOffset[i] - evOffset[i-1]); if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT) { ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", @@ -630,7 +633,7 @@ std::unique_ptr LoadHrtf00(std::istream &data, const char *filename) failed = AL_TRUE; } } - azCount.back() = irCount - evOffset.back(); + azCount.back() = static_cast(irCount - evOffset.back()); if(azCount.back() < MIN_AZ_COUNT || azCount.back() > MAX_AZ_COUNT) { ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n", @@ -640,8 +643,8 @@ std::unique_ptr LoadHrtf00(std::istream &data, const char *filename) if(failed) return nullptr; - al::vector> coeffs(irSize*irCount); - al::vector> delays(irCount); + auto coeffs = al::vector>(irSize*irCount); + auto delays = al::vector>(irCount); for(auto &val : coeffs) val[0] = GetLE_ALshort(data) / 32768.0f; for(auto &val : delays) @@ -711,7 +714,7 @@ std::unique_ptr LoadHrtf01(std::istream &data, const char *filename) if(failed) return nullptr; - al::vector azCount(evCount); + auto azCount = al::vector(evCount); std::generate(azCount.begin(), azCount.end(), std::bind(GetLE_ALubyte, std::ref(data))); if(!data || data.eof()) { @@ -735,12 +738,12 @@ std::unique_ptr LoadHrtf01(std::istream &data, const char *filename) ALushort irCount{azCount[0]}; for(size_t i{1};i < evCount;i++) { - evOffset[i] = evOffset[i-1] + azCount[i-1]; + evOffset[i] = static_cast(evOffset[i-1] + azCount[i-1]); irCount += azCount[i]; } - al::vector> coeffs(irSize*irCount); - al::vector> delays(irCount); + auto coeffs = al::vector>(irSize*irCount); + auto delays = al::vector>(irCount); for(auto &val : coeffs) val[0] = GetLE_ALshort(data) / 32768.0f; for(auto &val : delays) @@ -903,7 +906,7 @@ std::unique_ptr LoadHrtf02(std::istream &data, const char *filename) else if(sampleType == SAMPLETYPE_S24) { for(auto &val : coeffs) - val[0] = GetLE_ALint24(data) / 8388608.0f; + val[0] = static_cast(GetLE_ALint24(data)) / 8388608.0f; } for(auto &val : delays) val[0] = GetLE_ALubyte(data); @@ -935,8 +938,8 @@ std::unique_ptr LoadHrtf02(std::istream &data, const char *filename) { for(auto &val : coeffs) { - val[0] = GetLE_ALint24(data) / 8388608.0f; - val[1] = GetLE_ALint24(data) / 8388608.0f; + val[0] = static_cast(GetLE_ALint24(data)) / 8388608.0f; + val[1] = static_cast(GetLE_ALint24(data)) / 8388608.0f; } } for(auto &val : delays) diff --git a/alc/mastering.cpp b/alc/mastering.cpp index 2f575f35..d0a2f78a 100644 --- a/alc/mastering.cpp +++ b/alc/mastering.cpp @@ -337,7 +337,7 @@ void SignalDelay(Compressor *Comp, const ALuint SamplesToDo, FloatBufferLine *Ou * ReleaseTimeMin - Release time (in seconds). Acts as a maximum when * automating release time. */ -std::unique_ptr CompressorInit(const ALuint NumChans, const ALuint SampleRate, +std::unique_ptr CompressorInit(const ALuint NumChans, const ALfloat SampleRate, const ALboolean AutoKnee, const ALboolean AutoAttack, const ALboolean AutoRelease, const ALboolean AutoPostGain, const ALboolean AutoDeclip, const ALfloat LookAheadTime, const ALfloat HoldTime, const ALfloat PreGainDb, const ALfloat PostGainDb, @@ -363,7 +363,6 @@ std::unique_ptr CompressorInit(const ALuint NumChans, const ALuint S auto Comp = std::unique_ptr{new (al_calloc(16, size)) Compressor{}}; Comp->mNumChans = NumChans; - Comp->mSampleRate = SampleRate; Comp->mAuto.Knee = AutoKnee != AL_FALSE; Comp->mAuto.Attack = AutoAttack != AL_FALSE; Comp->mAuto.Release = AutoRelease != AL_FALSE; diff --git a/alc/mastering.h b/alc/mastering.h index 6c8fc628..851381e9 100644 --- a/alc/mastering.h +++ b/alc/mastering.h @@ -24,7 +24,6 @@ struct SlidingHold; */ struct Compressor { ALuint mNumChans{0u}; - ALuint mSampleRate{0u}; struct { bool Knee : 1; @@ -94,7 +93,7 @@ struct Compressor { * ReleaseTimeMin - Release time (in seconds). Acts as a maximum when * automating release time. */ -std::unique_ptr CompressorInit(const ALuint NumChans, const ALuint SampleRate, +std::unique_ptr CompressorInit(const ALuint NumChans, const ALfloat SampleRate, const ALboolean AutoKnee, const ALboolean AutoAttack, const ALboolean AutoRelease, const ALboolean AutoPostGain, const ALboolean AutoDeclip, const ALfloat LookAheadTime, const ALfloat HoldTime, const ALfloat PreGainDb, const ALfloat PostGainDb, diff --git a/alc/mixer/mixer_c.cpp b/alc/mixer/mixer_c.cpp index 720b264b..74315dd5 100644 --- a/alc/mixer/mixer_c.cpp +++ b/alc/mixer/mixer_c.cpp @@ -16,9 +16,9 @@ namespace { inline ALfloat do_point(const InterpState&, const ALfloat *RESTRICT vals, const ALuint) { return vals[0]; } inline ALfloat do_lerp(const InterpState&, const ALfloat *RESTRICT vals, const ALuint frac) -{ return lerp(vals[0], vals[1], frac * (1.0f/FRACTIONONE)); } +{ return lerp(vals[0], vals[1], static_cast(frac)*(1.0f/FRACTIONONE)); } inline ALfloat do_cubic(const InterpState&, const ALfloat *RESTRICT vals, const ALuint frac) -{ return cubic(vals[0], vals[1], vals[2], vals[3], frac * (1.0f/FRACTIONONE)); } +{ return cubic(vals[0], vals[1], vals[2], vals[3], static_cast(frac)*(1.0f/FRACTIONONE)); } inline ALfloat do_bsinc(const InterpState &istate, const ALfloat *RESTRICT vals, const ALuint frac) { ASSUME(istate.bsinc.m > 0); @@ -26,10 +26,11 @@ inline ALfloat do_bsinc(const InterpState &istate, const ALfloat *RESTRICT vals, // Calculate the phase index and factor. #define FRAC_PHASE_BITDIFF (FRACTIONBITS-BSINC_PHASE_BITS) const ALuint pi{frac >> FRAC_PHASE_BITDIFF}; - const ALfloat pf{(frac & ((1<(frac & ((1<(istate.bsinc.m)*pi*4}; const ALfloat *scd{fil + istate.bsinc.m}; const ALfloat *phd{scd + istate.bsinc.m}; const ALfloat *spd{phd + istate.bsinc.m}; diff --git a/alc/mixer/mixer_neon.cpp b/alc/mixer/mixer_neon.cpp index 852bef38..2f11273a 100644 --- a/alc/mixer/mixer_neon.cpp +++ b/alc/mixer/mixer_neon.cpp @@ -55,10 +55,10 @@ const ALfloat *Resample_(const InterpState*, const ALfloat *RES if(dst_iter != dst.end()) { src += static_cast(vgetq_lane_s32(pos4, 0)); - frac = vgetq_lane_s32(frac4, 0); + frac = static_cast(vgetq_lane_s32(frac4, 0)); do { - *(dst_iter++) = lerp(src[0], src[1], frac * (1.0f/FRACTIONONE)); + *(dst_iter++) = lerp(src[0], src[1], static_cast(frac) * (1.0f/FRACTIONONE)); frac += increment; src += frac>>FRACTIONBITS; @@ -84,14 +84,15 @@ const ALfloat *Resample_(const InterpState *state, const ALflo // Calculate the phase index and factor. #define FRAC_PHASE_BITDIFF (FRACTIONBITS-BSINC_PHASE_BITS) const ALuint pi{frac >> FRAC_PHASE_BITDIFF}; - const ALfloat pf{(frac & ((1<(frac & ((1<(pi*4)}; const float *scd{fil + m}; const float *phd{scd + m}; const float *spd{phd + m}; @@ -179,8 +180,8 @@ void Mix_(const al::span InSamples, const al::span 0) ? 1.0f / static_cast(Counter) : 0.0f}; const bool reached_target{InSamples.size() >= Counter}; const auto min_end = reached_target ? InSamples.begin() + Counter : InSamples.end(); - const auto aligned_end = minz(InSamples.size(), (min_end-InSamples.begin()+3) & ~3u) + - InSamples.begin(); + const auto aligned_end = minz(static_cast(min_end-InSamples.begin()+3) & ~3u, + InSamples.size()) + InSamples.begin(); for(FloatBufferLine &output : OutBuffer) { ALfloat *RESTRICT dst{al::assume_aligned<16>(output.data()+OutPos)}; diff --git a/alc/mixer/mixer_sse.cpp b/alc/mixer/mixer_sse.cpp index 368b8dfe..65eb0dee 100644 --- a/alc/mixer/mixer_sse.cpp +++ b/alc/mixer/mixer_sse.cpp @@ -29,7 +29,8 @@ const ALfloat *Resample_(const InterpState *state, const ALfloa // Calculate the phase index and factor. #define FRAC_PHASE_BITDIFF (FRACTIONBITS-BSINC_PHASE_BITS) const ALuint pi{frac >> FRAC_PHASE_BITDIFF}; - const ALfloat pf{(frac & ((1<(frac & ((1<(const al::span InSamples, const al::span 0) ? 1.0f / static_cast(Counter) : 0.0f}; const bool reached_target{InSamples.size() >= Counter}; const auto min_end = reached_target ? InSamples.begin() + Counter : InSamples.end(); - const auto aligned_end = minz(InSamples.size(), (min_end-InSamples.begin()+3) & ~3u) + - InSamples.begin(); + const auto aligned_end = minz(static_cast(min_end-InSamples.begin()+3) & ~3u, + InSamples.size()) + InSamples.begin(); for(FloatBufferLine &output : OutBuffer) { ALfloat *RESTRICT dst{al::assume_aligned<16>(output.data()+OutPos)}; diff --git a/alc/mixer/mixer_sse2.cpp b/alc/mixer/mixer_sse2.cpp index 38d77fd9..897cd1f7 100644 --- a/alc/mixer/mixer_sse2.cpp +++ b/alc/mixer/mixer_sse2.cpp @@ -72,7 +72,7 @@ const ALfloat *Resample_(const InterpState*, const ALfloat *RES frac = static_cast(_mm_cvtsi128_si32(frac4)); do { - *(dst_iter++) = lerp(src[0], src[1], frac * (1.0f/FRACTIONONE)); + *(dst_iter++) = lerp(src[0], src[1], static_cast(frac) * (1.0f/FRACTIONONE)); frac += increment; src += frac>>FRACTIONBITS; diff --git a/alc/mixer/mixer_sse41.cpp b/alc/mixer/mixer_sse41.cpp index 0a87f76f..cfa21e99 100644 --- a/alc/mixer/mixer_sse41.cpp +++ b/alc/mixer/mixer_sse41.cpp @@ -77,7 +77,7 @@ const ALfloat *Resample_(const InterpState*, const ALfloat *RES frac = static_cast(_mm_cvtsi128_si32(frac4)); do { - *(dst_iter++) = lerp(src[0], src[1], frac * (1.0f/FRACTIONONE)); + *(dst_iter++) = lerp(src[0], src[1], static_cast(frac) * (1.0f/FRACTIONONE)); frac += increment; src += frac>>FRACTIONBITS; diff --git a/alc/mixvoice.cpp b/alc/mixvoice.cpp index 7bdeea5e..d7a32f35 100644 --- a/alc/mixvoice.cpp +++ b/alc/mixvoice.cpp @@ -287,33 +287,35 @@ struct FmtTypeTraits { }; template<> struct FmtTypeTraits { using Type = ALubyte; - static constexpr ALfloat to_float(const Type val) { return (val-128) * (1.0f/128.0f); } + static constexpr ALfloat to_float(const Type val) noexcept + { return val*(1.0f/128.0f) - 128.0f; } }; template<> struct FmtTypeTraits { using Type = ALshort; - static constexpr ALfloat to_float(const Type val) { return val * (1.0f/32768.0f); } + static constexpr ALfloat to_float(const Type val) noexcept { return val*(1.0f/32768.0f); } }; template<> struct FmtTypeTraits { using Type = ALfloat; - static constexpr ALfloat to_float(const Type val) { return val; } + static constexpr ALfloat to_float(const Type val) noexcept { return val; } }; template<> struct FmtTypeTraits { using Type = ALdouble; - static constexpr ALfloat to_float(const Type val) { return static_cast(val); } + static constexpr ALfloat to_float(const Type val) noexcept + { return static_cast(val); } }; template<> struct FmtTypeTraits { using Type = ALubyte; - static constexpr ALfloat to_float(const Type val) + static constexpr ALfloat to_float(const Type val) noexcept { return muLawDecompressionTable[val] * (1.0f/32768.0f); } }; template<> struct FmtTypeTraits { using Type = ALubyte; - static constexpr ALfloat to_float(const Type val) + static constexpr ALfloat to_float(const Type val) noexcept { return aLawDecompressionTable[val] * (1.0f/32768.0f); } }; @@ -363,7 +365,7 @@ const ALfloat *DoFilters(BiquadFilter *lpfilter, BiquadFilter *hpfilter, ALfloat template inline void LoadSampleArray(ALfloat *RESTRICT dst, const al::byte *src, const size_t srcstep, - const size_t samples) + const size_t samples) noexcept { using SampleType = typename FmtTypeTraits::Type; @@ -373,7 +375,7 @@ inline void LoadSampleArray(ALfloat *RESTRICT dst, const al::byte *src, const si } void LoadSamples(ALfloat *RESTRICT dst, const al::byte *src, const size_t srcstep, FmtType srctype, - const size_t samples) + const size_t samples) noexcept { #define HANDLE_FMT(T) case T: LoadSampleArray(dst, src, srcstep, samples); break switch(srctype) diff --git a/common/almalloc.cpp b/common/almalloc.cpp index 8700bddc..842fb400 100644 --- a/common/almalloc.cpp +++ b/common/almalloc.cpp @@ -30,11 +30,11 @@ void *al_malloc(size_t alignment, size_t size) #elif defined(HAVE__ALIGNED_MALLOC) return _aligned_malloc(size, alignment); #else - char *ret = static_cast(malloc(size+alignment)); + auto *ret = static_cast(malloc(size+alignment)); if(ret != nullptr) { *(ret++) = 0x00; - while((reinterpret_cast(ret)&(alignment-1)) != 0) + while((reinterpret_cast(ret)&(alignment-1)) != 0) *(ret++) = 0x55; } return ret; @@ -57,7 +57,7 @@ void al_free(void *ptr) noexcept #else if(ptr != nullptr) { - char *finder = static_cast(ptr); + auto *finder = static_cast(ptr); do { --finder; } while(*finder == 0x55); diff --git a/examples/alrecord.c b/examples/alrecord.c index 627f8540..a66e5471 100644 --- a/examples/alrecord.c +++ b/examples/alrecord.c @@ -54,13 +54,14 @@ static float msvc_strtof(const char *str, char **end) static void fwrite16le(ALushort val, FILE *f) { - ALubyte data[2] = { val&0xff, (val>>8)&0xff }; + ALubyte data[2] = { (ALubyte)(val&0xff), (ALubyte)((val>>8)&0xff) }; fwrite(data, 1, 2, f); } static void fwrite32le(ALuint val, FILE *f) { - ALubyte data[4] = { val&0xff, (val>>8)&0xff, (val>>16)&0xff, (val>>24)&0xff }; + ALubyte data[4] = { (ALubyte)(val&0xff), (ALubyte)((val>>8)&0xff), (ALubyte)((val>>16)&0xff), + (ALubyte)((val>>24)&0xff) }; fwrite(data, 1, 4, f); } diff --git a/examples/altonegen.c b/examples/altonegen.c index aacc3496..26ae788d 100644 --- a/examples/altonegen.c +++ b/examples/altonegen.c @@ -97,7 +97,7 @@ static ALuint CreateWave(enum WaveType type, ALuint freq, ALuint srate) ALenum err; ALuint i; - data_size = srate * sizeof(ALfloat); + data_size = (ALuint)(srate * sizeof(ALfloat)); data = calloc(1, data_size); switch(type) { diff --git a/examples/common/alhelpers.c b/examples/common/alhelpers.c index 730d2e13..0febef43 100644 --- a/examples/common/alhelpers.c +++ b/examples/common/alhelpers.c @@ -175,8 +175,8 @@ int altime_get(void) void al_nssleep(unsigned long nsec) { struct timespec ts, rem; - ts.tv_sec = nsec / 1000000000ul; - ts.tv_nsec = nsec % 1000000000ul; + ts.tv_sec = (time_t)(nsec / 1000000000ul); + ts.tv_nsec = (long)(nsec % 1000000000ul); while(nanosleep(&ts, &rem) == -1 && errno == EINTR) ts = rem; } -- cgit v1.2.3 From 4b8f78a8d633e3f39e2b708184c051465fcfef7d Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 14 Sep 2019 19:42:54 -0700 Subject: Fix a few more GCC warnings --- alc/backends/coreaudio.cpp | 3 ++- alc/backends/opensl.cpp | 6 +++--- alc/backends/wasapi.cpp | 2 ++ alc/mixer/mixer_c.cpp | 2 +- common/alcomplex.cpp | 2 +- examples/almultireverb.c | 4 ++-- utils/openal-info.c | 2 +- 7 files changed, 12 insertions(+), 9 deletions(-) (limited to 'examples') diff --git a/alc/backends/coreaudio.cpp b/alc/backends/coreaudio.cpp index 99b06b7a..3ae9800c 100644 --- a/alc/backends/coreaudio.cpp +++ b/alc/backends/coreaudio.cpp @@ -374,7 +374,8 @@ OSStatus CoreAudioCapture::RecordProc(AudioUnitRenderActionFlags*, audiobuf.list.mNumberBuffers = 2; audiobuf.list.mBuffers[0].mNumberChannels = mFormat.mChannelsPerFrame; audiobuf.list.mBuffers[0].mData = rec_vec.first.buf; - audiobuf.list.mBuffers[0].mDataByteSize = rec_vec.first.len * mFormat.mBytesPerFrame; + audiobuf.list.mBuffers[0].mDataByteSize = static_cast(rec_vec.first.len) * + mFormat.mBytesPerFrame; audiobuf.list.mBuffers[1].mNumberChannels = mFormat.mChannelsPerFrame; audiobuf.list.mBuffers[1].mData = rec_vec.second.buf; audiobuf.list.mBuffers[1].mDataByteSize = remaining * mFormat.mBytesPerFrame; diff --git a/alc/backends/opensl.cpp b/alc/backends/opensl.cpp index 06d5cd40..3a2f455e 100644 --- a/alc/backends/opensl.cpp +++ b/alc/backends/opensl.cpp @@ -681,11 +681,11 @@ ALCenum OpenSLCapture::open(const ALCchar* name) { mFrameSize = mDevice->frameSizeFromFmt(); /* Ensure the total length is at least 100ms */ - ALsizei length{maxi(mDevice->BufferSize, mDevice->Frequency/10)}; + ALuint length{maxu(mDevice->BufferSize, mDevice->Frequency/10)}; /* Ensure the per-chunk length is at least 10ms, and no more than 50ms. */ - ALsizei update_len{clampi(mDevice->BufferSize/3, mDevice->Frequency/100, + ALuint update_len{clampu(mDevice->BufferSize/3, mDevice->Frequency/100, mDevice->Frequency/100*5)}; - ALsizei num_updates{(length+update_len-1) / update_len}; + ALuint num_updates{(length+update_len-1) / update_len}; try { mRing = CreateRingBuffer(num_updates, update_len*mFrameSize, false); diff --git a/alc/backends/wasapi.cpp b/alc/backends/wasapi.cpp index b762da76..0d04d5a7 100644 --- a/alc/backends/wasapi.cpp +++ b/alc/backends/wasapi.cpp @@ -429,6 +429,8 @@ constexpr char MessageStr[static_cast(MsgType::Count)][20]{ /* Proxy interface used by the message handler. */ struct WasapiProxy { + virtual ~WasapiProxy() = default; + virtual HRESULT openProxy() = 0; virtual void closeProxy() = 0; diff --git a/alc/mixer/mixer_c.cpp b/alc/mixer/mixer_c.cpp index 74315dd5..7beab1a9 100644 --- a/alc/mixer/mixer_c.cpp +++ b/alc/mixer/mixer_c.cpp @@ -30,7 +30,7 @@ inline ALfloat do_bsinc(const InterpState &istate, const ALfloat *RESTRICT vals, (1.0f/(1<(istate.bsinc.m)*pi*4}; + const ALfloat *fil{istate.bsinc.filter + istate.bsinc.m*static_cast(pi*4)}; const ALfloat *scd{fil + istate.bsinc.m}; const ALfloat *phd{scd + istate.bsinc.m}; const ALfloat *spd{phd + istate.bsinc.m}; diff --git a/common/alcomplex.cpp b/common/alcomplex.cpp index f77ec203..e5cbe8a0 100644 --- a/common/alcomplex.cpp +++ b/common/alcomplex.cpp @@ -35,7 +35,7 @@ void complex_fft(const al::span> buffer, const double sign) for(size_t i{1u};i < fftsize;i<<=1, step<<=1) { const size_t step2{step >> 1}; - double arg{al::MathDefs::Pi() / step2}; + double arg{al::MathDefs::Pi() / static_cast(step2)}; std::complex w{std::cos(arg), std::sin(arg)*sign}; std::complex u{1.0, 0.0}; diff --git a/examples/almultireverb.c b/examples/almultireverb.c index b967a050..4e3e188f 100644 --- a/examples/almultireverb.c +++ b/examples/almultireverb.c @@ -653,12 +653,12 @@ int main(int argc, char **argv) * Convert the difference to seconds. */ curtime = altime_get(); - timediff = (ALfloat)(curtime - basetime) / 1000.0f; + timediff = (float)(curtime - basetime) / 1000.0f; /* Avoid negative time deltas, in case of non-monotonic clocks. */ if(timediff < 0.0f) timediff = 0.0f; - else while(timediff >= 4.0f*((loops&1)+1)) + else while(timediff >= 4.0f*(float)((loops&1)+1)) { /* For this example, each transition occurs over 4 seconds, and * there's 2 transitions per cycle. diff --git a/utils/openal-info.c b/utils/openal-info.c index cc628b6e..76cdf37d 100644 --- a/utils/openal-info.c +++ b/utils/openal-info.c @@ -53,7 +53,7 @@ static WCHAR *FromUTF8(const char *str) if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0) { - out = calloc(sizeof(WCHAR), len); + out = calloc(sizeof(WCHAR), (unsigned int)(len)); MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len); } return out; -- cgit v1.2.3 From 66565ca7a3cd63e242eedb0141341eb9450f0d4a Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Wed, 18 Sep 2019 10:09:04 -0700 Subject: Enable and fix some more warnings --- CMakeLists.txt | 1 + al/auxeffectslot.cpp | 3 +- al/error.cpp | 3 +- alc/alc.cpp | 33 ++++++++++++---------- alc/hrtf.cpp | 4 +-- common/threads.cpp | 2 +- examples/alhrtf.c | 6 ++-- examples/allatency.c | 26 ++++++++--------- examples/alloopback.c | 8 +++--- examples/almultireverb.c | 72 ++++++++++++++++++++++++------------------------ examples/alreverb.c | 48 ++++++++++++++++---------------- utils/openal-info.c | 4 +-- 12 files changed, 108 insertions(+), 102 deletions(-) (limited to 'examples') diff --git a/CMakeLists.txt b/CMakeLists.txt index 3ef1ca6b..4f6cf010 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -222,6 +222,7 @@ IF(MSVC) ENDIF() ELSE() SET(C_FLAGS ${C_FLAGS} -Winline -Wunused -Wall -Wextra -Wshadow -Wconversion -Wcast-align + -Wpedantic -Wno-zero-length-array $<$:-Wold-style-cast -Wnon-virtual-dtor -Woverloaded-virtual>) IF(ALSOFT_WERROR) diff --git a/al/auxeffectslot.cpp b/al/auxeffectslot.cpp index df35c533..3c312c66 100644 --- a/al/auxeffectslot.cpp +++ b/al/auxeffectslot.cpp @@ -709,7 +709,8 @@ ALeffectslot::~ALeffectslot() if(props) { if(props->State) props->State->release(); - TRACE("Freed unapplied AuxiliaryEffectSlot update %p\n", props); + TRACE("Freed unapplied AuxiliaryEffectSlot update %p\n", + decltype(std::declval()){props}); delete props; } diff --git a/al/error.cpp b/al/error.cpp index f3e2dbb3..b667d14f 100644 --- a/al/error.cpp +++ b/al/error.cpp @@ -67,7 +67,8 @@ void ALCcontext::setError(ALenum errorCode, const char *msg, ...) else msg = ""; msglen = static_cast(strlen(msg)); - WARN("Error generated on context %p, code 0x%04x, \"%s\"\n", this, errorCode, msg); + WARN("Error generated on context %p, code 0x%04x, \"%s\"\n", + decltype(std::declval()){this}, errorCode, msg); if(TrapALError) { #ifdef _WIN32 diff --git a/alc/alc.cpp b/alc/alc.cpp index 8a0a3468..0652f858 100644 --- a/alc/alc.cpp +++ b/alc/alc.cpp @@ -845,8 +845,8 @@ std::atomic LastNullDeviceError{ALC_NO_ERROR}; void ReleaseThreadCtx(ALCcontext *context) { const bool result{context->releaseIfNoDelete()}; - ERR("Context %p current for thread being destroyed%s!\n", context, - result ? "" : ", leak detected"); + ERR("Context %p current for thread being destroyed%s!\n", + decltype(std::declval()){context}, result ? "" : ", leak detected"); } class ThreadCtx { @@ -1567,7 +1567,8 @@ void ALCcontext::processUpdates() */ static void alcSetError(ALCdevice *device, ALCenum errorCode) { - WARN("Error generated on device %p, code 0x%04x\n", device, errorCode); + WARN("Error generated on device %p, code 0x%04x\n", decltype(std::declval()){device}, + errorCode); if(TrapALCError) { #ifdef _WIN32 @@ -2256,7 +2257,7 @@ ALCdevice::ALCdevice(DeviceType type) : Type{type}, mContexts{&EmptyContextArray */ ALCdevice::~ALCdevice() { - TRACE("Freeing device %p\n", this); + TRACE("Freeing device %p\n", decltype(std::declval()){this}); Backend = nullptr; @@ -2311,15 +2312,15 @@ ALCcontext::ALCcontext(al::intrusive_ptr device) : mDevice{std::move( ALCcontext::~ALCcontext() { - TRACE("Freeing context %p\n", this); + TRACE("Freeing context %p\n", decltype(std::declval()){this}); + size_t count{0}; ALcontextProps *cprops{mUpdate.exchange(nullptr, std::memory_order_relaxed)}; if(cprops) { - TRACE("Freed unapplied context update %p\n", cprops); + ++count; delete cprops; } - size_t count{0}; cprops = mFreeContextProps.exchange(nullptr, std::memory_order_acquire); while(cprops) { @@ -2376,13 +2377,13 @@ ALCcontext::~ALCcontext() mVoices.clear(); + count = 0; ALlistenerProps *lprops{mListener.Params.Update.exchange(nullptr, std::memory_order_relaxed)}; if(lprops) { - TRACE("Freed unapplied listener update %p\n", lprops); + ++count; delete lprops; } - count = 0; lprops = mFreeListenerProps.exchange(nullptr, std::memory_order_acquire); while(lprops) { @@ -2462,7 +2463,7 @@ bool ALCcontext::deinit() { if(LocalContext.get() == this) { - WARN("%p released while current on thread\n", this); + WARN("%p released while current on thread\n", decltype(std::declval()){this}); LocalContext.set(nullptr); release(); } @@ -3356,7 +3357,7 @@ START_API_FUNC ERR("Failed to initialize the default effect\n"); } - TRACE("Created context %p\n", context.get()); + TRACE("Created context %p\n", decltype(std::declval()){context.get()}); return context.get(); } END_API_FUNC @@ -3700,7 +3701,8 @@ START_API_FUNC DeviceList.emplace(iter, device); } - TRACE("Created device %p, \"%s\"\n", device.get(), device->DeviceName.c_str()); + TRACE("Created device %p, \"%s\"\n", decltype(std::declval()){device.get()}, + device->DeviceName.c_str()); return device.get(); } END_API_FUNC @@ -3746,7 +3748,7 @@ START_API_FUNC for(ContextRef &context : orphanctxs) { - WARN("Releasing orphaned context %p\n", context.get()); + WARN("Releasing orphaned context %p\n", decltype(std::declval()){context.get()}); context->deinit(); } orphanctxs.clear(); @@ -3829,7 +3831,8 @@ START_API_FUNC DeviceList.emplace(iter, device); } - TRACE("Created device %p, \"%s\"\n", device.get(), device->DeviceName.c_str()); + TRACE("Created capture device %p, \"%s\"\n", decltype(std::declval()){device.get()}, + device->DeviceName.c_str()); return device.get(); } END_API_FUNC @@ -4011,7 +4014,7 @@ START_API_FUNC DeviceList.emplace(iter, device); } - TRACE("Created device %p\n", device.get()); + TRACE("Created loopback device %p\n", decltype(std::declval()){device.get()}); return device.get(); } END_API_FUNC diff --git a/alc/hrtf.cpp b/alc/hrtf.cpp index 7110478d..b925c5dd 100644 --- a/alc/hrtf.cpp +++ b/alc/hrtf.cpp @@ -1363,13 +1363,13 @@ HrtfEntry *GetLoadedHrtf(HrtfHandle *handle) void HrtfEntry::IncRef() { auto ref = IncrementRef(mRef); - TRACE("HrtfEntry %p increasing refcount to %u\n", this, ref); + TRACE("HrtfEntry %p increasing refcount to %u\n", decltype(std::declval()){this}, ref); } void HrtfEntry::DecRef() { auto ref = DecrementRef(mRef); - TRACE("HrtfEntry %p decreasing refcount to %u\n", this, ref); + TRACE("HrtfEntry %p decreasing refcount to %u\n", decltype(std::declval()){this}, ref); if(ref == 0) { std::lock_guard _{LoadedHrtfLock}; diff --git a/common/threads.cpp b/common/threads.cpp index fe34f5b0..ff01de42 100644 --- a/common/threads.cpp +++ b/common/threads.cpp @@ -43,7 +43,7 @@ void althrd_setname(const char *name) #pragma pack(pop) info.dwType = 0x1000; info.szName = name; - info.dwThreadID = -1; + info.dwThreadID = ~DWORD{0}; info.dwFlags = 0; __try { diff --git a/examples/alhrtf.c b/examples/alhrtf.c index f09f3e99..2be28a91 100644 --- a/examples/alhrtf.c +++ b/examples/alhrtf.c @@ -164,9 +164,9 @@ int main(int argc, char **argv) } /* Define a macro to help load the function pointers. */ -#define LOAD_PROC(d, x) ((x) = alcGetProcAddress((d), #x)) - LOAD_PROC(device, alcGetStringiSOFT); - LOAD_PROC(device, alcResetDeviceSOFT); +#define LOAD_PROC(d, T, x) ((x) = (T)alcGetProcAddress((d), #x)) + LOAD_PROC(device, LPALCGETSTRINGISOFT, alcGetStringiSOFT); + LOAD_PROC(device, LPALCRESETDEVICESOFT, alcResetDeviceSOFT); #undef LOAD_PROC /* Check for the AL_EXT_STEREO_ANGLES extension to be able to also rotate diff --git a/examples/allatency.c b/examples/allatency.c index ad700cc1..a61fb820 100644 --- a/examples/allatency.c +++ b/examples/allatency.c @@ -158,19 +158,19 @@ int main(int argc, char **argv) } /* Define a macro to help load the function pointers. */ -#define LOAD_PROC(x) ((x) = alGetProcAddress(#x)) - LOAD_PROC(alSourcedSOFT); - LOAD_PROC(alSource3dSOFT); - LOAD_PROC(alSourcedvSOFT); - LOAD_PROC(alGetSourcedSOFT); - LOAD_PROC(alGetSource3dSOFT); - LOAD_PROC(alGetSourcedvSOFT); - LOAD_PROC(alSourcei64SOFT); - LOAD_PROC(alSource3i64SOFT); - LOAD_PROC(alSourcei64vSOFT); - LOAD_PROC(alGetSourcei64SOFT); - LOAD_PROC(alGetSource3i64SOFT); - LOAD_PROC(alGetSourcei64vSOFT); +#define LOAD_PROC(T, x) ((x) = (T)alGetProcAddress(#x)) + LOAD_PROC(LPALSOURCEDSOFT, alSourcedSOFT); + LOAD_PROC(LPALSOURCE3DSOFT, alSource3dSOFT); + LOAD_PROC(LPALSOURCEDVSOFT, alSourcedvSOFT); + LOAD_PROC(LPALGETSOURCEDSOFT, alGetSourcedSOFT); + LOAD_PROC(LPALGETSOURCE3DSOFT, alGetSource3dSOFT); + LOAD_PROC(LPALGETSOURCEDVSOFT, alGetSourcedvSOFT); + LOAD_PROC(LPALSOURCEI64SOFT, alSourcei64SOFT); + LOAD_PROC(LPALSOURCE3I64SOFT, alSource3i64SOFT); + LOAD_PROC(LPALSOURCEI64VSOFT, alSourcei64vSOFT); + LOAD_PROC(LPALGETSOURCEI64SOFT, alGetSourcei64SOFT); + LOAD_PROC(LPALGETSOURCE3I64SOFT, alGetSource3i64SOFT); + LOAD_PROC(LPALGETSOURCEI64VSOFT, alGetSourcei64vSOFT); #undef LOAD_PROC /* Initialize SDL_sound. */ diff --git a/examples/alloopback.c b/examples/alloopback.c index 426a2af9..844efa74 100644 --- a/examples/alloopback.c +++ b/examples/alloopback.c @@ -149,10 +149,10 @@ int main(int argc, char *argv[]) } /* Define a macro to help load the function pointers. */ -#define LOAD_PROC(x) ((x) = alcGetProcAddress(NULL, #x)) - LOAD_PROC(alcLoopbackOpenDeviceSOFT); - LOAD_PROC(alcIsRenderFormatSupportedSOFT); - LOAD_PROC(alcRenderSamplesSOFT); +#define LOAD_PROC(T, x) ((x) = (T)alcGetProcAddress(NULL, #x)) + LOAD_PROC(LPALCLOOPBACKOPENDEVICESOFT, alcLoopbackOpenDeviceSOFT); + LOAD_PROC(LPALCISRENDERFORMATSUPPORTEDSOFT, alcIsRenderFormatSupportedSOFT); + LOAD_PROC(LPALCRENDERSAMPLESSOFT, alcRenderSamplesSOFT); #undef LOAD_PROC if(SDL_Init(SDL_INIT_AUDIO) == -1) diff --git a/examples/almultireverb.c b/examples/almultireverb.c index 4e3e188f..a90b3368 100644 --- a/examples/almultireverb.c +++ b/examples/almultireverb.c @@ -523,42 +523,42 @@ int main(int argc, char **argv) } /* Define a macro to help load the function pointers. */ -#define LOAD_PROC(x) ((x) = alGetProcAddress(#x)) - LOAD_PROC(alGenFilters); - LOAD_PROC(alDeleteFilters); - LOAD_PROC(alIsFilter); - LOAD_PROC(alFilteri); - LOAD_PROC(alFilteriv); - LOAD_PROC(alFilterf); - LOAD_PROC(alFilterfv); - LOAD_PROC(alGetFilteri); - LOAD_PROC(alGetFilteriv); - LOAD_PROC(alGetFilterf); - LOAD_PROC(alGetFilterfv); - - LOAD_PROC(alGenEffects); - LOAD_PROC(alDeleteEffects); - LOAD_PROC(alIsEffect); - LOAD_PROC(alEffecti); - LOAD_PROC(alEffectiv); - LOAD_PROC(alEffectf); - LOAD_PROC(alEffectfv); - LOAD_PROC(alGetEffecti); - LOAD_PROC(alGetEffectiv); - LOAD_PROC(alGetEffectf); - LOAD_PROC(alGetEffectfv); - - LOAD_PROC(alGenAuxiliaryEffectSlots); - LOAD_PROC(alDeleteAuxiliaryEffectSlots); - LOAD_PROC(alIsAuxiliaryEffectSlot); - LOAD_PROC(alAuxiliaryEffectSloti); - LOAD_PROC(alAuxiliaryEffectSlotiv); - LOAD_PROC(alAuxiliaryEffectSlotf); - LOAD_PROC(alAuxiliaryEffectSlotfv); - LOAD_PROC(alGetAuxiliaryEffectSloti); - LOAD_PROC(alGetAuxiliaryEffectSlotiv); - LOAD_PROC(alGetAuxiliaryEffectSlotf); - LOAD_PROC(alGetAuxiliaryEffectSlotfv); +#define LOAD_PROC(T, x) ((x) = (T)alGetProcAddress(#x)) + LOAD_PROC(LPALGENFILTERS, alGenFilters); + LOAD_PROC(LPALDELETEFILTERS, alDeleteFilters); + LOAD_PROC(LPALISFILTER, alIsFilter); + LOAD_PROC(LPALFILTERI, alFilteri); + LOAD_PROC(LPALFILTERIV, alFilteriv); + LOAD_PROC(LPALFILTERF, alFilterf); + LOAD_PROC(LPALFILTERFV, alFilterfv); + LOAD_PROC(LPALGETFILTERI, alGetFilteri); + LOAD_PROC(LPALGETFILTERIV, alGetFilteriv); + LOAD_PROC(LPALGETFILTERF, alGetFilterf); + LOAD_PROC(LPALGETFILTERFV, alGetFilterfv); + + LOAD_PROC(LPALGENEFFECTS, alGenEffects); + LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects); + LOAD_PROC(LPALISEFFECT, alIsEffect); + LOAD_PROC(LPALEFFECTI, alEffecti); + LOAD_PROC(LPALEFFECTIV, alEffectiv); + LOAD_PROC(LPALEFFECTF, alEffectf); + LOAD_PROC(LPALEFFECTFV, alEffectfv); + LOAD_PROC(LPALGETEFFECTI, alGetEffecti); + LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv); + LOAD_PROC(LPALGETEFFECTF, alGetEffectf); + LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv); + + LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots); + LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots); + LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot); + LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti); + LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv); + LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf); + LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv); + LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti); + LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv); + LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf); + LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv); #undef LOAD_PROC /* Initialize SDL_sound. */ diff --git a/examples/alreverb.c b/examples/alreverb.c index 68f0269f..d789dffe 100644 --- a/examples/alreverb.c +++ b/examples/alreverb.c @@ -252,30 +252,30 @@ int main(int argc, char **argv) } /* Define a macro to help load the function pointers. */ -#define LOAD_PROC(x) ((x) = alGetProcAddress(#x)) - LOAD_PROC(alGenEffects); - LOAD_PROC(alDeleteEffects); - LOAD_PROC(alIsEffect); - LOAD_PROC(alEffecti); - LOAD_PROC(alEffectiv); - LOAD_PROC(alEffectf); - LOAD_PROC(alEffectfv); - LOAD_PROC(alGetEffecti); - LOAD_PROC(alGetEffectiv); - LOAD_PROC(alGetEffectf); - LOAD_PROC(alGetEffectfv); - - LOAD_PROC(alGenAuxiliaryEffectSlots); - LOAD_PROC(alDeleteAuxiliaryEffectSlots); - LOAD_PROC(alIsAuxiliaryEffectSlot); - LOAD_PROC(alAuxiliaryEffectSloti); - LOAD_PROC(alAuxiliaryEffectSlotiv); - LOAD_PROC(alAuxiliaryEffectSlotf); - LOAD_PROC(alAuxiliaryEffectSlotfv); - LOAD_PROC(alGetAuxiliaryEffectSloti); - LOAD_PROC(alGetAuxiliaryEffectSlotiv); - LOAD_PROC(alGetAuxiliaryEffectSlotf); - LOAD_PROC(alGetAuxiliaryEffectSlotfv); +#define LOAD_PROC(T, x) ((x) = (T)alGetProcAddress(#x)) + LOAD_PROC(LPALGENEFFECTS, alGenEffects); + LOAD_PROC(LPALDELETEEFFECTS, alDeleteEffects); + LOAD_PROC(LPALISEFFECT, alIsEffect); + LOAD_PROC(LPALEFFECTI, alEffecti); + LOAD_PROC(LPALEFFECTIV, alEffectiv); + LOAD_PROC(LPALEFFECTF, alEffectf); + LOAD_PROC(LPALEFFECTFV, alEffectfv); + LOAD_PROC(LPALGETEFFECTI, alGetEffecti); + LOAD_PROC(LPALGETEFFECTIV, alGetEffectiv); + LOAD_PROC(LPALGETEFFECTF, alGetEffectf); + LOAD_PROC(LPALGETEFFECTFV, alGetEffectfv); + + LOAD_PROC(LPALGENAUXILIARYEFFECTSLOTS, alGenAuxiliaryEffectSlots); + LOAD_PROC(LPALDELETEAUXILIARYEFFECTSLOTS, alDeleteAuxiliaryEffectSlots); + LOAD_PROC(LPALISAUXILIARYEFFECTSLOT, alIsAuxiliaryEffectSlot); + LOAD_PROC(LPALAUXILIARYEFFECTSLOTI, alAuxiliaryEffectSloti); + LOAD_PROC(LPALAUXILIARYEFFECTSLOTIV, alAuxiliaryEffectSlotiv); + LOAD_PROC(LPALAUXILIARYEFFECTSLOTF, alAuxiliaryEffectSlotf); + LOAD_PROC(LPALAUXILIARYEFFECTSLOTFV, alAuxiliaryEffectSlotfv); + LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTI, alGetAuxiliaryEffectSloti); + LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTIV, alGetAuxiliaryEffectSlotiv); + LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTF, alGetAuxiliaryEffectSlotf); + LOAD_PROC(LPALGETAUXILIARYEFFECTSLOTFV, alGetAuxiliaryEffectSlotfv); #undef LOAD_PROC /* Initialize SDL_sound. */ diff --git a/utils/openal-info.c b/utils/openal-info.c index 76cdf37d..cdce77e0 100644 --- a/utils/openal-info.c +++ b/utils/openal-info.c @@ -223,7 +223,7 @@ static void printHRTFInfo(ALCdevice *device) return; } - alcGetStringiSOFT = alcGetProcAddress(device, "alcGetStringiSOFT"); + alcGetStringiSOFT = (LPALCGETSTRINGISOFT)alcGetProcAddress(device, "alcGetStringiSOFT"); alcGetIntegerv(device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num_hrtfs); if(!num_hrtfs) @@ -263,7 +263,7 @@ static void printResamplerInfo(void) return; } - alGetStringiSOFT = alGetProcAddress("alGetStringiSOFT"); + alGetStringiSOFT = (LPALGETSTRINGISOFT)alGetProcAddress("alGetStringiSOFT"); num_resamplers = alGetInteger(AL_NUM_RESAMPLERS_SOFT); def_resampler = alGetInteger(AL_DEFAULT_RESAMPLER_SOFT); -- cgit v1.2.3 From e70f98c95afc61802b26795dbe8aeb20514a211b Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 12 Oct 2019 16:41:13 -0700 Subject: Wrap the cycle amount when passing to sin() --- examples/altonegen.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/altonegen.c b/examples/altonegen.c index 26ae788d..553bc996 100644 --- a/examples/altonegen.c +++ b/examples/altonegen.c @@ -82,7 +82,10 @@ static void ApplySin(ALfloat *data, ALdouble g, ALuint srate, ALuint freq) ALdouble smps_per_cycle = (ALdouble)srate / freq; ALuint i; for(i = 0;i < srate;i++) - data[i] += (ALfloat)(sin(i/smps_per_cycle * 2.0*M_PI) * g); + { + ALdouble ival; + data[i] += (ALfloat)(sin(modf(i/smps_per_cycle, &ival) * 2.0*M_PI) * g); + } } /* Generates waveforms using additive synthesis. Each waveform is constructed -- cgit v1.2.3