-
Notifications
You must be signed in to change notification settings - Fork 2
/
fidlib.c
2300 lines (2010 loc) · 61.2 KB
/
fidlib.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Fidlib digital filter designer code
// -----------------------------------
//
// Copyright (c) 2002-2004 Jim Peters <http://uazu.net/>. This
// file is released under the GNU Lesser General Public License
// (LGPL) version 2.1 as published by the Free Software
// Foundation. See the file COPYING_LIB for details, or visit
// <http://www.fsf.org/licenses/licenses.html>.
//
// The code in this file was written to go with the Fiview app
// (http://uazu.net/fiview/), but it may be used as a library for
// other applications. The idea behind this library is to allow
// filters to be designed at run-time, which gives much greater
// flexibility to filtering applications.
//
// This file depends on the fidmkf.h file which provides the
// filter types from Tony Fisher's 'mkfilter' package. See that
// file for references and links used there.
//
//
// Here are some of the sources I used whilst writing this code:
//
// Robert Bristow-Johnson's EQ cookbook formulae:
// http://www.harmony-central.com/Computer/Programming/Audio-EQ-Cookbook.txt
//
#define VERSION "0.9.10"
//
// Filter specification string
// ---------------------------
//
// The filter specification string can be used to completely
// specify the filter, or it can be used with the frequency or
// frequency range missing, in which case default values are
// picked up from values passed directly to the routine.
//
// The spec consists of a series of letters usually followed by
// the order of the filter and then by any other parameters
// required, preceded by slashes. For example:
//
// LpBu4/20.4 Lowpass butterworth, 4th order, -3.01dB at 20.4Hz
// BpBu2/3-4 Bandpass butterworth, 2nd order, from 3 to 4Hz
// BpBu2/=3-4 Same filter, but adjusted exactly to the range given
// BsRe/1000/10 Bandstop resonator, Q=1000, frequency 10Hz
//
// The routines fid_design() or fid_parse() are used to convert
// this spec-string into filter coefficients and a description
// (if required).
//
//
// Typical usage:
// -------------
//
// FidFilter *filt, *filt2;
// char *desc;
// FidRun *run;
// FidFunc *funcp;
// void *fbuf1, *fbuf2;
// int delay;
// void my_error_func(char *err);
//
// // Design a filter, and optionally get its long description
// filt= fid_design(spec, rate, freq0, freq1, adj, &desc);
//
// // List all the possible filter types
// fid_list_filters(stdout);
// okay= fid_list_filters_buf(buf, buf+sizeof(buf));
//
// // Calculate the response of the filter at a given frequency
// // (frequency is given as a proportion of the sampling rate, in
// // the range 0 to 0.5). If phase is returned, then this is
// // given in the range 0 to 1 (for 0 to 2*pi).
// resp= fid_response(filt, freq);
// resp= fid_response_pha(filt, freq, &phase);
//
// // Estimate the signal delay caused by a particular filter, in samples
// delay= fid_calc_delay(filt);
//
// // Run a given filter (this will do JIT filter compilation if this is
// // implemented for this processor / OS)
// run= fid_run_new(filt, &funcp);
// fbuf1= fid_run_newbuf(run);
// fbuf2= fid_run_newbuf(run);
// while (...) {
// out_1= funcp(fbuf1, in_1);
// out_2= funcp(fbuf2, in_2);
// if (restart_required) fid_run_zapbuf(fbuf1);
// ...
// }
// fid_run_freebuf(fbuf2);
// fid_run_freebuf(fbuf1);
// fid_run_free(run);
//
// // If you need to allocate your own buffers separately for some
// // reason, then do it this way:
// run= fid_run_new(filt, &funcp);
// len= fid_run_bufsize(run);
// fbuf1= Alloc(len); fid_run_initbuf(run, fbuf1);
// fbuf2= Alloc(len); fid_run_initbuf(run, fbuf2);
// while (...) {
// out_1= funcp(fbuf1, in_1);
// out_2= funcp(fbuf2, in_2);
// if (restart_required) fid_run_zapbuf(fbuf1);
// ...
// }
// free(fbuf2);
// free(fbuf1);
// fid_run_free(run);
//
// // Convert an arbitrary filter into a new filter which is a single
// // IIR/FIR pair. This is done by convolving the coefficients. This
// // flattened filter will give the same result, in theory. However,
// // in practice this will be less accurate, especially in cases where
// // the limits of the floating point format are being reached (e.g.
// // subtracting numbers with small highly significant differences).
// // The routine also ensures that the IIR first coefficient is 1.0.
// filt2= fid_flatten(filt);
// free(filt);
//
// // Parse an entire filter-spec string possibly containing several FIR,
// // IIR and predefined filters and return it as a FidFilter at the given
// // location. Stops at the first ,; or unmatched )]} character, or the end
// // of the string. Returns a strdup'd error string on error, or else 0.
// err= fid_parse(double rate, char **pp, FidFilter **ffp);
//
// // Set up your own fatal-error handler (default is to dump a message
// // to STDERR and exit on fatal conditions)
// fid_set_error_handler(&my_error_func);
//
// // Get the version number of the library as a string (e.g. "1.0.0")
// txt= fid_version();
//
// // Design a filter and reduce it to a list of all the non-const
// // coefficients, which is returned in the given double[]. The number
// // of coefficients expected must be provided (as a check).
// #define N_COEF <whatever>
// double coef[N_COEF], gain;
// gain= fid_design_coef(coef, N_COEF, spec, rate, freq0, freq1, adj);
//
// // Rewrite a filter spec in a full and/or separated-out form
// char *full, *min;
// double minf0, minf1;
// int minadj;
// fid_rewrite_spec(spec, freq0, freq1, adj, &full, &min, &minf0, &minf1, &minadj);
// ...
// free(full); free(min);
//
// // Create a FidFilter based on coefficients provided in the
// // given double array.
// static double array[]= { 'I', 3, 1.0, 0.55, 0.77, 'F', 3, 1, -2, 1, 0 };
// filt= fid_cv_array(array);
//
// // Join a number of filters into a single filter (and free them too,
// // if the first argument is 1)
// filt= fid_cat(0, filt1, filt2, filt3, filt4, 0);
//
//
//
// Format of returned filter
// -------------------------
//
// The filter returned is a single chunk of allocated memory in
// which is stored a number of FidFilter instances. Each
// instance has variable length according to the coefficients
// contained in it. It is probably easier to think of this as a
// stream of items in memory. Each sub-filter starts with its
// type as a short -- either 'I' for IIR filters, or 'F' for FIR
// filters. (Other types may be added later, e.g. AM modulation
// elements, or whatever). This is followed by a short bitmap
// which indicates which of the coefficients are constants,
// aiding code-generation. Next comes the count of the following
// coefficients, as an int. (These header fields normally takes 8
// bytes, the same as a double, but this might depend on the
// platform). Then follow the coefficients, as doubles. The next
// sub-filter follows on straight after that. The end of the list
// is marked by 8 zero bytes, meaning typ==0, cbm==0 and len==0.
//
// The filter can be read with the aid of the FidFilter structure
// (giving typ, cbm, len and val[] elements) and the FFNEXT()
// macro: using ff= FFNEXT(ff) steps to the next FidFilter
// structure along the chain.
//
// Note that within the sub-filters, coefficients are listed in
// the order that they apply to data, from current-sample
// backwards in time, i.e. most recent first (so an FIR val[] of
// 0, 0, 1 represents a two-sample delay FIR filter). IIR
// filters are *not* necessarily adjusted so that their first
// coefficient is 1.
//
// Most filters have their gain pre-adjusted so that some
// suitable part of the response is at gain==1.0. However, this
// depends on the filter type.
//
//
// Check that a target macro has been set. This macro selects
// various fixes required on various platforms:
//
// T_LINUX Linux, or probably any UNIX-like platform with GCC
// T_MINGW MinGW -- either building on Win32 or cross-compiling
// T_MSVC Microsoft Visual C
//
// (On MSVC, add "T_MSVC" to the preprocessor definitions in the
// project settings, or add /D "T_MSVC" to the compiler
// command-line.)
//
#define T_LINUX
//
// Select which method of filter execution is preferred.
// RF_CMDLIST is recommended (and is the default).
//
// RF_COMBINED -- easy to understand code, lower accuracy
// RF_CMDLIST -- faster pre-compiled code
// RF_JIT -- fastest JIT run-time generated code (no longer supported)
//
#ifndef RF_COMBINED
#ifndef RF_CMDLIST
#ifndef RF_JIT
#define RF_CMDLIST
#endif
#endif
#endif
//
// Includes
//
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "fidlib.h"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
extern FidFilter *mkfilter(char *, ...);
//
// Target-specific fixes
//
// Macro for local inline routines that shouldn't be visible externally
#ifdef T_MSVC
#define STATIC_INLINE static __inline
#else
#define STATIC_INLINE static inline
#endif
// MinGW and MSVC fixes
#if defined(T_MINGW) || defined(T_MSVC)
#ifndef vsnprintf
#define vsnprintf _vsnprintf
#endif
#ifndef snprintf
#define snprintf _snprintf
#endif
// Not sure if we strictly need this still
STATIC_INLINE double
my_asinh(double val) {
return log(val + sqrt(val*val + 1.0));
}
#define asinh(xx) my_asinh(xx)
#endif
//
// Support code
//
static void (*error_handler)(char *err)= 0;
static void
error(char *fmt, ...) {
char buf[1024];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap); // Ignore overflow
buf[sizeof(buf)-1]= 0;
if (error_handler) error_handler(buf);
// If error handler routine returns, we dump to STDERR and exit anyway
fprintf(stderr, "fidlib error: %s\n", buf);
exit(1);
}
static char *
strdupf(char *fmt, ...) {
va_list ap;
char buf[1024], *rv;
int len;
va_start(ap, fmt);
len= vsnprintf(buf, sizeof(buf), fmt, ap);
if (len < 0 || len >= sizeof(buf)-1)
error("strdupf exceeded buffer");
rv= strdup(buf);
if (!rv) error("Out of memory");
return rv;
}
static void *
Alloc(int size) {
void *vp= calloc(1, size);
if (!vp) error("Out of memory");
return vp;
}
#define ALLOC(type) ((type*)Alloc(sizeof(type)))
#define ALLOC_ARR(cnt, type) ((type*)Alloc((cnt) * sizeof(type)))
//
// Complex multiply: aa *= bb;
//
STATIC_INLINE void
cmul(double *aa, double *bb) {
double rr= aa[0] * bb[0] - aa[1] * bb[1];
double ii= aa[0] * bb[1] + aa[1] * bb[0];
aa[0]= rr;
aa[1]= ii;
}
//
// Complex square: aa *= aa;
//
STATIC_INLINE void
csqu(double *aa) {
double rr= aa[0] * aa[0] - aa[1] * aa[1];
double ii= 2 * aa[0] * aa[1];
aa[0]= rr;
aa[1]= ii;
}
//
// Complex multiply by real: aa *= bb;
//
STATIC_INLINE void
cmulr(double *aa, double fact) {
aa[0] *= fact;
aa[1] *= fact;
}
//
// Complex conjugate: aa= aa*
//
STATIC_INLINE void
cconj(double *aa) {
aa[1]= -aa[1];
}
//
// Complex divide: aa /= bb;
//
STATIC_INLINE void
cdiv(double *aa, double *bb) {
double rr= aa[0] * bb[0] + aa[1] * bb[1];
double ii= -aa[0] * bb[1] + aa[1] * bb[0];
double fact= 1.0 / (bb[0] * bb[0] + bb[1] * bb[1]);
aa[0]= rr * fact;
aa[1]= ii * fact;
}
//
// Complex reciprocal: aa= 1/aa
//
STATIC_INLINE void
crecip(double *aa) {
double fact= 1.0 / (aa[0] * aa[0] + aa[1] * aa[1]);
aa[0] *= fact;
aa[1] *= -fact;
}
//
// Complex assign: aa= bb
//
STATIC_INLINE void
cass(double *aa, double *bb) {
memcpy(aa, bb, 2*sizeof(double)); // Assigning doubles is really slow
}
//
// Complex assign: aa= (rr + ii*j)
//
STATIC_INLINE void
cassz(double *aa, double rr, double ii) {
aa[0]= rr;
aa[1]= ii;
}
//
// Complex add: aa += bb
//
STATIC_INLINE void
cadd(double *aa, double *bb) {
aa[0] += bb[0];
aa[1] += bb[1];
}
//
// Complex add: aa += (rr + ii*j)
//
STATIC_INLINE void
caddz(double *aa, double rr, double ii) {
aa[0] += rr;
aa[1] += ii;
}
//
// Complex subtract: aa -= bb
//
STATIC_INLINE void
csub(double *aa, double *bb) {
aa[0] -= bb[0];
aa[1] -= bb[1];
}
//
// Complex subtract: aa -= (rr + ii*j)
//
STATIC_INLINE void
csubz(double *aa, double rr, double ii) {
aa[0] -= rr;
aa[1] -= ii;
}
//
// Complex negate: aa= -aa
//
STATIC_INLINE void
cneg(double *aa) {
aa[0]= -aa[0];
aa[1]= -aa[1];
}
//
// Evaluate a complex polynomial given the coefficients.
// rv[0]+i*rv[1] is the result, in[0]+i*in[1] is the input value.
// Coefficients are real values.
//
STATIC_INLINE void
evaluate(double *rv, double *coef, int n_coef, double *in) {
double pz[2]; // Powers of Z
// Handle first iteration by hand
rv[0]= *coef++;
rv[1]= 0;
if (--n_coef > 0) {
// Handle second iteration by hand
pz[0]= in[0];
pz[1]= in[1];
rv[0] += *coef * pz[0];
rv[1] += *coef * pz[1];
coef++; n_coef--;
// Loop for remainder
while (n_coef > 0) {
cmul(pz, in);
rv[0] += *coef * pz[0];
rv[1] += *coef * pz[1];
coef++;
n_coef--;
}
}
}
//
// Housekeeping
//
void
fid_set_error_handler(void (*rout)(char*)) {
error_handler= rout;
}
char *
fid_version() {
return VERSION;
}
//
// Get the response and phase of a filter at the given frequency
// (expressed as a proportion of the sampling rate, 0->0.5).
// Phase is returned as a number from 0 to 1, representing a
// phase between 0 and two-pi.
//
double
fid_response_pha(FidFilter *filt, double freq, double *phase) {
double top[2], bot[2];
double theta= freq * 2 * M_PI;
double zz[2];
top[0]= 1;
top[1]= 0;
bot[0]= 1;
bot[1]= 0;
zz[0]= cos(theta);
zz[1]= sin(theta);
while (filt->len) {
double resp[2];
int cnt= filt->len;
evaluate(resp, filt->val, cnt, zz);
if (filt->typ == 'I')
cmul(bot, resp);
else if (filt->typ == 'F')
cmul(top, resp);
else
error("Unknown filter type %d in fid_response_pha()", filt->typ);
filt= FFNEXT(filt);
}
cdiv(top, bot);
if (phase) {
double pha= atan2(top[1], top[0]) / (2 * M_PI);
if (pha < 0) pha += 1.0;
*phase= pha;
}
return hypot(top[1], top[0]);
}
//
// Get the response of a filter at the given frequency (expressed
// as a proportion of the sampling rate, 0->0.5).
//
// Code duplicate, as I didn't want the overhead of a function
// call to fid_response_pha. Almost every call in this routine
// can be inlined.
//
double
fid_response(FidFilter *filt, double freq) {
double top[2], bot[2];
double theta= freq * 2 * M_PI;
double zz[2];
top[0]= 1;
top[1]= 0;
bot[0]= 1;
bot[1]= 0;
zz[0]= cos(theta);
zz[1]= sin(theta);
while (filt->len) {
double resp[2];
int cnt= filt->len;
evaluate(resp, filt->val, cnt, zz);
if (filt->typ == 'I')
cmul(bot, resp);
else if (filt->typ == 'F')
cmul(top, resp);
else
error("Unknown filter type %d in fid_response()", filt->typ);
filt= FFNEXT(filt);
}
cdiv(top, bot);
return hypot(top[1], top[0]);
}
//
// Estimate the delay that a filter causes to the signal by
// looking for the point at which 50% of the filter calculations
// are complete. This involves running test impulses through the
// filter several times. The estimated delay in samples is
// returned.
//
// Delays longer than 8,000,000 samples are not handled well, as
// the code drops out at this point rather than get stuck in an
// endless loop.
//
int
fid_calc_delay(FidFilter *filt) {
FidRun *run;
FidFunc *dostep;
void *f1, *f2;
double tot, tot100, tot50;
int cnt;
run= fid_run_new(filt, &dostep);
// Run through to find at least the 99.9% point of filter; the r2
// (tot100) filter runs at 4x the speed of the other one to act as
// a reference point much further ahead in the impulse response.
f1= fid_run_newbuf(run);
f2= fid_run_newbuf(run);
tot= fabs(dostep(f1, 1.0));
tot100= fabs(dostep(f2, 1.0));
tot100 += fabs(dostep(f2, 0.0));
tot100 += fabs(dostep(f2, 0.0));
tot100 += fabs(dostep(f2, 0.0));
for (cnt= 1; cnt < 0x1000000; cnt++) {
tot += fabs(dostep(f1, 0.0));
tot100 += fabs(dostep(f2, 0.0));
tot100 += fabs(dostep(f2, 0.0));
tot100 += fabs(dostep(f2, 0.0));
tot100 += fabs(dostep(f2, 0.0));
if (tot/tot100 >= 0.999) break;
}
fid_run_freebuf(f1);
fid_run_freebuf(f2);
// Now find the 50% point
tot50= tot100/2;
f1= fid_run_newbuf(run);
tot= fabs(dostep(f1, 1.0));
for (cnt= 0; tot < tot50; cnt++)
tot += fabs(dostep(f1, 0.0));
fid_run_freebuf(f1);
// Clean up, return
fid_run_free(run);
return cnt;
}
//
// 'mkfilter'-derived code
//
#include "fidmkf.h"
//
// Stack a number of identical filters, generating the required
// FidFilter* return value
//
static FidFilter*
stack_filter(int order, int n_head, int n_val, ...) {
FidFilter *rv= FFALLOC(n_head * order, n_val * order);
FidFilter *p, *q;
va_list ap;
int a, b, len;
if (order == 0) return rv;
// Copy from ap
va_start(ap, n_val);
p= q= rv;
for (a= 0; a<n_head; a++) {
p->typ= va_arg(ap, int);
p->cbm= va_arg(ap, int);
p->len= va_arg(ap, int);
for (b= 0; b<p->len; b++)
p->val[b]= va_arg(ap, double);
p= FFNEXT(p);
}
order--;
// Check length
len= ((char*)p)-((char*)q);
if (len != FFCSIZE(n_head-1, n_val))
error("Internal error; bad call to stack_filter(); length mismatch (%d,%d)",
len, FFCSIZE(n_head-1, n_val));
// Make as many additional copies as necessary
while (order-- > 0) {
memcpy(p, q, len);
p= (void*)(len + (char*)p);
}
// List is already terminated due to zeroed allocation
return rv;
}
//
// Search for a peak between two given frequencies. It is
// assumed that the gradient goes upwards from 'f0' to the peak,
// and then down again to 'f3'. If there are any other curves,
// this routine will get confused and will come up with some
// frequency, although probably not the right one.
//
// Returns the frequency of the peak.
//
static double
search_peak(FidFilter *ff, double f0, double f3) {
double f1, f2;
double r1, r2;
int a;
// Binary search, modified, taking two intermediate points. Do 20
// subdivisions, which should give 1/2^20 == 1e-6 accuracy compared
// to original range.
for (a= 0; a<20; a++) {
f1= 0.51 * f0 + 0.49 * f3;
f2= 0.49 * f0 + 0.51 * f3;
if (f1 == f2) break; // We're hitting FP limit
r1= fid_response(ff, f1);
r2= fid_response(ff, f2);
if (r1 > r2) // Peak is either to the left, or between f1/f2
f3= f2;
else // Peak is either to the right, or between f1/f2
f0= f1;
}
return (f0+f3)*0.5;
}
//
// Handle the different 'back-ends' for Bessel, Butterworth and
// Chebyshev filters. First argument selects between bilinear
// (0) and matched-Z (non-0). The BL and MZ macros makes this a
// bit more obvious in the code.
//
// Overall filter gain is adjusted to give the peak at 1.0. This
// is easy for all types except for band-pass, where a search is
// required to find the precise peak. This is much slower than
// the other types.
//
#define BL 0
#define MZ 1
static FidFilter*
do_lowpass(int mz, double freq) {
FidFilter *rv;
lowpass(prewarp(freq));
if (mz) s2z_matchedZ(); else s2z_bilinear();
rv= z2fidfilter(1.0, ~0); // FIR is constant
rv->val[0]= 1.0 / fid_response(rv, 0.0);
return rv;
}
static FidFilter*
do_highpass(int mz, double freq) {
FidFilter *rv;
highpass(prewarp(freq));
if (mz) s2z_matchedZ(); else s2z_bilinear();
rv= z2fidfilter(1.0, ~0); // FIR is constant
rv->val[0]= 1.0 / fid_response(rv, 0.5);
return rv;
}
static FidFilter*
do_bandpass(int mz, double f0, double f1) {
FidFilter *rv;
bandpass(prewarp(f0), prewarp(f1));
if (mz) s2z_matchedZ(); else s2z_bilinear();
rv= z2fidfilter(1.0, ~0); // FIR is constant
rv->val[0]= 1.0 / fid_response(rv, search_peak(rv, f0, f1));
return rv;
}
static FidFilter*
do_bandstop(int mz, double f0, double f1) {
FidFilter *rv;
bandstop(prewarp(f0), prewarp(f1));
if (mz) s2z_matchedZ(); else s2z_bilinear();
rv= z2fidfilter(1.0, 5); // FIR second coefficient is *non-const* for bandstop
rv->val[0]= 1.0 / fid_response(rv, 0.0); // Use 0Hz response as reference
return rv;
}
//
// Information passed to individual filter design routines:
//
// double* rout(double rate, double f0, double f1,
// int order, int n_arg, double *arg);
//
// 'rate' is the sampling rate, or 1 if not set
// 'f0' and 'f1' give the frequency or frequency range as a
// proportion of the sampling rate
// 'order' is the order of the filter (the integer passed immediately
// after the name)
// 'n_arg' is the number of additional arguments for the filter
// 'arg' gives the additional argument values: arg[n]
//
// Note that #O #o #F and #R are mapped to the f0/f1/order
// arguments, and are not included in the arg[] array.
//
// See the previous description for the required meaning of the
// return value FidFilter list.
//
//
// Filter design routines and supporting code
//
static FidFilter*
des_bpre(double rate, double f0, double f1, int order, int n_arg, double *arg) {
bandpass_res(f0, arg[0]);
return z2fidfilter(1.0, ~0); // FIR constant
}
static FidFilter*
des_bsre(double rate, double f0, double f1, int order, int n_arg, double *arg) {
bandstop_res(f0, arg[0]);
return z2fidfilter(1.0, 0); // FIR not constant, depends on freq
}
static FidFilter*
des_apre(double rate, double f0, double f1, int order, int n_arg, double *arg) {
allpass_res(f0, arg[0]);
return z2fidfilter(1.0, 0); // FIR not constant, depends on freq
}
static FidFilter*
des_pi(double rate, double f0, double f1, int order, int n_arg, double *arg) {
prop_integral(prewarp(f0));
s2z_bilinear();
return z2fidfilter(1.0, 0); // FIR not constant, depends on freq
}
static FidFilter*
des_piz(double rate, double f0, double f1, int order, int n_arg, double *arg) {
prop_integral(prewarp(f0));
s2z_matchedZ();
return z2fidfilter(1.0, 0); // FIR not constant, depends on freq
}
static FidFilter*
des_lpbe(double rate, double f0, double f1, int order, int n_arg, double *arg) {
bessel(order);
return do_lowpass(BL, f0);
}
static FidFilter*
des_hpbe(double rate, double f0, double f1, int order, int n_arg, double *arg) {
bessel(order);
return do_highpass(BL, f0);
}
static FidFilter*
des_bpbe(double rate, double f0, double f1, int order, int n_arg, double *arg) {
bessel(order);
return do_bandpass(BL, f0, f1);
}
static FidFilter*
des_bsbe(double rate, double f0, double f1, int order, int n_arg, double *arg) {
bessel(order);
return do_bandstop(BL, f0, f1);
}
static FidFilter*
des_lpbez(double rate, double f0, double f1, int order, int n_arg, double *arg) {
bessel(order);
return do_lowpass(MZ, f0);
}
static FidFilter*
des_hpbez(double rate, double f0, double f1, int order, int n_arg, double *arg) {
bessel(order);
return do_highpass(MZ, f0);
}
static FidFilter*
des_bpbez(double rate, double f0, double f1, int order, int n_arg, double *arg) {
bessel(order);
return do_bandpass(MZ, f0, f1);
}
static FidFilter*
des_bsbez(double rate, double f0, double f1, int order, int n_arg, double *arg) {
bessel(order);
return do_bandstop(MZ, f0, f1);
}
static FidFilter* // Butterworth-Bessel cross
des_lpbube(double rate, double f0, double f1, int order, int n_arg, double *arg) {
double tmp[MAXPZ];
int a;
bessel(order); memcpy(tmp, pol, order * sizeof(double));
butterworth(order);
for (a= 0; a<order; a++) pol[a] += (tmp[a]-pol[a]) * 0.01 * arg[0];
//for (a= 1; a<order; a+=2) pol[a] += arg[1] * 0.01;
return do_lowpass(BL, f0);
}
static FidFilter*
des_lpbu(double rate, double f0, double f1, int order, int n_arg, double *arg) {
butterworth(order);
return do_lowpass(BL, f0);
}
static FidFilter*
des_hpbu(double rate, double f0, double f1, int order, int n_arg, double *arg) {
butterworth(order);
return do_highpass(BL, f0);
}
static FidFilter*
des_bpbu(double rate, double f0, double f1, int order, int n_arg, double *arg) {
butterworth(order);
return do_bandpass(BL, f0, f1);
}
static FidFilter*
des_bsbu(double rate, double f0, double f1, int order, int n_arg, double *arg) {
butterworth(order);
return do_bandstop(BL, f0, f1);
}
static FidFilter*
des_lpbuz(double rate, double f0, double f1, int order, int n_arg, double *arg) {
butterworth(order);
return do_lowpass(MZ, f0);
}
static FidFilter*
des_hpbuz(double rate, double f0, double f1, int order, int n_arg, double *arg) {
butterworth(order);
return do_highpass(MZ, f0);
}
static FidFilter*
des_bpbuz(double rate, double f0, double f1, int order, int n_arg, double *arg) {
butterworth(order);
return do_bandpass(MZ, f0, f1);
}
static FidFilter*
des_bsbuz(double rate, double f0, double f1, int order, int n_arg, double *arg) {
butterworth(order);
return do_bandstop(MZ, f0, f1);
}
static FidFilter*
des_lpch(double rate, double f0, double f1, int order, int n_arg, double *arg) {
chebyshev(order, arg[0]);
return do_lowpass(BL, f0);
}
static FidFilter*
des_hpch(double rate, double f0, double f1, int order, int n_arg, double *arg) {
chebyshev(order, arg[0]);
return do_highpass(BL, f0);
}
static FidFilter*
des_bpch(double rate, double f0, double f1, int order, int n_arg, double *arg) {
chebyshev(order, arg[0]);
return do_bandpass(BL, f0, f1);
}
static FidFilter*
des_bsch(double rate, double f0, double f1, int order, int n_arg, double *arg) {
chebyshev(order, arg[0]);
return do_bandstop(BL, f0, f1);
}
static FidFilter*
des_lpchz(double rate, double f0, double f1, int order, int n_arg, double *arg) {
chebyshev(order, arg[0]);
return do_lowpass(MZ, f0);
}
static FidFilter*
des_hpchz(double rate, double f0, double f1, int order, int n_arg, double *arg) {
chebyshev(order, arg[0]);
return do_highpass(MZ, f0);
}
static FidFilter*
des_bpchz(double rate, double f0, double f1, int order, int n_arg, double *arg) {
chebyshev(order, arg[0]);
return do_bandpass(MZ, f0, f1);
}
static FidFilter*