C: mem. for audio: optimize; use the same function

Memory allocation for the audio buffer:
1. Instant mode: Use `malloc` instead of `calloc`
2. Allocate heap memory before the loop to speed up audio generation, free
   the memory after the loop
3. Extract the memory allocation into a macro
This commit is contained in:
Intel A80486DX2-66 2024-01-29 19:07:06 +03:00
parent edd95e5af0
commit 551933cddd
Signed by: 80486DX2-66
GPG Key ID: 83631EF27054609B
1 changed files with 24 additions and 17 deletions

View File

@ -52,6 +52,17 @@ const char* ANSI_CLEAR = __ANSI_CLEAR_STRING;
#define unsigned_to_signed(x) (x - PCM_COEFFICIENT)
#define signed_to_unsigned(x) (x + PCM_COEFFICIENT)
// macros
#define ALLOCATE_MEMORY(nmemb) \
SAMPLE_TYPE* buffer = malloc( \
(size_t) nmemb * sizeof(SAMPLE_TYPE) \
); \
\
if (buffer == NULL) { \
perror("malloc"); \
return EXIT_FAILURE; \
}
// global variables
#define SILENT_MODE `silent_mode`
#define VERBOSE_MODE `verbose_mode`
@ -198,28 +209,24 @@ main(void)
}
const size_t MAX = (PRODUCT + (BLOCK_SIZE - 1)) / BLOCK_SIZE;
#endif
// * allocate heap for sample data
#if SEQUENTIAL_MODE
size_t calc_block_size = BLOCK_SIZE;
ALLOCATE_MEMORY(calc_block_size)
#else
ALLOCATE_MEMORY(PRODUCT)
#endif
#if SEQUENTIAL_MODE
size_t w = 0;
for (size_t seq = 0; seq < MAX; seq++) {
size_t calc_block_size = BLOCK_SIZE;
if ((w + BLOCK_SIZE) >= PRODUCT)
calc_block_size = PRODUCT - w;
#else
do {
#endif
// * allocate heap for sample data
SAMPLE_TYPE* buffer =
#if SEQUENTIAL_MODE
malloc((size_t) calc_block_size *
#else
calloc(PRODUCT,
#endif
sizeof(SAMPLE_TYPE));
if (buffer == NULL) {
perror("calloc");
return 1;
}
// * bytebeat generating loop
const uintmax_t product_minus_1 = PRODUCT - 1,
@ -324,14 +331,14 @@ main(void)
#if SEQUENTIAL_MODE
fflush(output_file);
#endif
// * free allocated heap
free(buffer);
}
#if !SEQUENTIAL_MODE
while (0);
#endif
// * free allocated heap
free(buffer);
// 6. close file
fclose(output_file);