ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
fft.c
Go to the documentation of this file.
2
4
5#include <options/options.h>
8#include <libplatform/memory.h>
10
11#include <math.h>
12#include <string.h>
13#include <fftw3.h>
14
15#define FFT_SIZE 1024
16#define FFT_MAX_COLUMNS MAX_TERMINAL_WIDTH
17#define FFT_CACHE_CELLS (MAX_TERMINAL_WIDTH * MAX_TERMINAL_HEIGHT * 2)
18#define FFT_REFRESH_NS 0
19
20static static_mutex_t fft_cache_mutex = STATIC_MUTEX_INIT;
21static struct {
23 unsigned char colors[FFT_CACHE_CELLS * 3];
24 unsigned int width, height;
27 terminal_render_mode_t render_mode;
29 bool valid;
30} fft_cache;
31
32static static_mutex_t fftw_mutex = STATIC_MUTEX_INIT;
33static float fftwf_input[FFT_MAX_COLUMNS * FFT_SIZE];
34static fftwf_complex fftwf_output[FFT_MAX_COLUMNS * (FFT_SIZE / 2 + 1)];
35static fftwf_plan fftwf_forward[FFT_MAX_COLUMNS + 1];
37static float fft_window[FFT_SIZE];
38static bool fft_window_ready;
39static static_mutex_t fft_scale_mutex = STATIC_MUTEX_INIT;
40static char fft_scale_text[32];
41static fft_scale_t fft_scale_cached;
42static bool fft_scale_cached_valid;
43
44static bool parse_fft_scale_value(const char *arg, fft_scale_t *parsed) {
45 parsed->mode = FFT_SCALE_DB;
46 parsed->min_db = -62.0f;
47 parsed->max_db = -6.0f;
48 if (!arg || !*arg)
49 return false;
50 if (!strcmp(arg, "linear")) {
51 parsed->mode = FFT_SCALE_LINEAR;
52 return true;
53 }
54 if (!strcmp(arg, "log")) {
55 parsed->mode = FFT_SCALE_LOG;
56 return true;
57 }
58 char *end = NULL;
59 parsed->min_db = strtof(arg, &end);
60 if (end == arg || *end != ':')
61 return false;
62 char *max_end = NULL;
63 parsed->max_db = strtof(end + 1, &max_end);
64 return max_end != end + 1 && *max_end == '\0' && isfinite(parsed->min_db) && isfinite(parsed->max_db) && parsed->min_db >= -120.0f && parsed->max_db <= 0.0f &&
65 parsed->max_db - parsed->min_db >= 12.0f && parsed->max_db > parsed->min_db;
66}
67
68static fft_scale_t get_fft_scale(void) {
69 const char *text = GET_OPTION(fft_scale);
70 static_mutex_lock(&fft_scale_mutex);
71 if (!fft_scale_cached_valid || strcmp(fft_scale_text, text ? text : "") != 0) {
72 if (!parse_fft_scale_value(text, &fft_scale_cached))
73 fft_scale_cached = (fft_scale_t){.mode = FFT_SCALE_DB, .min_db = -62.0f, .max_db = -6.0f};
74 SAFE_STRNCPY(fft_scale_text, text ? text : "", sizeof(fft_scale_text));
75 fft_scale_cached_valid = true;
76 }
77 fft_scale_t result = fft_scale_cached;
78 static_mutex_unlock(&fft_scale_mutex);
79 return result;
80}
81
83 (void)NAMED_REGISTER_MUTEX(&fft_cache_mutex, "audio.visualization.fft_cache", NULL);
84 (void)NAMED_REGISTER_MUTEX(&fftw_mutex, "audio.visualization.fftw", NULL);
85 (void)NAMED_REGISTER_MUTEX(&audio_fftw_planner_lock, "audio.fftw_planner", NULL);
86 static_mutex_lock(&fftw_mutex);
87 if (!fft_window_ready) {
88 for (size_t i = 0; i < FFT_SIZE; i++)
89 fft_window[i] = 0.5f - 0.5f * cosf(6.28318530718f * (float)i / (float)(FFT_SIZE - 1));
90 fft_window_ready = true;
91 }
92 static_mutex_unlock(&fftw_mutex);
93 return ASCIICHAT_OK;
94}
95
96static bool visualization_fft_batch(const float *const input, unsigned int columns, float *power_spectrum) {
97 static_mutex_lock(&fftw_mutex);
98 if (columns == 0 || columns > FFT_MAX_COLUMNS) {
99 static_mutex_unlock(&fftw_mutex);
100 return false;
101 }
102 if (!fftwf_forward[columns]) {
103 int n[] = {FFT_SIZE};
104 int inembed[] = {FFT_SIZE};
105 int onembed[] = {FFT_SIZE / 2 + 1};
106 static_mutex_lock(&audio_fftw_planner_lock);
107 fftwf_forward[columns] = fftwf_plan_many_dft_r2c(1, n, (int)columns, fftwf_input, inembed, 1, FFT_SIZE, fftwf_output, onembed, 1, FFT_SIZE / 2 + 1, FFTW_ESTIMATE);
108 static_mutex_unlock(&audio_fftw_planner_lock);
109 }
110 fftwf_plan plan = fftwf_forward[columns];
111 if (!plan) {
112 static_mutex_unlock(&fftw_mutex);
113 return false;
114 }
115 for (size_t i = 0; i < (size_t)columns * FFT_SIZE; i++)
116 fftwf_input[i] = input[i];
117 fftwf_execute(plan);
118 const float normalization = (float)FFT_SIZE * 0.25f;
119 for (size_t column = 0; column < columns; column++)
120 for (size_t i = 0; i <= FFT_SIZE / 2; i++) {
121 size_t output = column * (FFT_SIZE / 2 + 1) + i;
122 power_spectrum[output] = (fftwf_output[output][0] * fftwf_output[output][0] + fftwf_output[output][1] * fftwf_output[output][1]) / (normalization * normalization);
123 }
124 static_mutex_unlock(&fftw_mutex);
125 return true;
126}
127
128char *audio_visualization_render_fft(unsigned int width, unsigned int height, audio_visualization_source_t source, bool use_color, int color_mode, bool flip_x, bool flip_y) {
130 return NULL;
131
132 if (GET_OPTION(render_mode) == RENDER_MODE_HALF_BLOCK)
133 height *= 2;
134 static_mutex_lock(&fft_cache_mutex);
135 terminal_render_mode_t render_mode = (terminal_render_mode_t)GET_OPTION(render_mode);
136#if FFT_REFRESH_NS > 0
137 uint64_t now = time_get_ns();
138 if (fft_cache.valid && fft_cache.width == width && fft_cache.height == height && fft_cache.source == source && fft_cache.color_mode == color_mode && fft_cache.render_mode == render_mode &&
139 now >= fft_cache.updated_ns && now - fft_cache.updated_ns < FFT_REFRESH_NS) {
140 size_t cached_cells = (size_t)width * height;
141 char *cached = SAFE_MALLOC(cached_cells, char *);
142 unsigned char *cached_colors = SAFE_MALLOC(cached_cells * 3, unsigned char *);
143 if (!cached || !cached_colors) {
144 SAFE_FREE(cached);
145 SAFE_FREE(cached_colors);
146 static_mutex_unlock(&fft_cache_mutex);
147 return NULL;
148 }
149 memcpy(cached, fft_cache.cells, cached_cells);
150 memcpy(cached_colors, fft_cache.colors, cached_cells * 3);
151 static_mutex_unlock(&fft_cache_mutex);
152 char *frame = visualization_encode(cached, cached_colors, false, width, height, use_color, flip_x, flip_y);
153 SAFE_FREE(cached);
154 SAFE_FREE(cached_colors);
155 return frame;
156 }
157#endif
158 static_mutex_unlock(&fft_cache_mutex);
159 float *samples = SAFE_MALLOC(VISUALIZATION_HISTORY * sizeof(float), float *);
160 if (!samples)
161 return NULL;
163 size_t cell_count = (size_t)width * height;
164 char *cells = SAFE_MALLOC(cell_count, char *);
165 unsigned char *colors = SAFE_MALLOC(cell_count * 3, unsigned char *);
166 if (!cells || !colors) {
169 SAFE_FREE(samples);
170 return NULL;
171 }
172 memset(cells, ' ', cell_count);
173 memset(colors, 0, cell_count * 3);
174
175 /* Preserve the time-history layout: each column is a spectrum from a different
176 * overlapping window in the captured audio history. */
177 float *windowed = SAFE_MALLOC((size_t)width * FFT_SIZE * sizeof(*windowed), float *);
178 float *power_spectrum = SAFE_MALLOC((size_t)width * (FFT_SIZE / 2 + 1) * sizeof(*power_spectrum), float *);
179 if (!windowed || !power_spectrum) {
180 SAFE_FREE(windowed);
181 SAFE_FREE(power_spectrum);
182 SAFE_FREE(samples);
185 return NULL;
186 }
187 fft_scale_t scale = get_fft_scale();
188 static const char levels[] = " .:-=+*#%@";
189 const unsigned int spectrum_height = height;
190 size_t low_bins[MAX_TERMINAL_HEIGHT * 2], high_bins[MAX_TERMINAL_HEIGHT * 2], band_counts[MAX_TERMINAL_HEIGHT * 2];
191 float band_hz[MAX_TERMINAL_HEIGHT * 2];
192 for (unsigned int row = 0; row < spectrum_height; row++) {
193 float top_fraction = (float)(spectrum_height - row - 1) / (float)spectrum_height;
194 float bottom_fraction = (float)(spectrum_height - row) / (float)spectrum_height;
195 float low_hz = 35.0f * powf(18000.0f / 35.0f, top_fraction);
196 float high_hz = 35.0f * powf(18000.0f / 35.0f, bottom_fraction);
197 size_t low_bin = (size_t)fmaxf(1.0f, floorf(low_hz * FFT_SIZE / AUDIO_VISUALIZATION_SAMPLE_RATE));
198 size_t high_bin = (size_t)fmaxf((float)(low_bin + 1), ceilf(high_hz * FFT_SIZE / AUDIO_VISUALIZATION_SAMPLE_RATE));
199 if (high_bin > FFT_SIZE / 2)
200 high_bin = FFT_SIZE / 2;
201 low_bins[row] = low_bin;
202 high_bins[row] = high_bin;
203 band_counts[row] = high_bin - low_bin;
204 band_hz[row] = sqrtf(low_hz * high_hz);
205 }
206 for (unsigned int x = 0; x < width; x++) {
207 size_t center = (size_t)x * (VISUALIZATION_HISTORY - 1) / (width - 1);
208 size_t start = center > FFT_SIZE / 2 ? center - FFT_SIZE / 2 : 0;
209 if (start + FFT_SIZE > VISUALIZATION_HISTORY)
211 for (size_t i = 0; i < FFT_SIZE; i++)
212 windowed[(size_t)x * FFT_SIZE + i] = samples[start + i] * fft_window[i];
213 }
214 if (!visualization_fft_batch(windowed, width, power_spectrum)) {
215 SAFE_FREE(windowed);
216 SAFE_FREE(power_spectrum);
217 SAFE_FREE(samples);
220 return NULL;
221 }
222
223 for (unsigned int x = 0; x < width; x++) {
224 for (unsigned int row = 0; row < spectrum_height; row++) {
225 float power = 0.0f;
226 for (size_t bin = low_bins[row]; bin < high_bins[row]; bin++)
227 power += power_spectrum[(size_t)x * (FFT_SIZE / 2 + 1) + bin];
228 /* The default dB range leaves room for quiet speech while keeping loud music detailed. */
229 float amplitude = band_counts[row] ? sqrtf(power / (float)band_counts[row]) : 0.0f;
230 float intensity;
231 if (scale.mode == FFT_SCALE_LINEAR)
232 intensity = fminf(1.0f, amplitude * 4.0f);
233 else if (scale.mode == FFT_SCALE_LOG)
234 intensity = fminf(1.0f, log1pf(amplitude * 31.0f) / log1pf(31.0f));
235 else {
236 float db = 20.0f * log10f(fmaxf(amplitude, 0.00001f));
237 intensity = fmaxf(0.0f, fminf(1.0f, (db - scale.min_db) / (scale.max_db - scale.min_db)));
238 }
239 int level = (int)lrintf(intensity * (float)(sizeof(levels) - 2));
240 size_t cell = (size_t)row * width + x;
241 cells[cell] = levels[level];
242 visualization_color_for_level(band_hz[row], intensity, color_mode, &colors[cell * 3], &colors[cell * 3 + 1], &colors[cell * 3 + 2]);
243 }
244 }
245
246 static_mutex_lock(&fft_cache_mutex);
247 memcpy(fft_cache.cells, cells, cell_count);
248 memcpy(fft_cache.colors, colors, cell_count * 3);
249 fft_cache.width = width;
250 fft_cache.height = height;
251 fft_cache.source = source;
252 fft_cache.color_mode = color_mode;
253 fft_cache.render_mode = render_mode;
254 fft_cache.updated_ns = time_get_ns();
255 fft_cache.valid = true;
256 static_mutex_unlock(&fft_cache_mutex);
257 char *frame = visualization_encode(cells, colors, false, width, height, use_color, flip_x, flip_y);
258 SAFE_FREE(windowed);
259 SAFE_FREE(power_spectrum);
262 SAFE_FREE(samples);
263 return frame;
264}
Platform initialization and static synchronization helpers.
Named object registry for debugging — log identifiable resource names.
int color_mode
Definition fft.c:26
char cells[(512 *256 *2)]
Definition fft.c:22
bool valid
Definition fft.c:29
asciichat_error_t audio_visualization_fft_init(void)
Definition fft.c:82
uint64_t updated_ns
Definition fft.c:28
unsigned char colors[(512 *256 *2) *3]
Definition fft.c:23
#define FFT_SIZE
Definition fft.c:15
#define FFT_REFRESH_NS
Definition fft.c:18
audio_visualization_source_t source
Definition fft.c:25
unsigned int height
Definition fft.c:24
terminal_render_mode_t render_mode
Definition fft.c:27
unsigned int width
Definition fft.c:24
#define FFT_CACHE_CELLS
Definition fft.c:17
#define FFT_MAX_COLUMNS
Definition fft.c:16
char * audio_visualization_render_fft(unsigned int width, unsigned int height, audio_visualization_source_t source, bool use_color, int color_mode, bool flip_x, bool flip_y)
Definition fft.c:128
@ FFT_SCALE_LOG
Definition fft.h:12
@ FFT_SCALE_LINEAR
Definition fft.h:12
@ FFT_SCALE_DB
Definition fft.h:12
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
unsigned long long uint64_t
#define NAMED_REGISTER_MUTEX(mutex, name, parent_ptr)
Register a mutex with automatic format specifier.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
#define GET_OPTION(field)
Definition options.h:1339
#define STATIC_MUTEX_INIT
🔢 Mathematical Utility Functions
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
static_mutex_t audio_fftw_planner_lock
Definition spectral.c:39
🔤 String Manipulation and Shell Escaping Utilities
fft_scale_mode_t mode
Definition fft.h:15
float max_db
Definition fft.h:17
float min_db
Definition fft.h:16
Static mutex structure for global mutexes requiring static initialization.
Definition common/sync.h:51
⏱️ High-precision timing utilities using sokol_time.h and uthash
char * visualization_encode(const char *cells, const unsigned char *colors, bool column_colors, unsigned int width, unsigned int height, bool use_color, bool flip_x, bool flip_y)
void visualization_color_for_level(float frequency_hz, float level, int color_mode, unsigned char *red, unsigned char *green, unsigned char *blue)
void audio_visualization_read(audio_visualization_source_t source, float *samples, size_t count)
audio_visualization_source_t
@ AUDIO_VISUALIZATION_SOURCE_MIX
#define AUDIO_VISUALIZATION_SAMPLE_RATE
#define MAX_TERMINAL_WIDTH
#define VISUALIZATION_HISTORY
#define MAX_TERMINAL_HEIGHT