]> code.delx.au - pulseaudio/blob - src/modules/module-equalizer-sink.c
drop redundant alloc call
[pulseaudio] / src / modules / module-equalizer-sink.c
1 /***
2 This file is part of PulseAudio.
3
4 This module is based off Lennart Poettering's LADSPA sink and swaps out
5 LADSPA functionality for a dbus-aware STFT OLA based digital equalizer.
6 All new work is published under Pulseaudio's original license.
7 Copyright 2009 Jason Newton <nevion@gmail.com>
8
9 Original Author:
10 Copyright 2004-2008 Lennart Poettering
11
12 PulseAudio is free software; you can redistribute it and/or modify
13 it under the terms of the GNU Lesser General Public License as published
14 by the Free Software Foundation; either version 2.1 of the License,
15 or (at your option) any later version.
16
17 PulseAudio is distributed in the hope that it will be useful, but
18 WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 General Public License for more details.
21
22 You should have received a copy of the GNU Lesser General Public License
23 along with PulseAudio; if not, write to the Free Software
24 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
25 USA.
26 ***/
27
28 #ifdef HAVE_CONFIG_H
29 #include <config.h>
30 #endif
31
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <float.h>
35 #include <math.h>
36 #include <fftw3.h>
37 #include <string.h>
38
39 #include <pulse/xmalloc.h>
40 #include <pulse/i18n.h>
41 #include <pulse/timeval.h>
42
43 #include <pulsecore/core-rtclock.h>
44 #include <pulsecore/aupdate.h>
45 #include <pulsecore/core-error.h>
46 #include <pulsecore/namereg.h>
47 #include <pulsecore/sink.h>
48 #include <pulsecore/module.h>
49 #include <pulsecore/core-util.h>
50 #include <pulsecore/modargs.h>
51 #include <pulsecore/log.h>
52 #include <pulsecore/thread.h>
53 #include <pulsecore/thread-mq.h>
54 #include <pulsecore/rtpoll.h>
55 #include <pulsecore/sample-util.h>
56 #include <pulsecore/shared.h>
57 #include <pulsecore/idxset.h>
58 #include <pulsecore/strlist.h>
59 #include <pulsecore/database.h>
60 #include <pulsecore/protocol-dbus.h>
61 #include <pulsecore/dbus-util.h>
62
63 #include <stdint.h>
64 #include <time.h>
65
66
67 //#undef __SSE2__
68 #ifdef __SSE2__
69 #include <xmmintrin.h>
70 #include <emmintrin.h>
71 #endif
72
73
74
75 #include "module-equalizer-sink-symdef.h"
76
77 PA_MODULE_AUTHOR("Jason Newton");
78 PA_MODULE_DESCRIPTION(_("General Purpose Equalizer"));
79 PA_MODULE_VERSION(PACKAGE_VERSION);
80 PA_MODULE_LOAD_ONCE(FALSE);
81 PA_MODULE_USAGE(_("sink=<sink to connect to> "));
82
83 #define MEMBLOCKQ_MAXLENGTH (16*1024*1024)
84
85
86 struct userdata {
87 pa_module *module;
88 pa_sink *sink;
89 pa_sink_input *sink_input;
90 char *name;
91
92 size_t channels;
93 size_t fft_size;//length (res) of fft
94 size_t window_size;/*
95 *sliding window size
96 *effectively chooses R
97 */
98 size_t R;/* the hop size between overlapping windows
99 * the latency of the filter, calculated from window_size
100 * based on constraints of COLA and window function
101 */
102 //for twiddling with pulseaudio
103 size_t overlap_size;//window_size-R
104 size_t samples_gathered;
105 size_t input_buffer_max;
106 //message
107 float *W;//windowing function (time domain)
108 float *work_buffer, **input, **overlap_accum;
109 fftwf_complex *output_window;
110 fftwf_plan forward_plan, inverse_plan;
111 //size_t samplings;
112
113 float **Xs;
114 float ***Hs;//thread updatable copies of the freq response filters (magintude based)
115 pa_aupdate **a_H;
116 pa_memchunk conv_buffer;
117 pa_memblockq *input_q;
118 pa_bool_t first_iteration;
119
120 pa_dbus_protocol *dbus_protocol;
121 char *dbus_path;
122 pa_bool_t set_default;
123
124 pa_database *database;
125 char **base_profiles;
126 };
127
128 static const char* const valid_modargs[] = {
129 "sink_name",
130 "sink_properties",
131 "master",
132 "format",
133 "rate",
134 "set_default",
135 "channels",
136 "channel_map",
137 NULL
138 };
139
140
141 #define v_size 4
142 #define SINKLIST "equalized_sinklist"
143 #define EQDB "equalizer_db"
144 #define EQ_STATE_DB "equalizer-state"
145 #define FILTER_SIZE (u->fft_size / 2 + 1)
146 #define CHANNEL_PROFILE_SIZE (FILTER_SIZE + 1)
147 #define FILTER_STATE_SIZE (CHANNEL_PROFILE_SIZE * u->channels)
148 static void dbus_init(struct userdata *u);
149 static void dbus_done(struct userdata *u);
150
151 static void hanning_window(float *W, size_t window_size){
152 //h=.5*(1-cos(2*pi*j/(window_size+1)), COLA for R=(M+1)/2
153 for(size_t i=0; i < window_size;++i){
154 W[i] = (float).5*(1-cos(2*M_PI*i/(window_size+1)));
155 }
156 }
157
158 static void fix_filter(float *H, size_t fft_size){
159 //divide out the fft gain
160 for(size_t i = 0; i < fft_size / 2 + 1; ++i){
161 H[i] /= fft_size;
162 }
163 }
164
165 static void interpolate(float *signal, size_t length, uint32_t *xs, float *ys, size_t n_points){
166 //Note that xs must be monotonically increasing!
167 float x_range_lower, x_range_upper, c0;
168 pa_assert_se(n_points>=2);
169 pa_assert_se(xs[0] == 0);
170 pa_assert_se(xs[n_points - 1] == length - 1);
171 for(size_t x = 0, x_range_lower_i = 0; x < length-1; ++x){
172 pa_assert(x_range_lower_i < n_points-1);
173 x_range_lower = (float) (xs[x_range_lower_i]);
174 x_range_upper = (float) (xs[x_range_lower_i+1]);
175 pa_assert_se(x_range_lower < x_range_upper);
176 pa_assert_se(x >= x_range_lower);
177 pa_assert_se(x <= x_range_upper);
178 //bilinear-interpolation of coefficients specified
179 c0 = (x-x_range_lower)/(x_range_upper-x_range_lower);
180 pa_assert_se(c0 >= 0&&c0 <= 1.0);
181 signal[x] = ((1.0f - c0) * ys[x_range_lower_i] + c0 * ys[x_range_lower_i + 1]);
182 while(x >= xs[x_range_lower_i + 1]){
183 x_range_lower_i++;
184 }
185 }
186 signal[length-1]=ys[n_points-1];
187 }
188
189 static int is_monotonic(const uint32_t *xs,size_t length){
190 if(length<2){
191 return 1;
192 }
193 for(size_t i = 1; i < length; ++i){
194 if(xs[i]<=xs[i-1]){
195 return 0;
196 }
197 }
198 return 1;
199 }
200
201 //ensure's memory allocated is a multiple of v_size
202 //and aligned
203 static void * alloc(size_t x,size_t s){
204 size_t f = PA_ROUND_UP(x*s, sizeof(float)*v_size);
205 float *t;
206 pa_assert(f >= x*s);
207 t = fftwf_malloc(f);
208 memset(t, 0, f);
209 return t;
210 }
211
212 static void alloc_input_buffers(struct userdata *u, size_t min_buffer_length){
213 if(min_buffer_length <= u->input_buffer_max){
214 return;
215 }
216 pa_assert(min_buffer_length >= u->window_size);
217 for(size_t c = 0; c < u->channels; ++c){
218 float *tmp = alloc(min_buffer_length, sizeof(float));
219 if(u->input[c]){
220 if(!u->first_iteration){
221 memcpy(tmp, u->input[c], u->overlap_size * sizeof(float));
222 }
223 free(u->input[c]);
224 }
225 u->input[c] = tmp;
226 }
227 u->input_buffer_max = min_buffer_length;
228 }
229
230 /* Called from I/O thread context */
231 static int sink_process_msg_cb(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
232 struct userdata *u = PA_SINK(o)->userdata;
233
234 switch (code) {
235
236 case PA_SINK_MESSAGE_GET_LATENCY: {
237 //size_t fs=pa_frame_size(&u->sink->sample_spec);
238
239 /* The sink is _put() before the sink input is, so let's
240 * make sure we don't access it in that time. Also, the
241 * sink input is first shut down, the sink second. */
242 if (!PA_SINK_IS_LINKED(u->sink->thread_info.state) ||
243 !PA_SINK_INPUT_IS_LINKED(u->sink_input->thread_info.state)) {
244 *((pa_usec_t*) data) = 0;
245 return 0;
246 }
247
248 *((pa_usec_t*) data) =
249 /* Get the latency of the master sink */
250 pa_sink_get_latency_within_thread(u->sink_input->sink) +
251
252 /* Add the latency internal to our sink input on top */
253 pa_bytes_to_usec(pa_memblockq_get_length(u->sink_input->thread_info.render_memblockq), &u->sink_input->sink->sample_spec);
254 // pa_bytes_to_usec(u->samples_gathered * fs, &u->sink->sample_spec);
255 //+ pa_bytes_to_usec(u->latency * fs, ss)
256 //+ pa_bytes_to_usec(pa_memblockq_get_length(u->input_q), ss);
257 return 0;
258 }
259 }
260
261 return pa_sink_process_msg(o, code, data, offset, chunk);
262 }
263
264
265 /* Called from main context */
266 static int sink_set_state_cb(pa_sink *s, pa_sink_state_t state) {
267 struct userdata *u;
268
269 pa_sink_assert_ref(s);
270 pa_assert_se(u = s->userdata);
271
272 if (!PA_SINK_IS_LINKED(state) ||
273 !PA_SINK_INPUT_IS_LINKED(pa_sink_input_get_state(u->sink_input)))
274 return 0;
275
276 pa_sink_input_cork(u->sink_input, state == PA_SINK_SUSPENDED);
277 return 0;
278 }
279
280 /* Called from I/O thread context */
281 static void sink_request_rewind_cb(pa_sink *s) {
282 struct userdata *u;
283
284 pa_sink_assert_ref(s);
285 pa_assert_se(u = s->userdata);
286
287 if (!PA_SINK_IS_LINKED(u->sink->thread_info.state) ||
288 !PA_SINK_INPUT_IS_LINKED(u->sink_input->thread_info.state))
289 return;
290
291 /* Just hand this one over to the master sink */
292 pa_sink_input_request_rewind(u->sink_input, s->thread_info.rewind_nbytes+pa_memblockq_get_length(u->input_q), TRUE, FALSE, FALSE);
293 }
294
295 /* Called from I/O thread context */
296 static void sink_update_requested_latency_cb(pa_sink *s) {
297 struct userdata *u;
298
299 pa_sink_assert_ref(s);
300 pa_assert_se(u = s->userdata);
301
302 if (!PA_SINK_IS_LINKED(u->sink->thread_info.state) ||
303 !PA_SINK_INPUT_IS_LINKED(u->sink_input->thread_info.state))
304 return;
305
306 /* Just hand this one over to the master sink */
307 pa_sink_input_set_requested_latency_within_thread(
308 u->sink_input,
309 pa_sink_get_requested_latency_within_thread(s));
310 }
311
312 /* Called from main context */
313 static void sink_set_volume_cb(pa_sink *s) {
314 struct userdata *u;
315
316 pa_sink_assert_ref(s);
317 pa_assert_se(u = s->userdata);
318
319 if (!PA_SINK_IS_LINKED(pa_sink_get_state(s)) ||
320 !PA_SINK_INPUT_IS_LINKED(pa_sink_input_get_state(u->sink_input)))
321 return;
322
323 pa_sink_input_set_volume(u->sink_input, &s->real_volume, s->save_volume, TRUE);
324 }
325
326 /* Called from main context */
327 static void sink_set_mute_cb(pa_sink *s) {
328 struct userdata *u;
329
330 pa_sink_assert_ref(s);
331 pa_assert_se(u = s->userdata);
332
333 if (!PA_SINK_IS_LINKED(pa_sink_get_state(s)) ||
334 !PA_SINK_INPUT_IS_LINKED(pa_sink_input_get_state(u->sink_input)))
335 return;
336
337 pa_sink_input_set_mute(u->sink_input, s->muted, s->save_muted);
338 }
339
340 #ifndef __SSE2__
341 //reference implementation
342 static void dsp_logic(
343 float * restrict dst,//used as a temp array too, needs to be fft_length!
344 float * restrict src,/*input data w/ overlap at start,
345 *automatically cycled in routine
346 */
347 float * restrict overlap,
348 const float X,//multipliar
349 const float * restrict H,//The freq. magnitude scalers filter
350 const float * restrict W,//The windowing function
351 fftwf_complex * restrict output_window,//The transformed window'd src
352 struct userdata *u){
353 //use a linear-phase sliding STFT and overlap-add method (for each channel)
354 //window the data
355 for(size_t j = 0; j < u->window_size; ++j){
356 dst[j] = X * W[j] * src[j];
357 }
358 //zero padd the the remaining fft window
359 memset(dst + u->window_size, 0, (u->fft_size - u->window_size) * sizeof(float));
360 //Processing is done here!
361 //do fft
362 fftwf_execute_dft_r2c(u->forward_plan, dst, output_window);
363 //perform filtering
364 for(size_t j = 0; j < FILTER_SIZE; ++j){
365 u->output_window[j][0] *= H[j];
366 u->output_window[j][1] *= H[j];
367 }
368 //inverse fft
369 fftwf_execute_dft_c2r(u->inverse_plan, output_window, dst);
370 ////debug: tests overlaping add
371 ////and negates ALL PREVIOUS processing
372 ////yields a perfect reconstruction if COLA is held
373 //for(size_t j = 0; j < u->window_size; ++j){
374 // u->work_buffer[j] = u->W[j] * u->input[c][j];
375 //}
376
377 //overlap add and preserve overlap component from this window (linear phase)
378 for(size_t j = 0; j < u->overlap_size; ++j){
379 u->work_buffer[j] += overlap[j];
380 overlap[j] = dst[u->R + j];
381 }
382 ////debug: tests if basic buffering works
383 ////shouldn't modify the signal AT ALL (beyond roundoff)
384 //for(size_t j = 0; j < u->window_size;++j){
385 // u->work_buffer[j] = u->input[c][j];
386 //}
387
388 //preseve the needed input for the next window's overlap
389 memmove(src, src + u->R,
390 (u->samples_gathered - u->R) * sizeof(float)
391 );
392 }
393 #else
394 typedef float v4sf __attribute__ ((__aligned__(v_size * sizeof(float))));
395 typedef union float_vector {
396 float f[v_size];
397 v4sf v;
398 __m128 m;
399 } float_vector_t;
400
401 //regardless of sse enabled, the loops in here assume
402 //16 byte aligned addresses and memory allocations divisible by v_size
403 static void dsp_logic(
404 float * restrict dst,//used as a temp array too, needs to be fft_length!
405 float * restrict src,/*input data w/ overlap at start,
406 *automatically cycled in routine
407 */
408 float * restrict overlap,//The size of the overlap
409 const float X,//multipliar
410 const float * restrict H,//The freq. magnitude scalers filter
411 const float * restrict W,//The windowing function
412 fftwf_complex * restrict output_window,//The transformed window'd src
413 struct userdata *u){//Collection of constants
414 const size_t overlap_size = PA_ROUND_UP(u->overlap_size, v_size);
415
416
417 //assert(u->samples_gathered >= u->R);
418 //use a linear-phase sliding STFT and overlap-add method
419 for(size_t j = 0; j < u->window_size; j += v_size){
420 //dst[j] = W[j] * src[j];
421 float_vector_t *d = (float_vector_t*) (dst + j);
422 float_vector_t *w = (float_vector_t*) (W + j);
423 float_vector_t *s = (float_vector_t*) (src + j);
424 //#if __SSE2__
425 d->m = _mm_mul_ps(w->m, s->m);
426 //#else
427 // d->v = w->v * s->v;
428 //#endif
429 }
430 //zero padd the the remaining fft window
431 memset(dst + u->window_size, 0, (u->fft_size - u->window_size) * sizeof(float));
432
433 //Processing is done here!
434 //do fft
435 fftwf_execute_dft_r2c(u->forward_plan, dst, output_window);
436 //perform filtering - purely magnitude based
437 for(size_t j = 0; j < FILTER_SIZE; j += v_size / 2){
438 //output_window[j][0]*=H[j];
439 //output_window[j][1]*=H[j];
440 float_vector_t *d = (float_vector_t*)( ((float *) output_window) + 2 * j);
441 float_vector_t h;
442 h.f[0] = h.f[1] = H[j];
443 h.f[2] = h.f[3] = H[j + 1];
444 //#if __SSE2__
445 d->m = _mm_mul_ps(d->m, h.m);
446 //#else
447 // d->v = d->v * h.v;
448 //#endif
449 }
450
451 //inverse fft
452 fftwf_execute_dft_c2r(u->inverse_plan, output_window, dst);
453
454 ////debug: tests overlaping add
455 ////and negates ALL PREVIOUS processing
456 ////yields a perfect reconstruction if COLA is held
457 //for(size_t j = 0; j < u->window_size; ++j){
458 // dst[j] = W[j] * src[j];
459 //}
460
461 //overlap add and preserve overlap component from this window (linear phase)
462 for(size_t j = 0; j < overlap_size; j += v_size){
463 //dst[j]+=overlap[j];
464 //overlap[j]+=dst[j+R];
465 float_vector_t *d = (float_vector_t*)(dst + j);
466 float_vector_t *o = (float_vector_t*)(overlap + j);
467 //#if __SSE2__
468 d->m = _mm_add_ps(d->m, o->m);
469 o->m = ((float_vector_t*)(dst + u->R + j))->m;
470 //#else
471 // d->v = d->v + o->v;
472 // o->v = ((float_vector_t*)(dst + u->R + j))->v;
473 //#endif
474 }
475 //memcpy(overlap, dst+u->R, u->overlap_size * sizeof(float)); //overlap preserve (debug)
476 //zero out the bit beyond the real overlap so we don't add garbage next iteration
477 memset(overlap + u->overlap_size, 0, overlap_size - u->overlap_size);
478
479 ////debug: tests if basic buffering works
480 ////shouldn't modify the signal AT ALL (beyond roundoff)
481 //for(size_t j = 0; j < u->window_size; ++j){
482 // dst[j] = src[j];
483 //}
484
485 //preseve the needed input for the next window's overlap
486 memmove(src, src + u->R,
487 (u->samples_gathered - u->R) * sizeof(float)
488 );
489 }
490 #endif
491
492 static void process_samples(struct userdata *u, pa_memchunk *tchunk){
493 size_t fs = pa_frame_size(&(u->sink->sample_spec));
494 float *dst;
495 unsigned a_i;
496 float *H, X;
497 size_t iterations, offset;
498 pa_assert(u->samples_gathered >= u->window_size);
499 iterations = (u->samples_gathered - u->overlap_size) / u->R;
500 tchunk->index = 0;
501 tchunk->length = iterations * u->R * fs;
502 tchunk->memblock = pa_memblock_new(u->sink->core->mempool, tchunk->length);
503 dst = ((float*) pa_memblock_acquire(tchunk->memblock));
504 for(size_t iter = 0; iter < iterations; ++iter){
505 offset = iter * u->R * fs;
506 for(size_t c = 0;c < u->channels; c++) {
507 a_i = pa_aupdate_read_begin(u->a_H[c]);
508 X = u->Xs[c][a_i];
509 H = u->Hs[c][a_i];
510 dsp_logic(
511 u->work_buffer,
512 u->input[c],
513 u->overlap_accum[c],
514 X,
515 H,
516 u->W,
517 u->output_window,
518 u
519 );
520 pa_aupdate_read_end(u->a_H[c]);
521 if(u->first_iteration){
522 /* The windowing function will make the audio ramped in, as a cheap fix we can
523 * undo the windowing (for non-zero window values)
524 */
525 for(size_t i = 0; i < u->overlap_size; ++i){
526 u->work_buffer[i] = u->W[i] <= FLT_EPSILON ? u->work_buffer[i] : u->work_buffer[i] / u->W[i];
527 }
528 }
529 pa_sample_clamp(PA_SAMPLE_FLOAT32NE, (uint8_t *) (dst + c) + offset, fs, u->work_buffer, sizeof(float), u->R);
530 }
531 if(u->first_iteration){
532 u->first_iteration = FALSE;
533 }
534 u->samples_gathered -= u->R;
535 }
536 pa_memblock_release(tchunk->memblock);
537 }
538
539 static void input_buffer(struct userdata *u, pa_memchunk *in){
540 size_t fs = pa_frame_size(&(u->sink->sample_spec));
541 size_t samples = in->length/fs;
542 float *src = (float*) ((uint8_t*) pa_memblock_acquire(in->memblock) + in->index);
543 pa_assert(u->samples_gathered + samples <= u->input_buffer_max);
544 for(size_t c = 0; c < u->channels; c++) {
545 //buffer with an offset after the overlap from previous
546 //iterations
547 pa_assert_se(
548 u->input[c] + u->samples_gathered + samples <= u->input[c] + u->input_buffer_max
549 );
550 pa_sample_clamp(PA_SAMPLE_FLOAT32NE, u->input[c] + u->samples_gathered, sizeof(float), src + c, fs, samples);
551 }
552 u->samples_gathered += samples;
553 pa_memblock_release(in->memblock);
554 }
555
556 /* Called from I/O thread context */
557 static int sink_input_pop_cb(pa_sink_input *i, size_t nbytes, pa_memchunk *chunk) {
558 struct userdata *u;
559 size_t fs, target_samples;
560 struct timeval start, end;
561 pa_memchunk tchunk;
562 pa_sink_input_assert_ref(i);
563 pa_assert_se(u = i->userdata);
564 pa_assert(chunk);
565 pa_assert(u->sink);
566 fs = pa_frame_size(&(u->sink->sample_spec));
567 target_samples = PA_ROUND_UP(nbytes / fs, u->R);
568 if(u->first_iteration){
569 //allocate request_size
570 target_samples = PA_MAX(target_samples, u->window_size);
571 }else{
572 //allocate request_size + overlap
573 target_samples += u->overlap_size;
574 }
575 alloc_input_buffers(u, target_samples);
576 chunk->memblock = NULL;
577
578 /* Hmm, process any rewind request that might be queued up */
579 pa_sink_process_rewind(u->sink, 0);
580
581 //pa_log_debug("start output-buffered %ld, input-buffered %ld, requested %ld",buffered_samples,u->samples_gathered,samples_requested);
582 pa_rtclock_get(&start);
583 do{
584 size_t input_remaining = target_samples - u->samples_gathered;
585 pa_assert(input_remaining > 0);
586 while(pa_memblockq_peek(u->input_q, &tchunk) < 0){
587 //pa_sink_render(u->sink, input_remaining * fs, &tchunk);
588 pa_sink_render_full(u->sink, input_remaining * fs, &tchunk);
589 pa_assert(tchunk.memblock);
590 pa_memblockq_push(u->input_q, &tchunk);
591 pa_memblock_unref(tchunk.memblock);
592 }
593 pa_assert(tchunk.memblock);
594 tchunk.length = PA_MIN(input_remaining * fs, tchunk.length);
595 pa_memblockq_drop(u->input_q, tchunk.length);
596 //pa_log_debug("asked for %ld input samples, got %ld samples",input_remaining,buffer->length/fs);
597 /* copy new input */
598 //pa_rtclock_get(start);
599 input_buffer(u, &tchunk);
600 //pa_rtclock_get(&end);
601 //pa_log_debug("Took %0.5f seconds to setup", pa_timeval_diff(end, start) / (double) PA_USEC_PER_SEC);
602 pa_memblock_unref(tchunk.memblock);
603 }while(u->samples_gathered < target_samples);
604
605 pa_rtclock_get(&end);
606 pa_log_debug("Took %0.6f seconds to get data", (double) pa_timeval_diff(&end, &start) / PA_USEC_PER_SEC);
607
608 pa_assert(u->fft_size >= u->window_size);
609 pa_assert(u->R < u->window_size);
610 /* set the H filter */
611 pa_rtclock_get(&start);
612 /* process a block */
613 process_samples(u, chunk);
614 pa_rtclock_get(&end);
615 pa_log_debug("Took %0.6f seconds to process", (double) pa_timeval_diff(&end, &start) / PA_USEC_PER_SEC);
616
617 pa_assert(chunk->memblock);
618 //pa_log_debug("gave %ld", chunk->length/fs);
619 //pa_log_debug("end pop");
620 return 0;
621 }
622
623 /* Called from main context */
624 static void sink_input_volume_changed_cb(pa_sink_input *i) {
625 struct userdata *u;
626
627 pa_sink_input_assert_ref(i);
628 pa_assert_se(u = i->userdata);
629
630 pa_sink_volume_changed(u->sink, &i->volume);
631 }
632
633 /* Called from main context */
634 static void sink_input_mute_changed_cb(pa_sink_input *i) {
635 struct userdata *u;
636
637 pa_sink_input_assert_ref(i);
638 pa_assert_se(u = i->userdata);
639
640 pa_sink_mute_changed(u->sink, i->muted);
641 }
642
643 static void reset_filter(struct userdata *u){
644 size_t fs = pa_frame_size(&u->sink->sample_spec);
645 size_t max_request;
646 u->samples_gathered = 0;
647 for(size_t i = 0; i < u->channels; ++i){
648 memset(u->overlap_accum[i], 0, u->overlap_size * sizeof(float));
649 }
650 u->first_iteration = TRUE;
651 //set buffer size to max request, no overlap copy
652 max_request = PA_ROUND_UP(pa_sink_input_get_max_request(u->sink_input) / fs , u->R);
653 max_request = PA_MAX(max_request, u->window_size);
654 pa_sink_set_max_request_within_thread(u->sink, max_request * fs);
655 }
656
657 /* Called from I/O thread context */
658 static void sink_input_process_rewind_cb(pa_sink_input *i, size_t nbytes) {
659 struct userdata *u;
660 size_t amount = 0;
661
662 pa_log_debug("Rewind callback!");
663 pa_sink_input_assert_ref(i);
664 pa_assert_se(u = i->userdata);
665
666 if (u->sink->thread_info.rewind_nbytes > 0) {
667 size_t max_rewrite;
668
669 //max_rewrite = nbytes;
670 max_rewrite = nbytes + pa_memblockq_get_length(u->input_q);
671 //PA_MIN(pa_memblockq_get_length(u->input_q), nbytes);
672 amount = PA_MIN(u->sink->thread_info.rewind_nbytes, max_rewrite);
673 u->sink->thread_info.rewind_nbytes = 0;
674
675 if (amount > 0) {
676 //invalidate the output q
677 pa_memblockq_seek(u->input_q, - (int64_t) amount, PA_SEEK_RELATIVE, TRUE);
678 pa_log("Resetting filter");
679 //reset_filter(u); //this is the "proper" thing to do...
680 }
681 }
682
683 pa_sink_process_rewind(u->sink, amount);
684 pa_memblockq_rewind(u->input_q, nbytes);
685 }
686
687 /* Called from I/O thread context */
688 static void sink_input_update_max_rewind_cb(pa_sink_input *i, size_t nbytes) {
689 struct userdata *u;
690
691 pa_sink_input_assert_ref(i);
692 pa_assert_se(u = i->userdata);
693
694 pa_memblockq_set_maxrewind(u->input_q, nbytes);
695 pa_sink_set_max_rewind_within_thread(u->sink, nbytes);
696 }
697
698 /* Called from I/O thread context */
699 static void sink_input_update_max_request_cb(pa_sink_input *i, size_t nbytes) {
700 struct userdata *u;
701 size_t fs;
702 pa_sink_input_assert_ref(i);
703 pa_assert_se(u = i->userdata);
704 //if(u->first_iteration){
705 // return;
706 //}
707 fs = pa_frame_size(&(u->sink->sample_spec));
708 pa_sink_set_max_request_within_thread(u->sink, PA_ROUND_UP(nbytes / fs, u->R) * fs);
709 }
710
711 /* Called from I/O thread context */
712 static void sink_input_update_sink_latency_range_cb(pa_sink_input *i) {
713 struct userdata *u;
714
715 pa_sink_input_assert_ref(i);
716 pa_assert_se(u = i->userdata);
717
718 pa_sink_set_latency_range_within_thread(u->sink, i->sink->thread_info.min_latency, i->sink->thread_info.max_latency);
719 }
720
721 /* Called from I/O thread context */
722 static void sink_input_update_sink_fixed_latency_cb(pa_sink_input *i) {
723 struct userdata *u;
724
725 pa_sink_input_assert_ref(i);
726 pa_assert_se(u = i->userdata);
727
728 pa_sink_set_fixed_latency_within_thread(u->sink, i->sink->thread_info.fixed_latency);
729 }
730
731 /* Called from I/O thread context */
732 static void sink_input_detach_cb(pa_sink_input *i) {
733 struct userdata *u;
734
735 pa_sink_input_assert_ref(i);
736 pa_assert_se(u = i->userdata);
737
738 pa_sink_detach_within_thread(u->sink);
739
740 pa_sink_set_rtpoll(u->sink, NULL);
741 }
742
743 /* Called from I/O thread context */
744 static void sink_input_attach_cb(pa_sink_input *i) {
745 struct userdata *u;
746 size_t fs, max_request;
747 pa_sink_input_assert_ref(i);
748 pa_assert_se(u = i->userdata);
749
750 pa_sink_set_rtpoll(u->sink, i->sink->thread_info.rtpoll);
751 pa_sink_set_latency_range_within_thread(u->sink, i->sink->thread_info.min_latency, i->sink->thread_info.max_latency);
752
753 pa_sink_set_fixed_latency_within_thread(u->sink, i->sink->thread_info.fixed_latency);
754 fs = pa_frame_size(&u->sink->sample_spec);
755 //set buffer size to max request, no overlap copy
756 max_request = PA_ROUND_UP(pa_sink_input_get_max_request(u->sink_input) / fs , u->R);
757 max_request = PA_MAX(max_request, u->window_size);
758 pa_sink_set_max_request_within_thread(u->sink, max_request * fs);
759 pa_sink_set_max_rewind_within_thread(u->sink, pa_sink_input_get_max_rewind(i));
760 pa_sink_attach_within_thread(u->sink);
761 if(u->set_default){
762 pa_log_debug("Setting default sink to %s", u->sink->name);
763 pa_namereg_set_default_sink(u->module->core, u->sink);
764 }
765 }
766
767 /* Called from main context */
768 static void sink_input_kill_cb(pa_sink_input *i) {
769 struct userdata *u;
770
771 pa_sink_input_assert_ref(i);
772 pa_assert_se(u = i->userdata);
773
774 /* The order here matters! We first kill the sink input, followed
775 * by the sink. That means the sink callbacks must be protected
776 * against an unconnected sink input! */
777 pa_sink_input_unlink(u->sink_input);
778 pa_sink_unlink(u->sink);
779
780 pa_sink_input_unref(u->sink_input);
781 u->sink_input = NULL;
782
783 pa_sink_unref(u->sink);
784 u->sink = NULL;
785
786 pa_module_unload_request(u->module, TRUE);
787 }
788
789 /* Called from IO thread context */
790 static void sink_input_state_change_cb(pa_sink_input *i, pa_sink_input_state_t state) {
791 struct userdata *u;
792
793 pa_sink_input_assert_ref(i);
794 pa_assert_se(u = i->userdata);
795
796 /* If we are added for the first time, ask for a rewinding so that
797 * we are heard right-away. */
798 if (PA_SINK_INPUT_IS_LINKED(state) &&
799 i->thread_info.state == PA_SINK_INPUT_INIT) {
800 pa_log_debug("Requesting rewind due to state change.");
801 pa_sink_input_request_rewind(i, 0, FALSE, TRUE, TRUE);
802 }
803 }
804
805 static void pack(char **strs, size_t len, char **packed, size_t *length){
806 size_t t_len = 0;
807 size_t headers = (1+len) * sizeof(uint16_t);
808 char *p;
809 for(size_t i = 0; i < len; ++i){
810 t_len += strlen(strs[i]);
811 }
812 *length = headers + t_len;
813 p = *packed = pa_xmalloc0(*length);
814 *((uint16_t *) p) = (uint16_t) len;
815 p += sizeof(uint16_t);
816 for(size_t i = 0; i < len; ++i){
817 uint16_t l = strlen(strs[i]);
818 *((uint16_t *) p) = (uint16_t) l;
819 p += sizeof(uint16_t);
820 memcpy(p, strs[i], l);
821 p += l;
822 }
823 }
824 static void unpack(char *str, size_t length, char ***strs, size_t *len){
825 char *p = str;
826 *len = *((uint16_t *) p);
827 p += sizeof(uint16_t);
828 *strs = pa_xnew(char *, *len);
829
830 for(size_t i = 0; i < *len; ++i){
831 size_t l = *((uint16_t *) p);
832 p += sizeof(uint16_t);
833 (*strs)[i] = pa_xnew(char, l + 1);
834 memcpy((*strs)[i], p, l);
835 (*strs)[i][l] = '\0';
836 p += l;
837 }
838 }
839 static void save_profile(struct userdata *u, size_t channel, char *name){
840 unsigned a_i;
841 const size_t profile_size = CHANNEL_PROFILE_SIZE * sizeof(float);
842 float *H_n, *profile;
843 const float *H;
844 pa_datum key, data;
845 profile = pa_xnew0(float, profile_size);
846 a_i = pa_aupdate_read_begin(u->a_H[channel]);
847 profile[0] = u->Xs[a_i][channel];
848 H = u->Hs[channel][a_i];
849 H_n = profile + 1;
850 for(size_t i = 0 ; i <= FILTER_SIZE; ++i){
851 H_n[i] = H[i] * u->fft_size;
852 //H_n[i] = H[i];
853 }
854 pa_aupdate_read_end(u->a_H[channel]);
855 key.data=name;
856 key.size = strlen(key.data);
857 data.data = profile;
858 data.size = profile_size;
859 pa_database_set(u->database, &key, &data, TRUE);
860 pa_database_sync(u->database);
861 if(u->base_profiles[channel]){
862 pa_xfree(u->base_profiles[channel]);
863 }
864 u->base_profiles[channel] = pa_xstrdup(name);
865 }
866
867 static void save_state(struct userdata *u){
868 unsigned a_i;
869 const size_t filter_state_size = FILTER_STATE_SIZE * sizeof(float);
870 float *H_n, *state;
871 float *H;
872 pa_datum key, data;
873 pa_database *database;
874 char *dbname;
875 char *state_name = u->name;
876 char *packed;
877 size_t packed_length;
878
879 pack(u->base_profiles, u->channels, &packed, &packed_length);
880 state = (float *) pa_xmalloc0(filter_state_size + packed_length);
881 memcpy(state + FILTER_STATE_SIZE, packed, packed_length);
882 pa_xfree(packed);
883
884 for(size_t c = 0; c < u->channels; ++c){
885 a_i = pa_aupdate_read_begin(u->a_H[c]);
886 state[c * CHANNEL_PROFILE_SIZE] = u->Xs[c][a_i];
887 H = u->Hs[c][a_i];
888 H_n = &state[c * CHANNEL_PROFILE_SIZE + 1];
889 memcpy(H_n, H, FILTER_SIZE * sizeof(float));
890 pa_aupdate_read_end(u->a_H[c]);
891 }
892
893 key.data = state_name;
894 key.size = strlen(key.data);
895 data.data = state;
896 data.size = filter_state_size + packed_length;
897 //thread safety for 0.9.17?
898 pa_assert_se(dbname = pa_state_path(EQ_STATE_DB, FALSE));
899 pa_assert_se(database = pa_database_open(dbname, TRUE));
900 pa_xfree(dbname);
901
902 pa_database_set(database, &key, &data, TRUE);
903 pa_database_sync(database);
904 pa_database_close(database);
905 pa_xfree(state);
906 }
907
908 static void remove_profile(pa_core *c, char *name){
909 pa_datum key;
910 pa_database *database;
911 key.data = name;
912 key.size = strlen(key.data);
913 pa_assert_se(database = pa_shared_get(c, EQDB));
914 pa_database_unset(database, &key);
915 pa_database_sync(database);
916 }
917
918 static const char* load_profile(struct userdata *u, size_t channel, char *name){
919 unsigned a_i;
920 pa_datum key, value;
921 const size_t profile_size = CHANNEL_PROFILE_SIZE * sizeof(float);
922 key.data = name;
923 key.size = strlen(key.data);
924 if(pa_database_get(u->database, &key, &value) != NULL){
925 if(value.size == profile_size){
926 float *profile = (float *) value.data;
927 a_i = pa_aupdate_write_begin(u->a_H[channel]);
928 u->Xs[channel][a_i] = profile[0];
929 memcpy(u->Hs[channel][a_i], profile + 1, FILTER_SIZE * sizeof(float));
930 fix_filter(u->Hs[channel][a_i], u->fft_size);
931 pa_aupdate_write_end(u->a_H[channel]);
932 pa_xfree(u->base_profiles[channel]);
933 u->base_profiles[channel] = pa_xstrdup(name);
934 }else{
935 return "incompatible size";
936 }
937 pa_datum_free(&value);
938 }else{
939 return "profile doesn't exist";
940 }
941 return NULL;
942 }
943
944 static void load_state(struct userdata *u){
945 unsigned a_i;
946 float *H;
947 pa_datum key, value;
948 pa_database *database;
949 char *dbname;
950 char *state_name = u->name;
951 pa_assert_se(dbname = pa_state_path(EQ_STATE_DB, FALSE));
952 database = pa_database_open(dbname, FALSE);
953 pa_xfree(dbname);
954 if(!database){
955 pa_log("No resume state");
956 return;
957 }
958
959 key.data = state_name;
960 key.size = strlen(key.data);
961
962 if(pa_database_get(database, &key, &value) != NULL){
963 if(value.size > FILTER_STATE_SIZE * sizeof(float) + sizeof(uint16_t)){
964 float *state = (float *) value.data;
965 size_t n_profs;
966 char **names;
967 for(size_t c = 0; c < u->channels; ++c){
968 a_i = pa_aupdate_write_begin(u->a_H[c]);
969 H = state + c * CHANNEL_PROFILE_SIZE + 1;
970 u->Xs[c][a_i] = state[c * CHANNEL_PROFILE_SIZE];
971 memcpy(u->Hs[c][a_i], H, FILTER_SIZE * sizeof(float));
972 pa_aupdate_write_end(u->a_H[c]);
973 }
974 unpack(((char *)value.data) + FILTER_STATE_SIZE * sizeof(float), value.size - FILTER_STATE_SIZE * sizeof(float), &names, &n_profs);
975 n_profs = PA_MIN(n_profs, u->channels);
976 for(size_t c = 0; c < n_profs; ++c){
977 pa_xfree(u->base_profiles[c]);
978 u->base_profiles[c] = names[c];
979 }
980 pa_xfree(names);
981 }
982 pa_datum_free(&value);
983 }else{
984 pa_log("resume state exists but is wrong size!");
985 }
986 pa_database_close(database);
987 }
988
989 /* Called from main context */
990 static pa_bool_t sink_input_may_move_to_cb(pa_sink_input *i, pa_sink *dest) {
991 struct userdata *u;
992
993 pa_sink_input_assert_ref(i);
994 pa_assert_se(u = i->userdata);
995
996 return u->sink != dest;
997 }
998
999 /* Called from main context */
1000 static void sink_input_moving_cb(pa_sink_input *i, pa_sink *dest) {
1001 struct userdata *u;
1002
1003 pa_sink_input_assert_ref(i);
1004 pa_assert_se(u = i->userdata);
1005 if (dest) {
1006 pa_sink_set_asyncmsgq(u->sink, dest->asyncmsgq);
1007 pa_sink_update_flags(u->sink, PA_SINK_LATENCY|PA_SINK_DYNAMIC_LATENCY, dest->flags);
1008 } else
1009 pa_sink_set_asyncmsgq(u->sink, NULL);
1010 }
1011
1012 int pa__init(pa_module*m) {
1013 struct userdata *u;
1014 pa_sample_spec ss;
1015 pa_channel_map map;
1016 pa_modargs *ma;
1017 const char *z;
1018 pa_sink *master;
1019 pa_sink_input_new_data sink_input_data;
1020 pa_sink_new_data sink_data;
1021 size_t fs;
1022 float *H;
1023 unsigned a_i;
1024
1025 pa_assert(m);
1026
1027 if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
1028 pa_log("Failed to parse module arguments.");
1029 goto fail;
1030 }
1031
1032 if (!(master = pa_namereg_get(m->core, pa_modargs_get_value(ma, "master", NULL), PA_NAMEREG_SINK))) {
1033 pa_log("Master sink not found, trying default");
1034 master = pa_namereg_get_default_sink(m->core);
1035 if(!master){
1036 pa_log("no default sink found!");
1037 goto fail;
1038 }
1039 }
1040
1041 ss = master->sample_spec;
1042 ss.format = PA_SAMPLE_FLOAT32;
1043 map = master->channel_map;
1044 if (pa_modargs_get_sample_spec_and_channel_map(ma, &ss, &map, PA_CHANNEL_MAP_DEFAULT) < 0) {
1045 pa_log("Invalid sample format specification or channel map");
1046 goto fail;
1047 }
1048 fs = pa_frame_size(&ss);
1049
1050 u = pa_xnew0(struct userdata, 1);
1051 u->module = m;
1052 m->userdata = u;
1053
1054 u->set_default = TRUE;
1055 pa_modargs_get_value_boolean(ma, "set_default", &u->set_default);
1056
1057 u->channels = ss.channels;
1058 u->fft_size = pow(2, ceil(log(ss.rate) / log(2)));//probably unstable near corner cases of powers of 2
1059 pa_log_debug("fft size: %ld", u->fft_size);
1060 u->window_size = 15999;
1061 if(u->window_size % 2 == 0){
1062 u->window_size--;
1063 }
1064 u->R = (u->window_size + 1) / 2;
1065 u->overlap_size = u->window_size - u->R;
1066 u->samples_gathered = 0;
1067 u->input_buffer_max = 0;
1068 u->a_H = pa_xnew0(pa_aupdate *, u->channels);
1069 u->Xs = pa_xnew0(float *, u->channels);
1070 u->Hs = pa_xnew0(float **, u->channels);
1071 for(size_t c = 0; c < u->channels; ++c){
1072 u->Xs[c] = pa_xnew0(float, 2);
1073 u->Hs[c] = pa_xnew0(float *, 2);
1074 for(size_t i = 0; i < 2; ++i){
1075 u->Hs[c][i] = alloc(FILTER_SIZE, sizeof(float));
1076 }
1077 }
1078 u->W = alloc(u->window_size, sizeof(float));
1079 u->work_buffer = alloc(u->fft_size, sizeof(float));
1080 memset(u->work_buffer, 0, u->fft_size*sizeof(float));
1081 u->input = pa_xnew0(float *, u->channels);
1082 u->overlap_accum = pa_xnew0(float *, u->channels);
1083 for(size_t c = 0; c < u->channels; ++c){
1084 u->a_H[c] = pa_aupdate_new();
1085 u->input[c] = NULL;
1086 u->overlap_accum[c] = alloc(u->overlap_size, sizeof(float));
1087 }
1088 u->output_window = alloc((FILTER_SIZE), sizeof(fftwf_complex));
1089 u->forward_plan = fftwf_plan_dft_r2c_1d(u->fft_size, u->work_buffer, u->output_window, FFTW_ESTIMATE);
1090 u->inverse_plan = fftwf_plan_dft_c2r_1d(u->fft_size, u->output_window, u->work_buffer, FFTW_ESTIMATE);
1091
1092 hanning_window(u->W, u->window_size);
1093 u->first_iteration = TRUE;
1094
1095 u->base_profiles = pa_xnew0(char *, u->channels);
1096 for(size_t c = 0; c < u->channels; ++c){
1097 u->base_profiles[c] = pa_xstrdup("default");
1098 }
1099
1100 /* Create sink */
1101 pa_sink_new_data_init(&sink_data);
1102 sink_data.driver = __FILE__;
1103 sink_data.module = m;
1104 if (!(sink_data.name = pa_xstrdup(pa_modargs_get_value(ma, "sink_name", NULL))))
1105 sink_data.name = pa_sprintf_malloc("%s.equalizer", master->name);
1106 pa_sink_new_data_set_sample_spec(&sink_data, &ss);
1107 pa_sink_new_data_set_channel_map(&sink_data, &map);
1108 z = pa_proplist_gets(master->proplist, PA_PROP_DEVICE_DESCRIPTION);
1109 pa_proplist_setf(sink_data.proplist, PA_PROP_DEVICE_DESCRIPTION, "FFT based equalizer on %s",z? z: master->name);
1110 pa_proplist_sets(sink_data.proplist, PA_PROP_DEVICE_MASTER_DEVICE, master->name);
1111 pa_proplist_sets(sink_data.proplist, PA_PROP_DEVICE_CLASS, "filter");
1112
1113 if (pa_modargs_get_proplist(ma, "sink_properties", sink_data.proplist, PA_UPDATE_REPLACE) < 0) {
1114 pa_log("Invalid properties");
1115 pa_sink_new_data_done(&sink_data);
1116 goto fail;
1117 }
1118
1119 u->sink = pa_sink_new(m->core, &sink_data,
1120 PA_SINK_HW_MUTE_CTRL|PA_SINK_HW_VOLUME_CTRL|PA_SINK_DECIBEL_VOLUME|
1121 (master->flags & (PA_SINK_LATENCY|PA_SINK_DYNAMIC_LATENCY)));
1122 pa_sink_new_data_done(&sink_data);
1123
1124 if (!u->sink) {
1125 pa_log("Failed to create sink.");
1126 goto fail;
1127 }
1128 u->name=pa_xstrdup(u->sink->name);
1129 u->sink->parent.process_msg = sink_process_msg_cb;
1130 u->sink->set_state = sink_set_state_cb;
1131 u->sink->update_requested_latency = sink_update_requested_latency_cb;
1132 u->sink->request_rewind = sink_request_rewind_cb;
1133 u->sink->set_volume = sink_set_volume_cb;
1134 u->sink->set_mute = sink_set_mute_cb;
1135 u->sink->userdata = u;
1136 u->input_q = pa_memblockq_new(0, MEMBLOCKQ_MAXLENGTH, 0, fs, 1, 1, 0, &u->sink->silence);
1137
1138 pa_sink_set_asyncmsgq(u->sink, master->asyncmsgq);
1139 //pa_sink_set_fixed_latency(u->sink, pa_bytes_to_usec(u->R*fs, &ss));
1140
1141 /* Create sink input */
1142 pa_sink_input_new_data_init(&sink_input_data);
1143 sink_input_data.driver = __FILE__;
1144 sink_input_data.module = m;
1145 sink_input_data.sink = master;
1146 pa_proplist_sets(sink_input_data.proplist, PA_PROP_MEDIA_NAME, "Equalized Stream");
1147 pa_proplist_sets(sink_input_data.proplist, PA_PROP_MEDIA_ROLE, "filter");
1148 pa_sink_input_new_data_set_sample_spec(&sink_input_data, &ss);
1149 pa_sink_input_new_data_set_channel_map(&sink_input_data, &map);
1150
1151 pa_sink_input_new(&u->sink_input, m->core, &sink_input_data);
1152 pa_sink_input_new_data_done(&sink_input_data);
1153
1154 if (!u->sink_input)
1155 goto fail;
1156
1157 u->sink_input->pop = sink_input_pop_cb;
1158 u->sink_input->process_rewind = sink_input_process_rewind_cb;
1159 u->sink_input->update_max_rewind = sink_input_update_max_rewind_cb;
1160 u->sink_input->update_max_request = sink_input_update_max_request_cb;
1161 u->sink_input->update_sink_latency_range = sink_input_update_sink_latency_range_cb;
1162 u->sink_input->update_sink_fixed_latency = sink_input_update_sink_fixed_latency_cb;
1163 u->sink_input->kill = sink_input_kill_cb;
1164 u->sink_input->attach = sink_input_attach_cb;
1165 u->sink_input->detach = sink_input_detach_cb;
1166 u->sink_input->state_change = sink_input_state_change_cb;
1167 u->sink_input->may_move_to = sink_input_may_move_to_cb;
1168 u->sink_input->moving = sink_input_moving_cb;
1169 u->sink_input->volume_changed = sink_input_volume_changed_cb;
1170 u->sink_input->mute_changed = sink_input_mute_changed_cb;
1171
1172 u->sink_input->userdata = u;
1173
1174 pa_sink_put(u->sink);
1175 pa_sink_input_put(u->sink_input);
1176
1177 pa_modargs_free(ma);
1178
1179
1180 dbus_init(u);
1181
1182 //default filter to these
1183 for(size_t c = 0; c< u->channels; ++c){
1184 a_i = pa_aupdate_write_begin(u->a_H[c]);
1185 H = u->Hs[c][a_i];
1186 u->Xs[c][a_i] = 1.0f;
1187 for(size_t i = 0; i < FILTER_SIZE; ++i){
1188 H[i] = 1.0 / sqrtf(2.0f);
1189 }
1190 fix_filter(H, u->fft_size);
1191 pa_aupdate_write_end(u->a_H[c]);
1192 }
1193 //load old parameters
1194 load_state(u);
1195
1196 return 0;
1197
1198 fail:
1199 if (ma)
1200 pa_modargs_free(ma);
1201
1202
1203 pa__done(m);
1204
1205 return -1;
1206 }
1207
1208 int pa__get_n_used(pa_module *m) {
1209 struct userdata *u;
1210
1211 pa_assert(m);
1212 pa_assert_se(u = m->userdata);
1213
1214 return pa_sink_linked_by(u->sink);
1215 }
1216
1217 void pa__done(pa_module*m) {
1218 struct userdata *u;
1219
1220 pa_assert(m);
1221
1222 if (!(u = m->userdata))
1223 return;
1224
1225 save_state(u);
1226
1227 dbus_done(u);
1228
1229 for(size_t c = 0; c < u->channels; ++c){
1230 pa_xfree(u->base_profiles[c]);
1231 }
1232 pa_xfree(u->base_profiles);
1233
1234 /* See comments in sink_input_kill_cb() above regarding
1235 * destruction order! */
1236
1237 if (u->sink_input)
1238 pa_sink_input_unlink(u->sink_input);
1239
1240 if (u->sink)
1241 pa_sink_unlink(u->sink);
1242
1243 if (u->sink_input)
1244 pa_sink_input_unref(u->sink_input);
1245
1246 if (u->sink)
1247 pa_sink_unref(u->sink);
1248
1249 pa_memblockq_free(u->input_q);
1250
1251 fftwf_destroy_plan(u->inverse_plan);
1252 fftwf_destroy_plan(u->forward_plan);
1253 pa_xfree(u->output_window);
1254 for(size_t c=0; c < u->channels; ++c){
1255 pa_aupdate_free(u->a_H[c]);
1256 pa_xfree(u->overlap_accum[c]);
1257 pa_xfree(u->input[c]);
1258 }
1259 pa_xfree(u->a_H);
1260 pa_xfree(u->overlap_accum);
1261 pa_xfree(u->input);
1262 pa_xfree(u->work_buffer);
1263 pa_xfree(u->W);
1264 for(size_t c = 0; c < u->channels; ++c){
1265 pa_xfree(u->Xs[c]);
1266 for(size_t i = 0; i < 2; ++i){
1267 pa_xfree(u->Hs[c][i]);
1268 }
1269 pa_xfree(u->Hs[c]);
1270 }
1271 pa_xfree(u->Xs);
1272 pa_xfree(u->Hs);
1273
1274 pa_xfree(u->name);
1275
1276 pa_xfree(u);
1277 }
1278
1279 /*
1280 * DBus Routines and Callbacks
1281 */
1282 #define EXTNAME "org.PulseAudio.Ext.Equalizing1"
1283 #define MANAGER_PATH "/org/pulseaudio/equalizing1"
1284 #define MANAGER_IFACE EXTNAME ".Manager"
1285 #define EQUALIZER_IFACE EXTNAME ".Equalizer"
1286 static void manager_get_revision(DBusConnection *conn, DBusMessage *msg, void *_u);
1287 static void manager_get_sinks(DBusConnection *conn, DBusMessage *msg, void *_u);
1288 static void manager_get_profiles(DBusConnection *conn, DBusMessage *msg, void *_u);
1289 static void manager_get_all(DBusConnection *conn, DBusMessage *msg, void *_u);
1290 static void manager_handle_remove_profile(DBusConnection *conn, DBusMessage *msg, void *_u);
1291 static void equalizer_get_revision(DBusConnection *conn, DBusMessage *msg, void *_u);
1292 static void equalizer_get_sample_rate(DBusConnection *conn, DBusMessage *msg, void *_u);
1293 static void equalizer_get_filter_rate(DBusConnection *conn, DBusMessage *msg, void *_u);
1294 static void equalizer_get_n_coefs(DBusConnection *conn, DBusMessage *msg, void *_u);
1295 static void equalizer_get_n_channels(DBusConnection *conn, DBusMessage *msg, void *_u);
1296 static void equalizer_get_all(DBusConnection *conn, DBusMessage *msg, void *_u);
1297 static void equalizer_handle_seed_filter(DBusConnection *conn, DBusMessage *msg, void *_u);
1298 static void equalizer_handle_get_filter_points(DBusConnection *conn, DBusMessage *msg, void *_u);
1299 static void equalizer_handle_get_filter(DBusConnection *conn, DBusMessage *msg, void *_u);
1300 static void equalizer_handle_set_filter(DBusConnection *conn, DBusMessage *msg, void *_u);
1301 static void equalizer_handle_save_profile(DBusConnection *conn, DBusMessage *msg, void *_u);
1302 static void equalizer_handle_load_profile(DBusConnection *conn, DBusMessage *msg, void *_u);
1303 static void equalizer_handle_save_state(DBusConnection *conn, DBusMessage *msg, void *_u);
1304 static void equalizer_handle_get_profile_name(DBusConnection *conn, DBusMessage *msg, void *_u);
1305 enum manager_method_index {
1306 MANAGER_METHOD_REMOVE_PROFILE,
1307 MANAGER_METHOD_MAX
1308 };
1309
1310 pa_dbus_arg_info remove_profile_args[]={
1311 {"name", "s","in"},
1312 };
1313
1314 static pa_dbus_method_handler manager_methods[MANAGER_METHOD_MAX]={
1315 [MANAGER_METHOD_REMOVE_PROFILE]{
1316 .method_name="RemoveProfile",
1317 .arguments=remove_profile_args,
1318 .n_arguments=sizeof(remove_profile_args)/sizeof(pa_dbus_arg_info),
1319 .receive_cb=manager_handle_remove_profile}
1320 };
1321
1322 enum manager_handler_index {
1323 MANAGER_HANDLER_REVISION,
1324 MANAGER_HANDLER_EQUALIZED_SINKS,
1325 MANAGER_HANDLER_PROFILES,
1326 MANAGER_HANDLER_MAX
1327 };
1328
1329 static pa_dbus_property_handler manager_handlers[MANAGER_HANDLER_MAX]={
1330 [MANAGER_HANDLER_REVISION]={.property_name="InterfaceRevision",.type="u",.get_cb=manager_get_revision,.set_cb=NULL},
1331 [MANAGER_HANDLER_EQUALIZED_SINKS]={.property_name="EqualizedSinks",.type="ao",.get_cb=manager_get_sinks,.set_cb=NULL},
1332 [MANAGER_HANDLER_PROFILES]={.property_name="Profiles",.type="as",.get_cb=manager_get_profiles,.set_cb=NULL}
1333 };
1334
1335 pa_dbus_arg_info sink_args[]={
1336 {"sink", "o", NULL}
1337 };
1338
1339 enum manager_signal_index{
1340 MANAGER_SIGNAL_SINK_ADDED,
1341 MANAGER_SIGNAL_SINK_REMOVED,
1342 MANAGER_SIGNAL_PROFILES_CHANGED,
1343 MANAGER_SIGNAL_MAX
1344 };
1345
1346 static pa_dbus_signal_info manager_signals[MANAGER_SIGNAL_MAX]={
1347 [MANAGER_SIGNAL_SINK_ADDED]={.name="SinkAdded", .arguments=sink_args, .n_arguments=sizeof(sink_args)/sizeof(pa_dbus_arg_info)},
1348 [MANAGER_SIGNAL_SINK_REMOVED]={.name="SinkRemoved", .arguments=sink_args, .n_arguments=sizeof(sink_args)/sizeof(pa_dbus_arg_info)},
1349 [MANAGER_SIGNAL_PROFILES_CHANGED]={.name="ProfilesChanged", .arguments=NULL, .n_arguments=0}
1350 };
1351
1352 static pa_dbus_interface_info manager_info={
1353 .name=MANAGER_IFACE,
1354 .method_handlers=manager_methods,
1355 .n_method_handlers=MANAGER_METHOD_MAX,
1356 .property_handlers=manager_handlers,
1357 .n_property_handlers=MANAGER_HANDLER_MAX,
1358 .get_all_properties_cb=manager_get_all,
1359 .signals=manager_signals,
1360 .n_signals=MANAGER_SIGNAL_MAX
1361 };
1362
1363 enum equalizer_method_index {
1364 EQUALIZER_METHOD_FILTER_POINTS,
1365 EQUALIZER_METHOD_SEED_FILTER,
1366 EQUALIZER_METHOD_SAVE_PROFILE,
1367 EQUALIZER_METHOD_LOAD_PROFILE,
1368 EQUALIZER_METHOD_SET_FILTER,
1369 EQUALIZER_METHOD_GET_FILTER,
1370 EQUALIZER_METHOD_SAVE_STATE,
1371 EQUALIZER_METHOD_GET_PROFILE_NAME,
1372 EQUALIZER_METHOD_MAX
1373 };
1374
1375 enum equalizer_handler_index {
1376 EQUALIZER_HANDLER_REVISION,
1377 EQUALIZER_HANDLER_SAMPLERATE,
1378 EQUALIZER_HANDLER_FILTERSAMPLERATE,
1379 EQUALIZER_HANDLER_N_COEFS,
1380 EQUALIZER_HANDLER_N_CHANNELS,
1381 EQUALIZER_HANDLER_MAX
1382 };
1383
1384 pa_dbus_arg_info filter_points_args[]={
1385 {"channel", "u","in"},
1386 {"xs", "au","in"},
1387 {"ys", "ad","out"},
1388 {"preamp", "d","out"}
1389 };
1390 pa_dbus_arg_info seed_filter_args[]={
1391 {"channel", "u","in"},
1392 {"xs", "au","in"},
1393 {"ys", "ad","in"},
1394 {"preamp", "d","in"}
1395 };
1396
1397 pa_dbus_arg_info set_filter_args[]={
1398 {"channel", "u","in"},
1399 {"ys", "ad","in"},
1400 {"preamp", "d","in"}
1401 };
1402 pa_dbus_arg_info get_filter_args[]={
1403 {"channel", "u","in"},
1404 {"ys", "ad","out"},
1405 {"preamp", "d","out"}
1406 };
1407
1408 pa_dbus_arg_info save_profile_args[]={
1409 {"channel", "u","in"},
1410 {"name", "s","in"}
1411 };
1412 pa_dbus_arg_info load_profile_args[]={
1413 {"channel", "u","in"},
1414 {"name", "s","in"}
1415 };
1416 pa_dbus_arg_info base_profile_name_args[]={
1417 {"channel", "u","in"},
1418 {"name", "s","out"}
1419 };
1420
1421 static pa_dbus_method_handler equalizer_methods[EQUALIZER_METHOD_MAX]={
1422 [EQUALIZER_METHOD_SEED_FILTER]{
1423 .method_name="SeedFilter",
1424 .arguments=seed_filter_args,
1425 .n_arguments=sizeof(seed_filter_args)/sizeof(pa_dbus_arg_info),
1426 .receive_cb=equalizer_handle_seed_filter},
1427 [EQUALIZER_METHOD_FILTER_POINTS]{
1428 .method_name="FilterAtPoints",
1429 .arguments=filter_points_args,
1430 .n_arguments=sizeof(filter_points_args)/sizeof(pa_dbus_arg_info),
1431 .receive_cb=equalizer_handle_get_filter_points},
1432 [EQUALIZER_METHOD_SET_FILTER]{
1433 .method_name="SetFilter",
1434 .arguments=set_filter_args,
1435 .n_arguments=sizeof(set_filter_args)/sizeof(pa_dbus_arg_info),
1436 .receive_cb=equalizer_handle_set_filter},
1437 [EQUALIZER_METHOD_GET_FILTER]{
1438 .method_name="GetFilter",
1439 .arguments=get_filter_args,
1440 .n_arguments=sizeof(get_filter_args)/sizeof(pa_dbus_arg_info),
1441 .receive_cb=equalizer_handle_get_filter},
1442 [EQUALIZER_METHOD_SAVE_PROFILE]{
1443 .method_name="SaveProfile",
1444 .arguments=save_profile_args,
1445 .n_arguments=sizeof(save_profile_args)/sizeof(pa_dbus_arg_info),
1446 .receive_cb=equalizer_handle_save_profile},
1447 [EQUALIZER_METHOD_LOAD_PROFILE]{
1448 .method_name="LoadProfile",
1449 .arguments=load_profile_args,
1450 .n_arguments=sizeof(load_profile_args)/sizeof(pa_dbus_arg_info),
1451 .receive_cb=equalizer_handle_load_profile},
1452 [EQUALIZER_METHOD_SAVE_STATE]{
1453 .method_name="SaveState",
1454 .arguments=NULL,
1455 .n_arguments=0,
1456 .receive_cb=equalizer_handle_save_state},
1457 [EQUALIZER_METHOD_GET_PROFILE_NAME]{
1458 .method_name="BaseProfile",
1459 .arguments=base_profile_name_args,
1460 .n_arguments=sizeof(base_profile_name_args)/sizeof(pa_dbus_arg_info),
1461 .receive_cb=equalizer_handle_get_profile_name}
1462 };
1463
1464 static pa_dbus_property_handler equalizer_handlers[EQUALIZER_HANDLER_MAX]={
1465 [EQUALIZER_HANDLER_REVISION]={.property_name="InterfaceRevision",.type="u",.get_cb=equalizer_get_revision,.set_cb=NULL},
1466 [EQUALIZER_HANDLER_SAMPLERATE]{.property_name="SampleRate",.type="u",.get_cb=equalizer_get_sample_rate,.set_cb=NULL},
1467 [EQUALIZER_HANDLER_FILTERSAMPLERATE]{.property_name="FilterSampleRate",.type="u",.get_cb=equalizer_get_filter_rate,.set_cb=NULL},
1468 [EQUALIZER_HANDLER_N_COEFS]{.property_name="NFilterCoefficients",.type="u",.get_cb=equalizer_get_n_coefs,.set_cb=NULL},
1469 [EQUALIZER_HANDLER_N_CHANNELS]{.property_name="NChannels",.type="u",.get_cb=equalizer_get_n_channels,.set_cb=NULL},
1470 };
1471
1472 enum equalizer_signal_index{
1473 EQUALIZER_SIGNAL_FILTER_CHANGED,
1474 EQUALIZER_SIGNAL_SINK_RECONFIGURED,
1475 EQUALIZER_SIGNAL_MAX
1476 };
1477
1478 static pa_dbus_signal_info equalizer_signals[EQUALIZER_SIGNAL_MAX]={
1479 [EQUALIZER_SIGNAL_FILTER_CHANGED]={.name="FilterChanged", .arguments=NULL, .n_arguments=0},
1480 [EQUALIZER_SIGNAL_SINK_RECONFIGURED]={.name="SinkReconfigured", .arguments=NULL, .n_arguments=0},
1481 };
1482
1483 static pa_dbus_interface_info equalizer_info={
1484 .name=EQUALIZER_IFACE,
1485 .method_handlers=equalizer_methods,
1486 .n_method_handlers=EQUALIZER_METHOD_MAX,
1487 .property_handlers=equalizer_handlers,
1488 .n_property_handlers=EQUALIZER_HANDLER_MAX,
1489 .get_all_properties_cb=equalizer_get_all,
1490 .signals=equalizer_signals,
1491 .n_signals=EQUALIZER_SIGNAL_MAX
1492 };
1493
1494 void dbus_init(struct userdata *u){
1495 uint32_t dummy;
1496 DBusMessage *signal = NULL;
1497 pa_idxset *sink_list = NULL;
1498 u->dbus_protocol=pa_dbus_protocol_get(u->sink->core);
1499 u->dbus_path=pa_sprintf_malloc("/org/pulseaudio/core1/sink%d", u->sink->index);
1500
1501 pa_dbus_protocol_add_interface(u->dbus_protocol, u->dbus_path, &equalizer_info, u);
1502 sink_list = pa_shared_get(u->sink->core, SINKLIST);
1503 u->database = pa_shared_get(u->sink->core, EQDB);
1504 if(sink_list == NULL){
1505 char *dbname;
1506 sink_list=pa_idxset_new(&pa_idxset_trivial_hash_func, &pa_idxset_trivial_compare_func);
1507 pa_shared_set(u->sink->core, SINKLIST, sink_list);
1508 pa_assert_se(dbname = pa_state_path("equalizer-presets", FALSE));
1509 pa_assert_se(u->database = pa_database_open(dbname, TRUE));
1510 pa_xfree(dbname);
1511 pa_shared_set(u->sink->core, EQDB, u->database);
1512 pa_dbus_protocol_add_interface(u->dbus_protocol, MANAGER_PATH, &manager_info, u->sink->core);
1513 pa_dbus_protocol_register_extension(u->dbus_protocol, EXTNAME);
1514 }
1515 pa_idxset_put(sink_list, u, &dummy);
1516
1517 pa_assert_se((signal = dbus_message_new_signal(MANAGER_PATH, MANAGER_IFACE, manager_signals[MANAGER_SIGNAL_SINK_ADDED].name)));
1518 dbus_message_append_args(signal, DBUS_TYPE_OBJECT_PATH, &u->dbus_path, DBUS_TYPE_INVALID);
1519 pa_dbus_protocol_send_signal(u->dbus_protocol, signal);
1520 dbus_message_unref(signal);
1521 }
1522
1523 void dbus_done(struct userdata *u){
1524 pa_idxset *sink_list;
1525 uint32_t dummy;
1526
1527 DBusMessage *signal = NULL;
1528 pa_assert_se((signal = dbus_message_new_signal(MANAGER_PATH, MANAGER_IFACE, manager_signals[MANAGER_SIGNAL_SINK_REMOVED].name)));
1529 dbus_message_append_args(signal, DBUS_TYPE_OBJECT_PATH, &u->dbus_path, DBUS_TYPE_INVALID);
1530 pa_dbus_protocol_send_signal(u->dbus_protocol, signal);
1531 dbus_message_unref(signal);
1532
1533 pa_assert_se(sink_list=pa_shared_get(u->sink->core,SINKLIST));
1534 pa_idxset_remove_by_data(sink_list,u,&dummy);
1535 if(pa_idxset_size(sink_list)==0){
1536 pa_dbus_protocol_unregister_extension(u->dbus_protocol, EXTNAME);
1537 pa_dbus_protocol_remove_interface(u->dbus_protocol, MANAGER_PATH, manager_info.name);
1538 pa_shared_remove(u->sink->core, EQDB);
1539 pa_database_close(u->database);
1540 pa_shared_remove(u->sink->core, SINKLIST);
1541 pa_xfree(sink_list);
1542 }
1543 pa_dbus_protocol_remove_interface(u->dbus_protocol, u->dbus_path, equalizer_info.name);
1544 pa_xfree(u->dbus_path);
1545 pa_dbus_protocol_unref(u->dbus_protocol);
1546 }
1547
1548 void manager_handle_remove_profile(DBusConnection *conn, DBusMessage *msg, void *_u) {
1549 DBusError error;
1550 pa_core *c = (pa_core *)_u;
1551 DBusMessage *signal = NULL;
1552 pa_dbus_protocol *dbus_protocol;
1553 char *name;
1554 pa_assert(conn);
1555 pa_assert(msg);
1556 pa_assert(c);
1557 dbus_error_init(&error);
1558 if(!dbus_message_get_args(msg, &error,
1559 DBUS_TYPE_STRING, &name,
1560 DBUS_TYPE_INVALID)){
1561 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "%s", error.message);
1562 dbus_error_free(&error);
1563 return;
1564 }
1565 remove_profile(c,name);
1566 pa_dbus_send_empty_reply(conn, msg);
1567
1568 pa_assert_se((signal = dbus_message_new_signal(MANAGER_PATH, MANAGER_IFACE, manager_signals[MANAGER_SIGNAL_PROFILES_CHANGED].name)));
1569 dbus_protocol = pa_dbus_protocol_get(c);
1570 pa_dbus_protocol_send_signal(dbus_protocol, signal);
1571 pa_dbus_protocol_unref(dbus_protocol);
1572 dbus_message_unref(signal);
1573 }
1574
1575 void manager_get_revision(DBusConnection *conn, DBusMessage *msg, void *_u){
1576 uint32_t rev=1;
1577 pa_dbus_send_basic_value_reply(conn, msg, DBUS_TYPE_UINT32, &rev);
1578 }
1579
1580 static void get_sinks(pa_core *u, char ***names, unsigned *n_sinks){
1581 void *iter = NULL;
1582 struct userdata *sink_u = NULL;
1583 uint32_t dummy;
1584 pa_idxset *sink_list;
1585 pa_assert(u);
1586 pa_assert(names);
1587 pa_assert(n_sinks);
1588
1589 pa_assert_se(sink_list = pa_shared_get(u, SINKLIST));
1590 *n_sinks = (unsigned) pa_idxset_size(sink_list);
1591 *names = *n_sinks > 0 ? pa_xnew0(char *,*n_sinks) : NULL;
1592 for(uint32_t i = 0; i < *n_sinks; ++i){
1593 sink_u = (struct userdata *) pa_idxset_iterate(sink_list, &iter, &dummy);
1594 (*names)[i] = pa_xstrdup(sink_u->dbus_path);
1595 }
1596 }
1597
1598 void manager_get_sinks(DBusConnection *conn, DBusMessage *msg, void *_u){
1599 unsigned n;
1600 char **names = NULL;
1601 pa_assert(conn);
1602 pa_assert(msg);
1603 pa_assert(_u);
1604
1605 get_sinks((pa_core *) _u, &names, &n);
1606 pa_dbus_send_basic_array_variant_reply(conn, msg, DBUS_TYPE_OBJECT_PATH, names, n);
1607 for(unsigned i = 0; i < n; ++i){
1608 pa_xfree(names[i]);
1609 }
1610 pa_xfree(names);
1611 }
1612
1613 static void get_profiles(pa_core *c, char ***names, unsigned *n){
1614 char *name;
1615 pa_database *database;
1616 pa_datum key, next_key;
1617 pa_strlist *head=NULL, *iter;
1618 pa_bool_t done;
1619 pa_assert_se(database = pa_shared_get(c, EQDB));
1620
1621 pa_assert(c);
1622 pa_assert(names);
1623 pa_assert(n);
1624 done = !pa_database_first(database, &key, NULL);
1625 *n = 0;
1626 while(!done){
1627 done = !pa_database_next(database, &key, &next_key, NULL);
1628 name=pa_xmalloc(key.size + 1);
1629 memcpy(name, key.data, key.size);
1630 name[key.size] = '\0';
1631 pa_datum_free(&key);
1632 head = pa_strlist_prepend(head, name);
1633 pa_xfree(name);
1634 key = next_key;
1635 (*n)++;
1636 }
1637 (*names) = *n > 0 ? pa_xnew0(char *, *n) : NULL;
1638 iter=head;
1639 for(unsigned i = 0; i < *n; ++i){
1640 (*names)[*n - 1 - i] = pa_xstrdup(pa_strlist_data(iter));
1641 iter = pa_strlist_next(iter);
1642 }
1643 pa_strlist_free(head);
1644 }
1645
1646 void manager_get_profiles(DBusConnection *conn, DBusMessage *msg, void *_u){
1647 char **names;
1648 unsigned n;
1649 pa_assert(conn);
1650 pa_assert(msg);
1651 pa_assert(_u);
1652
1653 get_profiles((pa_core *)_u, &names, &n);
1654 pa_dbus_send_basic_array_variant_reply(conn, msg, DBUS_TYPE_STRING, names, n);
1655 for(unsigned i = 0; i < n; ++i){
1656 pa_xfree(names[i]);
1657 }
1658 pa_xfree(names);
1659 }
1660
1661 void manager_get_all(DBusConnection *conn, DBusMessage *msg, void *_u){
1662 pa_core *c;
1663 char **names = NULL;
1664 unsigned n;
1665 DBusMessage *reply = NULL;
1666 DBusMessageIter msg_iter, dict_iter;
1667 uint32_t rev;
1668 pa_assert(conn);
1669 pa_assert(msg);
1670 pa_assert_se(c = _u);
1671
1672 pa_assert_se((reply = dbus_message_new_method_return(msg)));
1673 dbus_message_iter_init_append(reply, &msg_iter);
1674 pa_assert_se(dbus_message_iter_open_container(&msg_iter, DBUS_TYPE_ARRAY, "{sv}", &dict_iter));
1675
1676 rev = 1;
1677 pa_dbus_append_basic_variant_dict_entry(&dict_iter, manager_handlers[MANAGER_HANDLER_REVISION].property_name, DBUS_TYPE_UINT32, &rev);
1678
1679 get_sinks(c, &names, &n);
1680 pa_dbus_append_basic_array_variant_dict_entry(&dict_iter,manager_handlers[MANAGER_HANDLER_EQUALIZED_SINKS].property_name, DBUS_TYPE_OBJECT_PATH, names, n);
1681 for(unsigned i = 0; i < n; ++i){
1682 pa_xfree(names[i]);
1683 }
1684 pa_xfree(names);
1685
1686 get_profiles(c, &names, &n);
1687 pa_dbus_append_basic_array_variant_dict_entry(&dict_iter, manager_handlers[MANAGER_HANDLER_PROFILES].property_name, DBUS_TYPE_STRING, names, n);
1688 for(unsigned i = 0; i < n; ++i){
1689 pa_xfree(names[i]);
1690 }
1691 pa_xfree(names);
1692 pa_assert_se(dbus_message_iter_close_container(&msg_iter, &dict_iter));
1693 pa_assert_se(dbus_connection_send(conn, reply, NULL));
1694 dbus_message_unref(reply);
1695 }
1696
1697 void equalizer_handle_seed_filter(DBusConnection *conn, DBusMessage *msg, void *_u) {
1698 struct userdata *u=(struct userdata *) _u;
1699 DBusError error;
1700 DBusMessage *signal = NULL;
1701 float *ys;
1702 uint32_t *xs, channel, r_channel;
1703 double *_ys, preamp;
1704 unsigned x_npoints, y_npoints, a_i;
1705 float *H;
1706 pa_bool_t points_good = TRUE;
1707 pa_assert(conn);
1708 pa_assert(msg);
1709 pa_assert(u);
1710
1711 dbus_error_init(&error);
1712
1713 if(!dbus_message_get_args(msg, &error,
1714 DBUS_TYPE_UINT32, &channel,
1715 DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32, &xs, &x_npoints,
1716 DBUS_TYPE_ARRAY, DBUS_TYPE_DOUBLE, &_ys, &y_npoints,
1717 DBUS_TYPE_DOUBLE, &preamp,
1718 DBUS_TYPE_INVALID)){
1719 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "%s", error.message);
1720 dbus_error_free(&error);
1721 return;
1722 }
1723 if(channel > u->channels){
1724 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "invalid channel: %d", channel);
1725 dbus_error_free(&error);
1726 return;
1727 }
1728 for(size_t i = 0; i < x_npoints; ++i){
1729 if(xs[i] >= FILTER_SIZE){
1730 points_good = FALSE;
1731 break;
1732 }
1733 }
1734 if(!is_monotonic(xs, x_npoints) || !points_good){
1735 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "xs must be monotonic and 0<=x<=%ld", u->fft_size / 2);
1736 dbus_error_free(&error);
1737 return;
1738 }else if(x_npoints != y_npoints || x_npoints < 2 || x_npoints > FILTER_SIZE ){
1739 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "xs and ys must be the same length and 2<=l<=%ld!", FILTER_SIZE);
1740 dbus_error_free(&error);
1741 return;
1742 }else if(xs[0] != 0 || xs[x_npoints - 1] != u->fft_size / 2){
1743 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "xs[0] must be 0 and xs[-1]=fft_size/2");
1744 dbus_error_free(&error);
1745 return;
1746 }
1747
1748 ys = pa_xmalloc(x_npoints * sizeof(float));
1749 for(uint32_t i = 0; i < x_npoints; ++i){
1750 ys[i] = (float) _ys[i];
1751 }
1752 r_channel = channel == u->channels ? 0 : channel;
1753 a_i = pa_aupdate_write_begin(u->a_H[r_channel]);
1754 H = u->Hs[r_channel][a_i];
1755 u->Xs[r_channel][a_i] = preamp;
1756 interpolate(H, FILTER_SIZE, xs, ys, x_npoints);
1757 fix_filter(H, u->fft_size);
1758 if(channel == u->channels){
1759 for(size_t c = 1; c < u->channels; ++c){
1760 unsigned b_i = pa_aupdate_write_begin(u->a_H[c]);
1761 float *H_p = u->Hs[c][b_i];
1762 u->Xs[c][b_i] = preamp;
1763 memcpy(H_p, H, FILTER_SIZE * sizeof(float));
1764 pa_aupdate_write_end(u->a_H[c]);
1765 }
1766 }
1767 pa_aupdate_write_end(u->a_H[r_channel]);
1768 pa_xfree(ys);
1769
1770
1771 pa_dbus_send_empty_reply(conn, msg);
1772
1773 pa_assert_se((signal = dbus_message_new_signal(u->dbus_path, EQUALIZER_IFACE, equalizer_signals[EQUALIZER_SIGNAL_FILTER_CHANGED].name)));
1774 pa_dbus_protocol_send_signal(u->dbus_protocol, signal);
1775 dbus_message_unref(signal);
1776 }
1777
1778 void equalizer_handle_get_filter_points(DBusConnection *conn, DBusMessage *msg, void *_u) {
1779 struct userdata *u = (struct userdata *) _u;
1780 uint32_t *xs, channel, r_channel;
1781 double *ys, preamp;
1782 unsigned x_npoints, a_i;
1783 float *H;
1784 pa_bool_t points_good=TRUE;
1785 DBusMessage *reply = NULL;
1786 DBusMessageIter msg_iter;
1787 DBusError error;
1788
1789 pa_assert(conn);
1790 pa_assert(msg);
1791 pa_assert(u);
1792
1793 dbus_error_init(&error);
1794 if(!dbus_message_get_args(msg, &error,
1795 DBUS_TYPE_UINT32, &channel,
1796 DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32, &xs, &x_npoints,
1797 DBUS_TYPE_INVALID)){
1798 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "%s", error.message);
1799 dbus_error_free(&error);
1800 return;
1801 }
1802 if(channel > u->channels){
1803 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "invalid channel: %d", channel);
1804 dbus_error_free(&error);
1805 return;
1806 }
1807
1808 for(size_t i = 0; i < x_npoints; ++i){
1809 if(xs[i] >= FILTER_SIZE){
1810 points_good=FALSE;
1811 break;
1812 }
1813 }
1814
1815 if(x_npoints > FILTER_SIZE || !points_good){
1816 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "xs indices/length must be <= %ld!", FILTER_SIZE);
1817 dbus_error_free(&error);
1818 return;
1819 }
1820
1821 r_channel = channel == u->channels ? 0 : channel;
1822 ys = pa_xmalloc(x_npoints * sizeof(double));
1823 a_i = pa_aupdate_read_begin(u->a_H[r_channel]);
1824 H = u->Hs[r_channel][a_i];
1825 preamp = u->Xs[r_channel][a_i];
1826 for(uint32_t i = 0; i < x_npoints; ++i){
1827 ys[i] = H[xs[i]] * u->fft_size;
1828 }
1829 pa_aupdate_read_end(u->a_H[r_channel]);
1830
1831 pa_assert_se((reply = dbus_message_new_method_return(msg)));
1832 dbus_message_iter_init_append(reply, &msg_iter);
1833
1834 pa_dbus_append_basic_array(&msg_iter, DBUS_TYPE_DOUBLE, ys, x_npoints);
1835 pa_dbus_append_basic_variant(&msg_iter, DBUS_TYPE_DOUBLE, &preamp);
1836
1837 pa_assert_se(dbus_connection_send(conn, reply, NULL));
1838 dbus_message_unref(reply);
1839 pa_xfree(ys);
1840 }
1841
1842 static void get_filter(struct userdata *u, size_t channel, double **H_, double *preamp){
1843 float *H;
1844 unsigned a_i;
1845 size_t r_channel = channel == u->channels ? 0 : channel;
1846 *H_ = pa_xnew0(double, FILTER_SIZE);
1847 a_i = pa_aupdate_read_begin(u->a_H[r_channel]);
1848 H = u->Hs[r_channel][a_i];
1849 for(size_t i = 0;i < FILTER_SIZE; ++i){
1850 (*H_)[i] = H[i] * u->fft_size;
1851 }
1852 *preamp = u->Xs[r_channel][a_i];
1853
1854 pa_aupdate_read_end(u->a_H[r_channel]);
1855 }
1856
1857 void equalizer_handle_get_filter(DBusConnection *conn, DBusMessage *msg, void *_u){
1858 struct userdata *u;
1859 unsigned n_coefs;
1860 uint32_t channel;
1861 double *H_, preamp;
1862 DBusMessage *reply = NULL;
1863 DBusMessageIter msg_iter;
1864 DBusError error;
1865 pa_assert_se(u = (struct userdata *) _u);
1866 pa_assert(conn);
1867 pa_assert(msg);
1868
1869 dbus_error_init(&error);
1870 if(!dbus_message_get_args(msg, &error,
1871 DBUS_TYPE_UINT32, &channel,
1872 DBUS_TYPE_INVALID)){
1873 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "%s", error.message);
1874 dbus_error_free(&error);
1875 return;
1876 }
1877 if(channel > u->channels){
1878 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "invalid channel: %d", channel);
1879 dbus_error_free(&error);
1880 return;
1881 }
1882
1883 n_coefs = CHANNEL_PROFILE_SIZE;
1884 pa_assert(conn);
1885 pa_assert(msg);
1886 get_filter(u, channel, &H_, &preamp);
1887 pa_assert_se((reply = dbus_message_new_method_return(msg)));
1888 dbus_message_iter_init_append(reply, &msg_iter);
1889
1890 pa_dbus_append_basic_array(&msg_iter, DBUS_TYPE_DOUBLE, H_, n_coefs);
1891 pa_dbus_append_basic_variant(&msg_iter, DBUS_TYPE_DOUBLE, &preamp);
1892
1893 pa_assert_se(dbus_connection_send(conn, reply, NULL));
1894 dbus_message_unref(reply);
1895 pa_xfree(H_);
1896 }
1897
1898 static void set_filter(struct userdata *u, size_t channel, double *H_, double preamp){
1899 unsigned a_i;
1900 size_t r_channel = channel == u->channels ? 0 : channel;
1901 float *H;
1902 //all channels
1903 a_i = pa_aupdate_write_begin(u->a_H[r_channel]);
1904 u->Xs[r_channel][a_i] = (float) preamp;
1905 H = u->Hs[r_channel][a_i];
1906 for(size_t i = 0; i < FILTER_SIZE; ++i){
1907 H[i] = (float) H_[i];
1908 }
1909 fix_filter(H, u->fft_size);
1910 if(channel == u->channels){
1911 for(size_t c = 1; c < u->channels; ++c){
1912 unsigned b_i = pa_aupdate_write_begin(u->a_H[c]);
1913 u->Xs[c][b_i] = u->Xs[r_channel][a_i];
1914 memcpy(u->Hs[c][b_i], u->Hs[r_channel][a_i], FILTER_SIZE * sizeof(float));
1915 pa_aupdate_write_end(u->a_H[c]);
1916 }
1917 }
1918 pa_aupdate_write_end(u->a_H[r_channel]);
1919 }
1920
1921 void equalizer_handle_set_filter(DBusConnection *conn, DBusMessage *msg, void *_u){
1922 struct userdata *u;
1923 double *H, preamp;
1924 uint32_t channel;
1925 unsigned _n_coefs;
1926 DBusMessage *signal = NULL;
1927 DBusError error;
1928 pa_assert_se(u = (struct userdata *) _u);
1929 pa_assert(conn);
1930 pa_assert(msg);
1931
1932 dbus_error_init(&error);
1933 if(!dbus_message_get_args(msg, &error,
1934 DBUS_TYPE_UINT32, &channel,
1935 DBUS_TYPE_ARRAY, DBUS_TYPE_DOUBLE, &H, &_n_coefs,
1936 DBUS_TYPE_DOUBLE, &preamp,
1937 DBUS_TYPE_INVALID)){
1938 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "%s", error.message);
1939 dbus_error_free(&error);
1940 return;
1941 }
1942 if(channel > u->channels){
1943 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "invalid channel: %d", channel);
1944 dbus_error_free(&error);
1945 return;
1946 }
1947 if(_n_coefs != FILTER_SIZE){
1948 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "This filter takes exactly %ld coefficients, you gave %d", FILTER_SIZE, _n_coefs);
1949 return;
1950 }
1951 set_filter(u, channel, H, preamp);
1952
1953 pa_dbus_send_empty_reply(conn, msg);
1954
1955 pa_assert_se((signal = dbus_message_new_signal(u->dbus_path, EQUALIZER_IFACE, equalizer_signals[EQUALIZER_SIGNAL_FILTER_CHANGED].name)));
1956 pa_dbus_protocol_send_signal(u->dbus_protocol, signal);
1957 dbus_message_unref(signal);
1958 }
1959
1960 void equalizer_handle_save_profile(DBusConnection *conn, DBusMessage *msg, void *_u) {
1961 struct userdata *u = (struct userdata *) _u;
1962 char *name;
1963 uint32_t channel, r_channel;
1964 DBusMessage *signal = NULL;
1965 DBusError error;
1966 pa_assert(conn);
1967 pa_assert(msg);
1968 pa_assert(u);
1969 dbus_error_init(&error);
1970
1971 if(!dbus_message_get_args(msg, &error,
1972 DBUS_TYPE_UINT32, &channel,
1973 DBUS_TYPE_STRING, &name,
1974 DBUS_TYPE_INVALID)){
1975 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "%s", error.message);
1976 dbus_error_free(&error);
1977 return;
1978 }
1979 if(channel > u->channels){
1980 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "invalid channel: %d", channel);
1981 dbus_error_free(&error);
1982 return;
1983 }
1984 r_channel = channel == u->channels ? 0 : channel;
1985 save_profile(u, r_channel, name);
1986 pa_dbus_send_empty_reply(conn, msg);
1987
1988 pa_assert_se((signal = dbus_message_new_signal(MANAGER_PATH, MANAGER_IFACE, manager_signals[MANAGER_SIGNAL_PROFILES_CHANGED].name)));
1989 pa_dbus_protocol_send_signal(u->dbus_protocol, signal);
1990 dbus_message_unref(signal);
1991 }
1992
1993 void equalizer_handle_load_profile(DBusConnection *conn, DBusMessage *msg, void *_u) {
1994 struct userdata *u = (struct userdata *) _u;
1995 char *name;
1996 DBusError error;
1997 uint32_t channel, r_channel;
1998 const char *err_msg = NULL;
1999 DBusMessage *signal = NULL;
2000
2001 pa_assert(conn);
2002 pa_assert(msg);
2003 pa_assert(u);
2004 dbus_error_init(&error);
2005
2006 if(!dbus_message_get_args(msg, &error,
2007 DBUS_TYPE_UINT32, &channel,
2008 DBUS_TYPE_STRING, &name,
2009 DBUS_TYPE_INVALID)){
2010 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "%s", error.message);
2011 dbus_error_free(&error);
2012 return;
2013 }
2014 if(channel > u->channels){
2015 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "invalid channel: %d", channel);
2016 dbus_error_free(&error);
2017 return;
2018 }
2019 r_channel = channel == u->channels ? 0 : channel;
2020
2021 err_msg = load_profile(u, r_channel, name);
2022 if(err_msg != NULL){
2023 pa_dbus_send_error(conn, msg, DBUS_ERROR_FAILED, "error loading profile %s: %s", name, err_msg);
2024 dbus_error_free(&error);
2025 return;
2026 }
2027 if(channel == u->channels){
2028 for(uint32_t c = 1; c < u->channels; ++c){
2029 load_profile(u, c, name);
2030 }
2031 }
2032 pa_dbus_send_empty_reply(conn, msg);
2033
2034 pa_assert_se((signal = dbus_message_new_signal(u->dbus_path, EQUALIZER_IFACE, equalizer_signals[EQUALIZER_SIGNAL_FILTER_CHANGED].name)));
2035 pa_dbus_protocol_send_signal(u->dbus_protocol, signal);
2036 dbus_message_unref(signal);
2037 }
2038
2039 void equalizer_handle_save_state(DBusConnection *conn, DBusMessage *msg, void *_u) {
2040 struct userdata *u = (struct userdata *) _u;
2041 pa_assert(conn);
2042 pa_assert(msg);
2043 pa_assert(u);
2044
2045 save_state(u);
2046 pa_dbus_send_empty_reply(conn, msg);
2047 }
2048
2049 void equalizer_handle_get_profile_name(DBusConnection *conn, DBusMessage *msg, void *_u){
2050 struct userdata *u = (struct userdata *) _u;
2051 DBusError error;
2052 uint32_t channel, r_channel;
2053
2054 pa_assert(conn);
2055 pa_assert(msg);
2056 pa_assert(u);
2057 dbus_error_init(&error);
2058
2059 if(!dbus_message_get_args(msg, &error,
2060 DBUS_TYPE_UINT32, &channel,
2061 DBUS_TYPE_INVALID)){
2062 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "%s", error.message);
2063 dbus_error_free(&error);
2064 return;
2065 }
2066 if(channel > u->channels){
2067 pa_dbus_send_error(conn, msg, DBUS_ERROR_INVALID_ARGS, "invalid channel: %d", channel);
2068 dbus_error_free(&error);
2069 return;
2070 }
2071 r_channel = channel == u->channels ? 0 : channel;
2072 pa_assert(u->base_profiles[r_channel]);
2073 pa_dbus_send_basic_value_reply(conn,msg, DBUS_TYPE_STRING, &u->base_profiles[r_channel]);
2074 }
2075
2076 void equalizer_get_revision(DBusConnection *conn, DBusMessage *msg, void *_u){
2077 uint32_t rev=1;
2078 pa_dbus_send_basic_value_reply(conn, msg, DBUS_TYPE_UINT32, &rev);
2079 }
2080
2081 void equalizer_get_n_channels(DBusConnection *conn, DBusMessage *msg, void *_u){
2082 struct userdata *u;
2083 uint32_t channels;
2084 pa_assert_se(u = (struct userdata *) _u);
2085 pa_assert(conn);
2086 pa_assert(msg);
2087
2088 channels = (uint32_t) u->channels;
2089 pa_dbus_send_basic_variant_reply(conn, msg, DBUS_TYPE_UINT32, &channels);
2090 }
2091
2092 void equalizer_get_n_coefs(DBusConnection *conn, DBusMessage *msg, void *_u){
2093 struct userdata *u;
2094 uint32_t n_coefs;
2095 pa_assert_se(u = (struct userdata *) _u);
2096 pa_assert(conn);
2097 pa_assert(msg);
2098
2099 n_coefs = (uint32_t) CHANNEL_PROFILE_SIZE;
2100 pa_dbus_send_basic_variant_reply(conn, msg, DBUS_TYPE_UINT32, &n_coefs);
2101 }
2102
2103 void equalizer_get_sample_rate(DBusConnection *conn, DBusMessage *msg, void *_u){
2104 struct userdata *u;
2105 uint32_t rate;
2106 pa_assert_se(u = (struct userdata *) _u);
2107 pa_assert(conn);
2108 pa_assert(msg);
2109
2110 rate = (uint32_t) u->sink->sample_spec.rate;
2111 pa_dbus_send_basic_variant_reply(conn, msg, DBUS_TYPE_UINT32, &rate);
2112 }
2113
2114 void equalizer_get_filter_rate(DBusConnection *conn, DBusMessage *msg, void *_u){
2115 struct userdata *u;
2116 uint32_t fft_size;
2117 pa_assert_se(u = (struct userdata *) _u);
2118 pa_assert(conn);
2119 pa_assert(msg);
2120
2121 fft_size = (uint32_t) u->fft_size;
2122 pa_dbus_send_basic_variant_reply(conn, msg, DBUS_TYPE_UINT32, &fft_size);
2123 }
2124
2125 void equalizer_get_all(DBusConnection *conn, DBusMessage *msg, void *_u){
2126 struct userdata *u;
2127 DBusMessage *reply = NULL;
2128 DBusMessageIter msg_iter, dict_iter;
2129 uint32_t rev, n_coefs, rate, fft_size, channels;
2130 pa_assert_se(u = (struct userdata *) _u);
2131 pa_assert(msg);
2132
2133 rev = 1;
2134 n_coefs = (uint32_t) CHANNEL_PROFILE_SIZE;
2135 rate = (uint32_t) u->sink->sample_spec.rate;
2136 fft_size = (uint32_t) u->fft_size;
2137 channels = (uint32_t) u->channels;
2138
2139 pa_assert_se((reply = dbus_message_new_method_return(msg)));
2140 dbus_message_iter_init_append(reply, &msg_iter);
2141 pa_assert_se(dbus_message_iter_open_container(&msg_iter, DBUS_TYPE_ARRAY, "{sv}", &dict_iter));
2142
2143 pa_dbus_append_basic_variant_dict_entry(&dict_iter, equalizer_handlers[EQUALIZER_HANDLER_REVISION].property_name, DBUS_TYPE_UINT32, &rev);
2144 pa_dbus_append_basic_variant_dict_entry(&dict_iter, equalizer_handlers[EQUALIZER_HANDLER_SAMPLERATE].property_name, DBUS_TYPE_UINT32, &rate);
2145 pa_dbus_append_basic_variant_dict_entry(&dict_iter, equalizer_handlers[EQUALIZER_HANDLER_FILTERSAMPLERATE].property_name, DBUS_TYPE_UINT32, &fft_size);
2146 pa_dbus_append_basic_variant_dict_entry(&dict_iter, equalizer_handlers[EQUALIZER_HANDLER_N_COEFS].property_name, DBUS_TYPE_UINT32, &n_coefs);
2147 pa_dbus_append_basic_variant_dict_entry(&dict_iter, equalizer_handlers[EQUALIZER_HANDLER_N_CHANNELS].property_name, DBUS_TYPE_UINT32, &channels);
2148
2149 pa_assert_se(dbus_message_iter_close_container(&msg_iter, &dict_iter));
2150 pa_assert_se(dbus_connection_send(conn, reply, NULL));
2151 dbus_message_unref(reply);
2152 }