chvol
Simple interface to set PulseAudio's volume, with graphical feedback! 🔊
- Commit
- 50b8e64aaf48c60685e1312a3fe6790e1610ff91
-
- Parent
- 2f22f01864ff34f07be09c99acb90fc04dff131d
-
- Author
- Pablo <pablo-pie@riseup.net>
- Date
Added a compile time configuration file
Created a compile time configuration file and wrote a parser and code generation script
Merged "generate-pcm.c" into this script
Diffstats
11 files changed, 1302 insertions, 152 deletions
diff --git a/assets/audio-volume-change.ogg /dev/null
Binary files differ
diff --git a/nob.c b/nob.c
@@ -13,22 +13,23 @@
#define SRC_PATH SRC_DIR "main.c"
#define OUTPUT_PATH BUILD_DIR "chvol"
-#define GENERATE_PCM_OUTPUT_PATH BUILD_DIR "generate-pcm"
-#define GENERATE_PCM_SRC_PATH SRC_DIR "generate-pcm.c"
+#define CONFIGURE_OUTPUT_PATH BUILD_DIR "configure"
+#define CONFIGURE_SRC_PATH SRC_DIR "configure.c"
+#define CONFIG_PATH "./chvol.conf"
-#define PCM_SRC_PATH BUILD_SRC_DIR "pcm.c"
-
-#define MAN_SRC_PATH "chvol.1"
-#define MAN_BUILD_PATH BUILD_DIR MAN_SRC_PATH
+#define MAN_SRC_PATH "./chvol.1"
+#define MAN_BUILD_PATH BUILD_DIR MAN_SRC_PATH ".gz"
#define OPTS "-Wall", "-Wextra", "-pedantic", "-I" SRC_DIR, "-I" BUILD_SRC_DIR
const char* srcs[] = {
SRC_PATH,
+ SRC_DIR "pcm.h",
+ CONFIG_PATH,
MAN_SRC_PATH,
- GENERATE_PCM_SRC_PATH,
- PCM_SRC_PATH,
- ASSETS_DIR "audio-volume-change.ogg",
+
+ ASSETS_DIR "volume-change.ogg",
+ CONFIGURE_SRC_PATH,
};
int main(int argc, char** argv)
@@ -39,13 +40,13 @@ int main(int argc, char** argv)
Cmd cmd = {0};
if (needs_rebuild(OUTPUT_PATH, srcs, ARRAY_LEN(srcs))) {
- cmd_append(&cmd, "cc", GENERATE_PCM_SRC_PATH);
- cmd_append(&cmd, "-o", GENERATE_PCM_OUTPUT_PATH);
+ cmd_append(&cmd, "cc", CONFIGURE_SRC_PATH);
+ cmd_append(&cmd, "-o", CONFIGURE_OUTPUT_PATH);
cmd_append(&cmd, OPTS);
cmd_append(&cmd, "-lvorbisfile", "-lvorbis");
if (!cmd_run(&cmd)) return EXIT_FAILURE;
- cmd_append(&cmd, GENERATE_PCM_OUTPUT_PATH);
+ cmd_append(&cmd, CONFIGURE_OUTPUT_PATH, CONFIG_PATH);
if (!cmd_run(&cmd)) return EXIT_FAILURE;
cmd_append(&cmd, "cc", SRC_PATH, "-o", OUTPUT_PATH);
diff --git /dev/null b/src/arena.h
@@ -0,0 +1,451 @@
+// Copyright 2022 Alexey Kutepov <reximkut@gmail.com>
+
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+#ifndef ARENA_H_
+#define ARENA_H_
+
+#include <stddef.h>
+#include <stdint.h>
+
+#ifndef ARENA_NOSTDIO
+#include <stdarg.h>
+#include <stdio.h>
+#endif // ARENA_NOSTDIO
+
+#ifndef ARENA_ASSERT
+#include <assert.h>
+#define ARENA_ASSERT assert
+#endif
+
+#define ARENA_BACKEND_LIBC_MALLOC 0
+#define ARENA_BACKEND_LINUX_MMAP 1
+#define ARENA_BACKEND_WIN32_VIRTUALALLOC 2
+#define ARENA_BACKEND_WASM_HEAPBASE 3
+
+#ifndef ARENA_BACKEND
+#define ARENA_BACKEND ARENA_BACKEND_LIBC_MALLOC
+#endif // ARENA_BACKEND
+
+typedef struct Region Region;
+
+struct Region {
+ Region *next;
+ size_t count;
+ size_t capacity;
+ uintptr_t data[];
+};
+
+typedef struct {
+ Region *begin, *end;
+} Arena;
+
+typedef struct {
+ Region *region;
+ size_t count;
+} Arena_Mark;
+
+#ifndef ARENA_REGION_DEFAULT_CAPACITY
+#define ARENA_REGION_DEFAULT_CAPACITY (8*1024)
+#endif // ARENA_REGION_DEFAULT_CAPACITY
+
+Region *new_region(size_t capacity);
+void free_region(Region *r);
+
+void *arena_alloc(Arena *a, size_t size_bytes);
+void *arena_realloc(Arena *a, void *oldptr, size_t oldsz, size_t newsz);
+char *arena_strdup(Arena *a, const char *cstr);
+void *arena_memdup(Arena *a, void *data, size_t size);
+void *arena_memcpy(void *dest, const void *src, size_t n);
+#ifndef ARENA_NOSTDIO
+char *arena_sprintf(Arena *a, const char *format, ...);
+char *arena_vsprintf(Arena *a, const char *format, va_list args);
+#endif // ARENA_NOSTDIO
+
+Arena_Mark arena_snapshot(Arena *a);
+void arena_reset(Arena *a);
+void arena_rewind(Arena *a, Arena_Mark m);
+void arena_free(Arena *a);
+void arena_trim(Arena *a);
+
+#ifndef ARENA_DA_INIT_CAP
+#define ARENA_DA_INIT_CAP 256
+#endif // ARENA_DA_INIT_CAP
+
+#ifdef __cplusplus
+ #define cast_ptr(ptr) (decltype(ptr))
+#else
+ #define cast_ptr(...)
+#endif
+
+#define arena_da_append(a, da, item) \
+ do { \
+ if ((da)->count >= (da)->capacity) { \
+ size_t new_capacity = (da)->capacity == 0 ? ARENA_DA_INIT_CAP : (da)->capacity*2; \
+ (da)->items = cast_ptr((da)->items)arena_realloc( \
+ (a), (da)->items, \
+ (da)->capacity*sizeof(*(da)->items), \
+ new_capacity*sizeof(*(da)->items)); \
+ (da)->capacity = new_capacity; \
+ } \
+ \
+ (da)->items[(da)->count++] = (item); \
+ } while (0)
+
+// Append several items to a dynamic array
+#define arena_da_append_many(a, da, new_items, new_items_count) \
+ do { \
+ if ((da)->count + (new_items_count) > (da)->capacity) { \
+ size_t new_capacity = (da)->capacity; \
+ if (new_capacity == 0) new_capacity = ARENA_DA_INIT_CAP; \
+ while ((da)->count + (new_items_count) > new_capacity) new_capacity *= 2; \
+ (da)->items = cast_ptr((da)->items)arena_realloc( \
+ (a), (da)->items, \
+ (da)->capacity*sizeof(*(da)->items), \
+ new_capacity*sizeof(*(da)->items)); \
+ (da)->capacity = new_capacity; \
+ } \
+ arena_memcpy((da)->items + (da)->count, (new_items), (new_items_count)*sizeof(*(da)->items)); \
+ (da)->count += (new_items_count); \
+ } while (0)
+
+// Append a sized buffer to a string builder
+#define arena_sb_append_buf arena_da_append_many
+
+// Append a NULL-terminated string to a string builder
+#define arena_sb_append_cstr(a, sb, cstr) \
+ do { \
+ const char *s = (cstr); \
+ size_t n = arena_strlen(s); \
+ arena_da_append_many(a, sb, s, n); \
+ } while (0)
+
+// Append a single NULL character at the end of a string builder. So then you can
+// use it a NULL-terminated C string
+#define arena_sb_append_null(a, sb) arena_da_append(a, sb, 0)
+
+#endif // ARENA_H_
+
+#ifdef ARENA_IMPLEMENTATION
+
+#if ARENA_BACKEND == ARENA_BACKEND_LIBC_MALLOC
+#include <stdlib.h>
+
+// TODO: instead of accepting specific capacity new_region() should accept the size of the object we want to fit into the region
+// It should be up to new_region() to decide the actual capacity to allocate
+Region *new_region(size_t capacity)
+{
+ size_t size_bytes = sizeof(Region) + sizeof(uintptr_t)*capacity;
+ // TODO: it would be nice if we could guarantee that the regions are allocated by ARENA_BACKEND_LIBC_MALLOC are page aligned
+ Region *r = (Region*)malloc(size_bytes);
+ ARENA_ASSERT(r); // TODO: since ARENA_ASSERT is disableable go through all the places where we use it to check for failed memory allocation and return with NULL there.
+ r->next = NULL;
+ r->count = 0;
+ r->capacity = capacity;
+ return r;
+}
+
+void free_region(Region *r)
+{
+ free(r);
+}
+#elif ARENA_BACKEND == ARENA_BACKEND_LINUX_MMAP
+#include <unistd.h>
+#include <sys/mman.h>
+
+Region *new_region(size_t capacity)
+{
+ size_t size_bytes = sizeof(Region) + sizeof(uintptr_t) * capacity;
+ Region *r = mmap(NULL, size_bytes, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ ARENA_ASSERT(r != MAP_FAILED);
+ r->next = NULL;
+ r->count = 0;
+ r->capacity = capacity;
+ return r;
+}
+
+void free_region(Region *r)
+{
+ size_t size_bytes = sizeof(Region) + sizeof(uintptr_t) * r->capacity;
+ int ret = munmap(r, size_bytes);
+ ARENA_ASSERT(ret == 0);
+}
+
+#elif ARENA_BACKEND == ARENA_BACKEND_WIN32_VIRTUALALLOC
+
+#if !defined(_WIN32)
+# error "Current platform is not Windows"
+#endif
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+
+#define INV_HANDLE(x) (((x) == NULL) || ((x) == INVALID_HANDLE_VALUE))
+
+Region *new_region(size_t capacity)
+{
+ SIZE_T size_bytes = sizeof(Region) + sizeof(uintptr_t) * capacity;
+ Region *r = VirtualAllocEx(
+ GetCurrentProcess(), /* Allocate in current process address space */
+ NULL, /* Unknown position */
+ size_bytes, /* Bytes to allocate */
+ MEM_COMMIT | MEM_RESERVE, /* Reserve and commit allocated page */
+ PAGE_READWRITE /* Permissions ( Read/Write )*/
+ );
+ if (INV_HANDLE(r))
+ ARENA_ASSERT(0 && "VirtualAllocEx() failed.");
+
+ r->next = NULL;
+ r->count = 0;
+ r->capacity = capacity;
+ return r;
+}
+
+void free_region(Region *r)
+{
+ if (INV_HANDLE(r))
+ return;
+
+ BOOL free_result = VirtualFreeEx(
+ GetCurrentProcess(), /* Deallocate from current process address space */
+ (LPVOID)r, /* Address to deallocate */
+ 0, /* Bytes to deallocate ( Unknown, deallocate entire page ) */
+ MEM_RELEASE /* Release the page ( And implicitly decommit it ) */
+ );
+
+ if (FALSE == free_result)
+ ARENA_ASSERT(0 && "VirtualFreeEx() failed.");
+}
+
+#elif ARENA_BACKEND == ARENA_BACKEND_WASM_HEAPBASE
+
+// Stolen from https://surma.dev/things/c-to-webassembly/
+
+extern unsigned char __heap_base;
+// Since ARENA_BACKEND_WASM_HEAPBASE entirely hijacks __heap_base it is expected that no other means of memory
+// allocation are used except the arenas.
+unsigned char* bump_pointer = &__heap_base;
+// TODO: provide a way to deallocate all the arenas at once by setting bump_pointer back to &__heap_base?
+
+// __builtin_wasm_memory_size and __builtin_wasm_memory_grow are defined in units of page sizes
+#define ARENA_WASM_PAGE_SIZE (64*1024)
+
+Region *new_region(size_t capacity)
+{
+ size_t size_bytes = sizeof(Region) + sizeof(uintptr_t)*capacity;
+ Region *r = (void*)bump_pointer;
+
+ // grow memory brk() style
+ size_t current_memory_size = ARENA_WASM_PAGE_SIZE * __builtin_wasm_memory_size(0);
+ size_t desired_memory_size = (size_t) bump_pointer + size_bytes;
+ if (desired_memory_size > current_memory_size) {
+ size_t delta_bytes = desired_memory_size - current_memory_size;
+ size_t delta_pages = (delta_bytes + (ARENA_WASM_PAGE_SIZE - 1))/ARENA_WASM_PAGE_SIZE;
+ if (__builtin_wasm_memory_grow(0, delta_pages) < 0) {
+ ARENA_ASSERT(0 && "memory.grow failed");
+ return NULL;
+ }
+ }
+
+ bump_pointer += size_bytes;
+
+ r->next = NULL;
+ r->count = 0;
+ r->capacity = capacity;
+ return r;
+}
+
+void free_region(Region *r)
+{
+ // Since ARENA_BACKEND_WASM_HEAPBASE uses a primitive bump allocator to
+ // allocate the regions, free_region() does nothing. It is generally
+ // not recommended to free arenas anyway since it is better to keep
+ // reusing already allocated memory with arena_reset().
+ (void) r;
+}
+
+#else
+# error "Unknown Arena backend"
+#endif
+
+// TODO: add debug statistic collection mode for arena
+// Should collect things like:
+// - How many times new_region was called
+// - How many times existing region was skipped
+// - How many times allocation exceeded ARENA_REGION_DEFAULT_CAPACITY
+
+void *arena_alloc(Arena *a, size_t size_bytes)
+{
+ size_t size = (size_bytes + sizeof(uintptr_t) - 1)/sizeof(uintptr_t);
+
+ if (a->end == NULL) {
+ ARENA_ASSERT(a->begin == NULL);
+ size_t capacity = ARENA_REGION_DEFAULT_CAPACITY;
+ if (capacity < size) capacity = size;
+ a->end = new_region(capacity);
+ a->begin = a->end;
+ }
+
+ while (a->end->count + size > a->end->capacity && a->end->next != NULL) {
+ a->end = a->end->next;
+ }
+
+ if (a->end->count + size > a->end->capacity) {
+ ARENA_ASSERT(a->end->next == NULL);
+ size_t capacity = ARENA_REGION_DEFAULT_CAPACITY;
+ if (capacity < size) capacity = size;
+ a->end->next = new_region(capacity);
+ a->end = a->end->next;
+ }
+
+ void *result = &a->end->data[a->end->count];
+ a->end->count += size;
+ return result;
+}
+
+void *arena_realloc(Arena *a, void *oldptr, size_t oldsz, size_t newsz)
+{
+ if (newsz <= oldsz) return oldptr;
+ void *newptr = arena_alloc(a, newsz);
+ char *newptr_char = (char*)newptr;
+ char *oldptr_char = (char*)oldptr;
+ for (size_t i = 0; i < oldsz; ++i) {
+ newptr_char[i] = oldptr_char[i];
+ }
+ return newptr;
+}
+
+size_t arena_strlen(const char *s)
+{
+ size_t n = 0;
+ while (*s++) n++;
+ return n;
+}
+
+void *arena_memcpy(void *dest, const void *src, size_t n)
+{
+ char *d = dest;
+ const char *s = src;
+ for (; n; n--) *d++ = *s++;
+ return dest;
+}
+
+char *arena_strdup(Arena *a, const char *cstr)
+{
+ size_t n = arena_strlen(cstr);
+ char *dup = (char*)arena_alloc(a, n + 1);
+ arena_memcpy(dup, cstr, n);
+ dup[n] = '\0';
+ return dup;
+}
+
+void *arena_memdup(Arena *a, void *data, size_t size)
+{
+ return arena_memcpy(arena_alloc(a, size), data, size);
+}
+
+#ifndef ARENA_NOSTDIO
+char *arena_vsprintf(Arena *a, const char *format, va_list args)
+{
+ va_list args_copy;
+ va_copy(args_copy, args);
+ int n = vsnprintf(NULL, 0, format, args_copy);
+ va_end(args_copy);
+
+ ARENA_ASSERT(n >= 0);
+ char *result = (char*)arena_alloc(a, n + 1);
+ vsnprintf(result, n + 1, format, args);
+
+ return result;
+}
+
+char *arena_sprintf(Arena *a, const char *format, ...)
+{
+ va_list args;
+ va_start(args, format);
+ char *result = arena_vsprintf(a, format, args);
+ va_end(args);
+
+ return result;
+}
+#endif // ARENA_NOSTDIO
+
+Arena_Mark arena_snapshot(Arena *a)
+{
+ Arena_Mark m;
+ if(a->end == NULL){ //snapshot of uninitialized arena
+ ARENA_ASSERT(a->begin == NULL);
+ m.region = a->end;
+ m.count = 0;
+ }else{
+ m.region = a->end;
+ m.count = a->end->count;
+ }
+
+ return m;
+}
+
+void arena_reset(Arena *a)
+{
+ for (Region *r = a->begin; r != NULL; r = r->next) {
+ r->count = 0;
+ }
+
+ a->end = a->begin;
+}
+
+void arena_rewind(Arena *a, Arena_Mark m)
+{
+ if(m.region == NULL){ //snapshot of uninitialized arena
+ arena_reset(a); //leave allocation
+ return;
+ }
+
+ m.region->count = m.count;
+ for (Region *r = m.region->next; r != NULL; r = r->next) {
+ r->count = 0;
+ }
+
+ a->end = m.region;
+}
+
+void arena_free(Arena *a)
+{
+ Region *r = a->begin;
+ while (r) {
+ Region *r0 = r;
+ r = r->next;
+ free_region(r0);
+ }
+ a->begin = NULL;
+ a->end = NULL;
+}
+
+void arena_trim(Arena *a){
+ Region *r = a->end->next;
+ while (r) {
+ Region *r0 = r;
+ r = r->next;
+ free_region(r0);
+ }
+ a->end->next = NULL;
+}
+
+#endif // ARENA_IMPLEMENTATION
diff --git /dev/null b/src/configure.c
@@ -0,0 +1,798 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+
+#include <vorbis/vorbisfile.h>
+
+#define ARENA_IMPLEMENTATION
+#include "arena.h"
+#include "pcm.h"
+
+#define OUTPUT_PATH "./build/src/config.h"
+
+#define BOLD_WHITE "\x1b[1;37m"
+#define BOLD_RED "\x1b[1;31m"
+#define BOLD_YELLOW "\x1b[1;33m"
+#define RESET "\x1b[0m"
+
+// NOTE: using GNU extension for ##__VA_ARGS__
+#define report(fmt, ...) \
+ fprintf(stderr, BOLD_WHITE "configure: " BOLD_RED "error: " RESET fmt "\n", \
+ ##__VA_ARGS__)
+
+typedef struct {
+ size_t window_width;
+ size_t window_height;
+ size_t window_progress_height;
+ size_t window_padding;
+ size_t window_border;
+ size_t window_timeout_ms;
+
+ size_t volume_inc;
+ size_t volume_cap;
+ const char* volume_audio_sample;
+
+ size_t color_background;
+ size_t color_light_background;
+ size_t color_accent;
+ size_t color_warning;
+} Config;
+
+bool parse_config(const char* path, Config* config);
+bool parse_sample(const char* path, PCM* pcm);
+
+int main(int argc, char** argv)
+{
+ if (argc < 2) {
+ report("No config file provided");
+ return EXIT_FAILURE;
+ }
+
+ const char* path = (const char*)argv[1];
+
+ Config config;
+ PCM sample;
+ if (!parse_config(path, &config)) return EXIT_FAILURE;
+ if (!parse_sample(config.volume_audio_sample, &sample))
+ return EXIT_FAILURE;
+
+ FILE* f = fopen(OUTPUT_PATH, "w");
+ if (!f) {
+ report("Could not open \"%s\": %s", OUTPUT_PATH, strerror(errno));
+ return EXIT_FAILURE;
+ }
+
+ fprintf(f, "#include \"pcm.h\"\n\n");
+
+ fprintf(f, "#define WIN_WIDTH %zu\n", config.window_width);
+ fprintf(f, "#define WIN_HEIGHT %zu\n", config.window_height);
+ fprintf(f, "#define WIN_PROGRESS_HEIGHT %zu\n", config.window_progress_height);
+ fprintf(f, "#define WIN_PADDING %zu\n", config.window_padding);
+ fprintf(f, "#define WIN_BORDER %zu\n", config.window_border);
+ fprintf(f, "#define WIN_TIMEOUT_MS %zu\n\n", config.window_timeout_ms);
+
+ fprintf(f, "#define VOLUME_INC %zu\n", config.volume_inc);
+ fprintf(f, "#define VOLUME_CAP %zu\n\n", config.volume_cap);
+
+ fprintf(f, "#define COLOR_BACKGROUND 0xFF%lX\n", config.color_background);
+ fprintf(f, "#define COLOR_LIGHT_BACKGROUND 0xFF%lX\n", config.color_light_background);
+ fprintf(f, "#define COLOR_ACCENT 0xFF%lX\n", config.color_accent);
+ fprintf(f, "#define COLOR_WARNING 0xFF%lX\n\n", config.color_warning);
+
+ fprintf(f, "int16_t volume_change_samples_buff[%zu] = {",
+ sample.samples_len);
+ for (size_t i = 0; i < sample.samples_len; i++) {
+ if (i % 8 == 0) fprintf(f, "\n ");
+ else fprintf(f, " ");
+ if (sample.samples[i] >= 0) fprintf(f, " 0x%04X,", sample.samples[i]);
+ else fprintf(f, "-0x%04X,", -sample.samples[i]);
+
+ }
+ fprintf(f, "\n};\n\n");
+
+ fprintf(f, "PCM volume_change_sample = {\n");
+ fprintf(f, " .samples = volume_change_samples_buff,\n");
+ fprintf(f, " .samples_len = %zu,\n", sample.samples_len);
+ fprintf(f, " .sample_rate = %zu,\n", sample.sample_rate);
+ fprintf(f, " .channels = %u,\n", sample.channels);
+ fprintf(f, "};");
+
+ return EXIT_SUCCESS;
+}
+
+size_t log_floor(size_t n)
+{
+ size_t result;
+ if (n == 0) return 1;
+ for (result = 0; n > 0; result++, n /= 10);
+ return result;
+}
+
+// = vorbis parsing ===========================================================
+#define VORBIS_READ_CHUNK 4096
+
+// TODO: verify this
+const char *ov_error_str(int e){
+ switch(e){
+ case 0: return "OK";
+ case OV_EREAD: return "read error";
+ case OV_ENOTVORBIS: return "not a Vorbis bitstream";
+ case OV_EVERSION: return "Vorbis version mismatch";
+ case OV_EBADHEADER: return "invalid Vorbis header";
+ case OV_EFAULT: return "internal fault";
+ default: return "unknown error";
+ }
+}
+
+
+bool parse_sample(const char* path, PCM* pcm)
+{
+ OggVorbis_File f;
+ int ret = ov_fopen(path, &f);
+ if (ret < 0) {
+ report("Could not open \"%s\": %s", path, ov_error_str(ret));
+ return false;
+ }
+
+ vorbis_info* info = ov_info(&f, -1);
+ if (!info) {
+ report("Failed to extract Vorbis info from \"%s\"", path);
+ ov_clear(&f);
+ return false;
+ }
+
+ int channels = info->channels;
+ long sample_rate = info->rate;
+
+ assert(sample_rate);
+ assert(channels && channels < UINT8_MAX);
+ pcm->sample_rate = (size_t)sample_rate;
+ pcm->channels = (uint8_t)channels;
+
+ int16_t* buff = malloc(5 * VORBIS_READ_CHUNK);
+ size_t buff_len = 0;
+
+ int section;
+ char read_buff[VORBIS_READ_CHUNK];
+
+ for (;;) {
+ long ret = ov_read(&f, read_buff, VORBIS_READ_CHUNK, 0, 2, 1, §ion);
+ if (ret == 0) break;
+ if (ret < 0) {
+ report("Failed to decode Vorbis: %s", ov_error_str(ret));
+ return false;
+ }
+
+ size_t new_samples = ret / sizeof(buff[0]);
+
+ buff = realloc(buff, (buff_len + new_samples) * sizeof(buff[0]));
+ assert(buff && "buy more RAM!");
+
+ memcpy(buff + buff_len, read_buff, ret);
+ buff_len += new_samples;
+ }
+
+ assert(buff);
+ pcm->samples = buff;
+ pcm->samples_len = buff_len;
+
+ return true;
+}
+
+// = string view & string builder =============================================
+typedef struct {
+ const char* data;
+ size_t len;
+} SV;
+
+typedef struct {
+ char* data;
+ size_t len;
+ size_t capacity;
+} SB;
+
+#define SB_CHUNCK_CAP 512
+
+bool sv_equals(SV str1, const char* str2)
+{
+ if (str1.len != strlen(str2)) return false;
+ return memcmp(str1.data, str2, str1.len) == 0;
+}
+
+bool sv_starts_with(SV str, const char* prefix)
+{
+ size_t prefix_len = strlen(prefix);
+ if (str.len < prefix_len) return false;
+
+ return memcmp(str.data, prefix, prefix_len) == 0;
+}
+
+void sb_append(SB *sb, char c)
+{
+ assert(sb->len <= sb->capacity);
+ if (sb->len + 1 > sb->capacity) {
+ sb->capacity += SB_CHUNCK_CAP;
+
+ char* new_data = realloc(sb->data, sb->capacity);
+ assert(new_data && "buy more RAM!");
+ sb->data = new_data;
+ }
+
+ sb->data[sb->len] = c;
+ sb->len++;
+}
+
+void sb_clear(SB *sb)
+{
+ sb->len = 0;
+}
+
+// = minimal DOS-INI lexer/parser =============================================
+typedef struct {
+ const char* src_path;
+
+ const char* data;
+ size_t cursor;
+ size_t len;
+
+ size_t current_line;
+ size_t current_line_start;
+
+ SB sb;
+ Arena* allocator;
+} Lexer;
+
+typedef enum {
+ TOKEN_SECTION,
+ TOKEN_KEY,
+ TOKEN_INT,
+ TOKEN_STR,
+ TOKEN_EQUALS,
+
+ TOKEN_KIND_COUNT,
+} TokenKind;
+
+static_assert(TOKEN_KIND_COUNT == 5);
+const char* token_kind_str[TOKEN_KIND_COUNT] = {
+ [TOKEN_SECTION] = "header",
+ [TOKEN_KEY] = "key",
+ [TOKEN_INT] = "integer",
+ [TOKEN_STR] = "string",
+ [TOKEN_EQUALS] = "'='",
+};
+
+typedef struct {
+ const char* src_path;
+ size_t line;
+ size_t offset;
+
+ SV text_start;
+} Location;
+
+typedef struct {
+ Location location;
+
+ union {
+ SV as_text;
+ size_t as_int;
+ const char* as_str;
+ };
+ TokenKind kind;
+} Token;
+
+typedef enum {
+ LOG_ERROR,
+ LOG_WARNING,
+} LogLevel;
+
+// NOTE: using GNU extension for ##__VA_ARGS__
+#define location_report(loc, level, fmt, ...) \
+ do { \
+ location_report_start((loc), (level)); \
+ fprintf(stderr, fmt "\n", ##__VA_ARGS__); \
+ location_report_end((loc), (level)); \
+ } while(0)
+
+void location_report_start(Location loc, LogLevel level)
+{
+ fprintf(stderr, BOLD_WHITE "%s:%zu:%zu: " RESET,
+ loc.src_path, loc.line, loc.offset + 1);
+ switch (level) {
+ case LOG_ERROR:
+ fprintf(stderr, BOLD_RED "error: " RESET); break;
+ case LOG_WARNING:
+ fprintf(stderr, BOLD_YELLOW "warning: " RESET); break;
+ }
+}
+
+void location_report_end(Location loc, LogLevel level)
+{
+ SV text = loc.text_start;
+
+ int len;
+ for (len = 0; len < (int)text.len && text.data[len] != '\n'; len++);
+
+ fprintf(stderr, " %zu | %.*s\n ", loc.line, len, text.data);
+ for (size_t i = 0; i < log_floor(loc.line); i++) fprintf(stderr, " ");
+ fprintf(stderr, " | ");
+ for (size_t i = 0; i < loc.offset; i++) fprintf(stderr, " ");
+ switch (level) {
+ case LOG_ERROR:
+ fprintf(stderr, BOLD_RED "^\n" RESET); break;
+ case LOG_WARNING:
+ fprintf(stderr, BOLD_YELLOW "^\n" RESET); break;
+ }
+}
+
+// TODO: support negative numbers!
+bool parse_int(SV text, Location loc, size_t* val)
+{
+ *val = 0;
+
+ if (sv_starts_with(text, "0x") || sv_starts_with(text, "0X")) {
+ text.data += 2;
+ text.len -= 2;
+
+ for (size_t i = 0; i < text.len; i++) {
+ char c = text.data[i];
+ *val *= 16;
+
+ if (isdigit(c)) {
+ *val += (size_t)(text.data[i] - '0');
+ } else if (c == '_') {
+ continue;
+ } else if (c >= 'A' && c <= 'F') {
+ *val += (size_t)(c - 'A' + 10);
+ } else if (c >= 'a' && c <= 'f') {
+ *val += (size_t)(c - 'a' + 10);
+ } else {
+ loc.offset += i + 2;
+ location_report(loc, LOG_ERROR,
+ "Could not parse integer value \"%.*s\"",
+ (int)text.len, text.data);
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ for (size_t i = 0; i < text.len; i++) {
+ char c = text.data[i];
+
+ if (c == '_') continue;
+ if (!isdigit(c)) {
+ loc.offset += i;
+ location_report(loc, LOG_ERROR,
+ "Could not parse integer value \"%.*s\"",
+ (int)text.len, text.data);
+ return false;
+ }
+
+ *val *= 10;
+ *val += (size_t)(c - '0');
+ }
+
+ return true;
+}
+
+void lexer_skip_whitespace(Lexer* l)
+{
+ for (; l->cursor < l->len; l->cursor++) {
+ char c = l->data[l->cursor];
+
+ if (c == ';' || c == '#') { // comment
+ for (; l->cursor < l->len && l->data[l->cursor] != '\n'; l->cursor++);
+ if (l->cursor >= l->len) return;
+
+ l->cursor++;
+ l->current_line++;
+ l->current_line_start = l->cursor + 1;
+ }
+
+ if (!isspace(c)) break;
+ if (c == '\n') {
+ l->current_line++;
+ l->current_line_start = l->cursor + 1;
+ }
+ }
+}
+
+bool lexer_new(const char* path, Lexer* l, Arena* a)
+{
+ memset(l, 0, sizeof(*l));
+ l->src_path = path;
+ l->allocator = a;
+
+ int fd = open(path, O_RDONLY);
+ if (fd < 0) {
+ report("Could not open \"%s\": %s", path, strerror(errno));
+ return false;
+ }
+
+ struct stat st;
+ if (fstat(fd, &st) < 0) {
+ report("Could not stat \"%s\": %s", path, strerror(errno));
+ close(fd);
+ return false;
+ }
+
+ size_t len = st.st_size;
+ if (len == 0) return true;
+
+ const char* buff = malloc(len);
+ assert(buff && "buy more RAM!");
+
+ if (read(fd, (void*)buff, len) != (ssize_t)len) {
+ report("Could not read \"%s\"", path);
+ free((char*)buff);
+ close(fd);
+ return false;
+ }
+
+ l->data = buff;
+ l->len = (size_t)len;
+ close(fd);
+
+ // NOTE: need to clear whitespaces at startup since
+ // we only clear the whitespaces AFTER lexing each token afterwards
+ lexer_skip_whitespace(l);
+ return true;
+}
+
+bool lexer_finished(Lexer* l)
+{
+ return l->cursor >= l->len;
+}
+
+bool lexer_next(Lexer* l, Token* token)
+{
+ Location loc;
+ loc.src_path = l->src_path;
+ loc.line = l->current_line + 1;
+ loc.offset = l->cursor - l->current_line_start;
+ loc.text_start.data = l->data + l->current_line_start;
+ loc.text_start.len = l->len - l->current_line_start;
+
+ if (lexer_finished(l)) {
+ location_report(loc, LOG_ERROR, "Expected token, got EOF");
+ return false;
+ }
+
+ char c = l->data[l->cursor];
+ if (c == '[') {
+ l->cursor++;
+ token->kind = TOKEN_SECTION;
+
+ SV text = {0};
+ text.data = l->data + l->cursor;
+
+ for (; l->cursor < l->len; l->cursor++) {
+ char c = l->data[l->cursor];
+ if (c == ']') break;
+ if (c == '\n') {
+ loc.offset += text.len;
+ location_report(loc, LOG_ERROR,
+ "Reached end of line before matching ']'");
+ return false;
+ }
+
+ text.len++;
+ }
+
+ for (size_t i = 0; i < text.len; i++) {
+ char c = text.data[i];
+ if (!(isalnum(c) || c == ' ' || c == '.')) {
+ loc.offset += i + 1;
+ location_report(loc, LOG_ERROR,
+ "Invalid section header \"%.*s\"",
+ (int)text.len, text.data);
+ return false;
+ }
+ }
+
+ if (l->cursor >= l->len) {
+ location_report(loc, LOG_ERROR, "Expected ']', got EOF");
+ return false;
+ }
+
+ assert(l->data[l->cursor] == ']');
+ l->cursor++;
+
+ token->as_text = text;
+ } else if (c == '=') {
+ token->kind = TOKEN_EQUALS;
+ token->as_text.data = l->data + l->cursor;
+ token->as_text.len = 1;
+ l->cursor++;
+ } else if (c == '"') {
+ token->kind = TOKEN_STR;
+
+ l->cursor++;
+ if (lexer_finished(l)) {
+ loc.offset++;
+ location_report(loc, LOG_ERROR, "Expected '\"', got EOF");
+ return false;
+ }
+
+ sb_clear(&l->sb);
+ bool loop = true;
+ while (loop) {
+ if (lexer_finished(l)) {
+ loc.offset += l->sb.len;
+ location_report(loc, LOG_ERROR, "Expected '\"', got EOF");
+ return false;
+ }
+
+ char c = l->data[l->cursor];
+ switch (c) {
+ case '"':
+ char* str = arena_alloc(l->allocator, l->sb.len + 1);
+ assert(str && "buy more RAM!");
+
+ memcpy(str, l->sb.data, l->sb.len);
+ str[l->sb.len] = '\0';
+
+ token->as_str = str;
+ loop = false;
+ break;
+ case '\n':
+ loc.offset += l->sb.len;
+ location_report(loc, LOG_ERROR, "Expected '\"', got '\\n'");
+ return false;
+ case '\\':
+ l->cursor++;
+ if (lexer_finished(l)) {
+ loc.offset += l->sb.len;
+ location_report(loc, LOG_ERROR, "Expected escape code, got EOF");
+ return false;
+ }
+
+ // TODO: support '\xhhhh'?
+ char e = l->data[l->cursor];
+ switch (e) {
+ case '\n':
+ location_report(loc, LOG_ERROR, "Expected escape code, got '\\n'");
+ return false;
+ case '0':
+ sb_append(&l->sb, '\0');
+ break;
+ case 't':
+ sb_append(&l->sb, '\t');
+ break;
+ case 'r':
+ sb_append(&l->sb, '\r');
+ break;
+ case 'n':
+ sb_append(&l->sb, '\n');
+ break;
+ case 'a':
+ sb_append(&l->sb, '\a');
+ break;
+ case 'b':
+ sb_append(&l->sb, '\b');
+ break;
+ default:
+ sb_append(&l->sb, e);
+ break;
+ }
+ break;
+ default:
+ sb_append(&l->sb, c);
+ }
+ l->cursor++;
+ }
+ } else if (isalpha(c)) {
+ token->kind = TOKEN_KEY;
+ token->as_text.data = l->data + l->cursor;
+
+ size_t len = 0;
+ for (; l->cursor < l->len; l->cursor++) {
+ char c = l->data[l->cursor];
+ if (!(isalnum(c) || c == '_')) break;
+ len++;
+ }
+
+ token->as_text.len = len;
+ } else if (isdigit(c)) {
+ SV text; size_t len = 0;
+ text.data = l->data + l->cursor;
+ for (; l->cursor < l->len; l->cursor++) {
+ if (!isalnum(l->data[l->cursor])) break;
+ len++;
+ }
+ text.len = len;
+
+ size_t val;
+ if (!parse_int(text, loc, &val)) return false;
+
+ token->kind = TOKEN_INT;
+ token->as_int = val;
+ } else {
+ // TODO: escape `c` if needed
+ location_report(loc, LOG_ERROR, "Unexpected character '%c'", c);
+ return false;
+ }
+
+ lexer_skip_whitespace(l);
+ token->location = loc;
+ return true;
+}
+
+// = parser for our config format =============================================
+static_assert(sizeof(Config) == 104);
+typedef enum {
+ KEY_WINDOW_WIDTH = 0,
+ KEY_WINDOW_HEIGHT,
+ KEY_WINDOW_PROGRESS_HEIGHT,
+ KEY_WINDOW_PADDING,
+ KEY_WINDOW_BORDER,
+ KEY_WINDOW_TIMEOUT_MS,
+ KEY_VOLUME_INC,
+ KEY_VOLUME_CAP,
+ KEY_VOLUME_AUDIO_SAMPLE,
+ KEY_COLOR_BACKGROUND,
+ KEY_COLOR_LIGHT_BACKGROUND,
+ KEY_COLOR_ACCENT,
+ KEY_COLOR_WARNING,
+
+ KEYS_COUNT,
+} Key;
+
+typedef struct {
+ const char* name;
+ const char* section;
+ size_t offset;
+
+ TokenKind kind;
+ size_t min_val;
+ size_t max_val;
+} KeyInfo;
+
+static_assert(KEYS_COUNT == 13);
+KeyInfo key_infos[KEYS_COUNT] = {
+ [KEY_WINDOW_WIDTH] = { "width", "window", offsetof(Config, window_width), TOKEN_INT, },
+ [KEY_WINDOW_HEIGHT] = { "height", "window", offsetof(Config, window_height), TOKEN_INT, },
+ [KEY_WINDOW_PROGRESS_HEIGHT] = { "progress_height", "window", offsetof(Config, window_progress_height), TOKEN_INT, },
+ [KEY_WINDOW_PADDING] = { "padding", "window", offsetof(Config, window_padding), TOKEN_INT, },
+ [KEY_WINDOW_BORDER] = { "border", "window", offsetof(Config, window_border), TOKEN_INT, },
+ [KEY_WINDOW_TIMEOUT_MS] = { "timeout_ms", "window", offsetof(Config, window_timeout_ms), TOKEN_INT, },
+ [KEY_VOLUME_INC] = { "increment", "volume", offsetof(Config, volume_inc), TOKEN_INT, },
+ [KEY_VOLUME_CAP] = { "cap", "volume", offsetof(Config, volume_cap), TOKEN_INT, },
+ [KEY_VOLUME_AUDIO_SAMPLE] = { "audio_sample", "volume", offsetof(Config, volume_audio_sample), TOKEN_STR, },
+ [KEY_COLOR_BACKGROUND] = { "background", "theme", offsetof(Config, color_background), TOKEN_INT, },
+ [KEY_COLOR_LIGHT_BACKGROUND] = { "light_background", "theme", offsetof(Config, color_light_background), TOKEN_INT, },
+ [KEY_COLOR_ACCENT] = { "accent", "theme", offsetof(Config, color_accent), TOKEN_INT, },
+ [KEY_COLOR_WARNING] = { "warning", "theme", offsetof(Config, color_warning), TOKEN_INT, },
+};
+
+// NOTE: using GNU extension for ##__VA_ARGS__
+#define file_report(path, fmt, ...) \
+ fprintf(stderr, BOLD_WHITE "%s: " BOLD_RED "error: " RESET \
+ fmt "\n", (path), ##__VA_ARGS__)
+
+bool check_bounds(const char* path, Key k, Config* config,
+ size_t min, size_t max)
+{
+ KeyInfo info = key_infos[k];
+ assert(info.kind == TOKEN_INT);
+ size_t val = *(size_t*)((uint8_t*)config + info.offset);
+
+ if (val < min) {
+ file_report(path, "Value of field \"%s\" is too small: %zu < %zu",
+ info.name, val, min);
+ return false;
+ }
+
+ if (max != 0 && val > max) {
+ file_report(path, "Value of field \"%s\" is too big: %zu > %zu",
+ info.name, val, max);
+ return false;
+ }
+
+ return true;
+}
+
+bool parse_config(const char* path, Config* config)
+{
+ Arena allocator = {0}; Lexer l;
+ if (!lexer_new(path, &l, &allocator)) return false;
+
+ // = parsing ================================================================
+ Token token; uint16_t key_set_flag = 0;
+ while (!lexer_finished(&l)) {
+ if (!lexer_next(&l, &token)) return false;
+ if (token.kind == TOKEN_SECTION) continue; // skip section headers
+
+ Location loc = token.location;
+ if (token.kind != TOKEN_KEY) {
+ location_report(loc, LOG_ERROR,
+ "Expected key, got %s", token_kind_str[token.kind]);
+ return false;
+ }
+
+ SV key = token.as_text;
+ if (!lexer_next(&l, &token)) return false;
+ if (token.kind != TOKEN_EQUALS) {
+ location_report(loc, LOG_ERROR,
+ "Expected '=', got %s", token_kind_str[token.kind]);
+ return false;
+ }
+
+ if (!lexer_next(&l, &token)) return false;
+ if (token.kind != TOKEN_INT && token.kind != TOKEN_STR) {
+ location_report(loc, LOG_ERROR,
+ "Expected integer or string, got %s",
+ token_kind_str[token.kind]);
+ return false;
+ }
+
+ bool key_found = false;
+ for (size_t k = 0; k < KEYS_COUNT; k++) {
+ KeyInfo info = key_infos[k];
+
+ if (!sv_equals(key, info.name)) continue;
+ if (token.kind != info.kind) {
+ loc = token.location;
+ location_report(loc, LOG_ERROR, "Expected %s, got %s",
+ token_kind_str[info.kind],
+ token_kind_str[token.kind]);
+ return false;
+ }
+
+ key_set_flag |= 1 << k;
+
+ uint8_t* field_ptr = (uint8_t*)config + info.offset;
+ if (info.kind == TOKEN_INT) *(size_t*) field_ptr = token.as_int;
+ else *(const char**)field_ptr = token.as_str;
+
+ key_found = true;
+ break;
+ }
+
+ if (!key_found) {
+ location_report(loc, LOG_WARNING, "Ignoring unknown field \"%.*s\"",
+ (int)key.len, key.data);
+ }
+ }
+
+ // = validation =============================================================
+ for (size_t k = 0; k < KEYS_COUNT; k++) {
+ KeyInfo info = key_infos[k];
+
+ if (!(key_set_flag & (1 << k))) {
+ file_report(path, "Field \"%s\" in section [%s] is not set",
+ info.name, info.section);
+ return false;
+ }
+ }
+
+ if (!check_bounds(path, KEY_WINDOW_WIDTH, config, 1, 0)) return false;
+ if (!check_bounds(path, KEY_WINDOW_HEIGHT, config, 1, 0)) return false;
+
+ size_t size = config->window_width;
+ if (config->window_height > size) size = config->window_height;
+
+ if (!check_bounds(path, KEY_WINDOW_PROGRESS_HEIGHT,
+ config, 1, config->window_height)) return false;
+ if (!check_bounds(path, KEY_WINDOW_PADDING, config, 0, size/2)) return false;
+ if (!check_bounds(path, KEY_WINDOW_BORDER, config, 0, size/2)) return false;
+
+ if (!check_bounds(path, KEY_WINDOW_TIMEOUT_MS, config, 1, 0)) return false;
+
+ if (!check_bounds(path, KEY_VOLUME_INC, config, 1, UINT8_MAX)) return false;
+ if (!check_bounds(path, KEY_VOLUME_CAP, config, 1, UINT8_MAX)) return false;
+
+ for (size_t k = KEY_COLOR_BACKGROUND; k <= KEY_COLOR_WARNING; k++) {
+ if (!check_bounds(path, k, config, 0, 0xFFFFFF)) return false;
+ }
+
+ return true;
+}
diff --git a/src/generate-pcm.c /dev/null
@@ -1,107 +0,0 @@
-#include <stdlib.h>
-#include <stdio.h>
-#include <stdint.h>
-#include <stdbool.h>
-#include <assert.h>
-#include <errno.h>
-#include <string.h>
-
-#include <vorbis/vorbisfile.h>
-
-#include "pcm.h"
-
-#define INPUT_PATH "./assets/audio-volume-change.ogg"
-#define OUTPUT_PATH "./build/src/pcm.c"
-
-#define READ_CHUNK 4096
-
-bool parse_pcm(const char* input_path, PCM* pcm)
-{
- OggVorbis_File input_f;
- if (ov_fopen(input_path, &input_f) < 0) {
- fprintf(stderr, "ERROR: Failed to open \"%s\"\n", INPUT_PATH);
- return false;
- }
-
- vorbis_info* info = ov_info(&input_f, -1);
- if (!info) {
- fprintf(stderr, "ERROR: Failed to read Vorbis info\n");
- ov_clear(&input_f);
- return false;
- }
-
- int channels = info->channels;
- long sample_rate = info->rate;
-
- assert(sample_rate);
- assert(channels && channels < UINT8_MAX);
- pcm->sample_rate = (size_t)sample_rate;
- pcm->channels = (uint8_t)channels;
-
- int16_t* buff = malloc(5 * READ_CHUNK);
- size_t buff_len = 0;
-
- int current_sec;
- char read_buff[READ_CHUNK];
-
- for (;;) {
- long ret = ov_read(&input_f, read_buff, READ_CHUNK, 0, 2, 1, ¤t_sec);
- if (ret == 0) break;
- if (ret < 0) {
- fprintf(stderr, "ERROR: could not decode Vorbis: %ld\n", ret);
- return false;
- }
-
- size_t new_samples = ret / sizeof(buff[0]);
-
- buff = realloc(buff, (buff_len + new_samples) * sizeof(buff[0]));
- if (!buff) {
- fprintf(stderr, "ERROR: buy more RAM!\n");
- return false;
- }
-
- memcpy(buff + buff_len, read_buff, ret);
- buff_len += new_samples;
- }
-
- assert(buff);
- pcm->samples = buff;
- pcm->samples_len = buff_len;
-
- return true;
-}
-
-int main(void)
-{
- PCM pcm;
- if (!parse_pcm(INPUT_PATH, &pcm)) return EXIT_FAILURE;
-
- FILE* f = fopen(OUTPUT_PATH, "w");
- if (!f) {
- fprintf(stderr, "ERROR: Could not open \"%s\": %s\n", OUTPUT_PATH,
- strerror(errno));
- return EXIT_FAILURE;
- }
-
- fprintf(f, "#include \"pcm.h\"\n\n");
-
- fprintf(f, "int16_t pcm_buff[%zu] = {", pcm.samples_len);
- for (size_t i = 0; i < pcm.samples_len; i++) {
- if (i % 8 == 0) fprintf(f, "\n ");
- else fprintf(f, " ");
- if (pcm.samples[i] >= 0) fprintf(f, "+0x%04X,", pcm.samples[i]);
- else fprintf(f, "-0x%04X,", -pcm.samples[i]);
-
- }
- fprintf(f, "\n};\n\n");
-
- fprintf(f, "PCM sample_pcm = {\n");
- fprintf(f, " .samples = pcm_buff,\n");
- fprintf(f, " .samples_len = %zu,\n", pcm.samples_len);
- fprintf(f, " .sample_rate = %zu,\n", pcm.sample_rate);
- fprintf(f, " .channels = %u,\n", pcm.channels);
- fprintf(f, "};");
-
- fclose(f);
- return EXIT_SUCCESS;
-}
diff --git a/src/main.c b/src/main.c
@@ -18,7 +18,6 @@
#include <pulse/error.h>
#include "config.h"
-#include "pcm.c"
static_assert(VOLUME_CAP <= UINT8_MAX);
@@ -314,29 +313,28 @@ bool pa_run_cmd(Cmd cmd)
return ret_value == 0;
}
-bool pa_play_sample(PCM pcm)
+bool pa_play_sample(PCM sample)
{
- assert(pcm.channels);
- if (!pcm.samples_len) return true;
+ assert(sample.channels);
+ if (!sample.samples_len) return true;
pa_sample_spec ss;
ss.format = PA_SAMPLE_S16LE;
- ss.channels = pcm.channels;
- ss.rate = pcm.sample_rate;
+ ss.channels = sample.channels;
+ ss.rate = sample.sample_rate;
int pa_err;
pa_simple* simple_api = pa_simple_new(NULL, "audio-volume-change",
PA_STREAM_PLAYBACK, NULL, "playback",
&ss, NULL, NULL, &pa_err);
if (!simple_api) {
- fprintf(stderr, "ERROR: pa_simple_new failed: %s\n",
- pa_strerror(pa_err));
+ fprintf(stderr, "ERROR: pa_simple_new failed: %s\n", pa_strerror(pa_err));
return false;
}
- size_t bytes = pcm.samples_len * sizeof(pcm.samples[0]);
+ size_t bytes = sample.samples_len * sizeof(sample.samples[0]);
size_t written = 0;
- const uint8_t* ptr = (const uint8_t *)pcm.samples;
+ const uint8_t* ptr = (const uint8_t *)sample.samples;
while (written < bytes) {
size_t chunk = bytes - written;
if (chunk > 65536) chunk = 65536;
@@ -474,7 +472,7 @@ void vol_inc_cb(pa_context* ctx, const pa_sink_info* info, int eol, void* data)
}
if (cmd.show_graphics) {
- if (!pa_play_sample(sample_pcm)) {
+ if (!pa_play_sample(volume_change_sample)) {
fprintf(stderr, "ERROR: failed to play audio sample\n");
mainloop_quit(EXIT_FAILURE);
}
@@ -516,7 +514,7 @@ void vol_set_cb(pa_context* ctx, const pa_sink_info* info, int eol, void* data)
}
if (cmd.show_graphics) {
- if (!pa_play_sample(sample_pcm)) {
+ if (!pa_play_sample(volume_change_sample)) {
fprintf(stderr, "ERROR: failed to play audio sample\n");
mainloop_quit(EXIT_FAILURE);
}