-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsnd_dsp_v2.c
5415 lines (4325 loc) · 142 KB
/
snd_dsp_v2.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
/*
s_dsp.c - digital signal processing algorithms for audio FX
Copyright (C) 2009 Uncle Mike
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*/
#include "quakedef.h"
#define SIGN( d ) (( d ) < 0 ? -1 : 1 )
#define ABS( a ) abs( a )
#define MSEC_TO_SAMPS( a ) ((( a ) * shm->speed) / 1000 ) // convert milliseconds to # samples in equivalent time
#define SEC_TO_SAMPS( a ) (( a ) * shm->speed) // conver seconds to # samples in equivalent time
#define CLIP_DSP( x ) ( x )
#define SOUND_MS_PER_FT 1 // sound travels approx 1 foot per millisecond
#define ROOM_MAX_SIZE 1000 // max size in feet of room simulation for dsp
// Performance notes:
// DSP processing should take no more than 3ms total time per frame to remain on par with hl1
// Assume a min frame rate of 24fps = 42ms per frame
// at 24fps, to maintain 44.1khz output rate, we must process about 1840 mono samples per frame.
// So we must process 1840 samples in 3ms.
// on a 1Ghz CPU (mid-low end CPU) 3ms provides roughly 3,000,000 cycles.
// Thus we have 3e6 / 1840 = 1630 cycles per sample.
#define PBITS 12 // parameter bits
#define PMAX ((1 << PBITS)-1) // parameter max size
// crossfade from y2 to y1 at point r (0 < r < PMAX )
#define XFADE( y1, y2, r ) (((y1) * (r)) >> PBITS) + (((y2) * (PMAX - (r))) >> PBITS);
#define XFADEF( y1, y2, r ) (((y1) * (r)) / (float)(PMAX)) + (((y2) * (PMAX - (r))) / (float)(PMAX));
/////////////////////
// dsp helpers
/////////////////////
// dot two integer vectors of length M+1
// M is filter order, h is filter vector, w is filter state vector
int dot ( int M, int *h, int *w )
{
int i, y;
for( y = 0, i = 0; i <= M; i++ )
y += ( h[i] * w[i] ) >> PBITS;
return y;
}
// delay array w[] by D samples
// w[0] = input, w[D] = output
// practical for filters, but not for large values of D
void delay( int D, int *w )
{
int i;
for( i = D; i >= 1; i-- ) // reverse order updating
w[i] = w[i-1];
}
// circular wrap of pointer p, relative to array w
// D delay line size in samples w[0...D]
// w delay line buffer pointer, dimension D+1
// p circular pointer
void wrap( int D, int *w, int **p )
{
if( *p > w + D ) *p -= D + 1; // when *p = w + D + 1, it wraps around to *p = w
if( *p < w ) *p += D + 1; // when *p = w - 1, it wraps around to *p = w + D
}
// simple averaging filter for performance - a[] is 0, b[] is 1, L is # of samples to average
int avg_filter( int M, int *a, int L, int *b, int *w, int x )
{
int i, y = 0;
w[0] = x;
// output adder
switch( L )
{
default:
case 12: y += w[12];
case 11: y += w[11];
case 10: y += w[10];
case 9: y += w[9];
case 8: y += w[8];
case 7: y += w[7];
case 6: y += w[6];
case 5: y += w[5];
case 4: y += w[4];
case 3: y += w[3];
case 2: y += w[2];
case 1: y += w[1];
case 0: y += w[0];
}
for( i = L; i >= 1; i-- ) // reverse update internal state
w[i] = w[i-1];
switch( L )
{
default:
case 12: return y / 13;
case 11: return y / 12;
case 10: return y / 11;
case 9: return y / 10;
case 8: return y / 9;
case 7: return y >> 3;
case 6: return y / 7;
case 5: return y / 6;
case 4: return y / 5;
case 3: return y >> 2;
case 2: return y / 3;
case 1: return y >> 1;
case 0: return y;
}
return y; // current output sample
}
// IIR filter, cannonical form
// returns single sample y for current input value x
// x is input sample
// w = internal state vector, dimension max(M,L) + 1
// L, M numerator and denominator filter orders
// a,b are M+1 dimensional arrays of filter params
//
// for M = 4:
//
// 1 w0(n) b0
// x(n)--->(+)--(*)-----.------(*)->(+)---> y(n)
// ^ | ^
// | [Delay d] |
// | | |
// | -a1 |W1 b1 |
// ----(*)---.------(*)----
// ^ | ^
// | [Delay d] |
// | | |
// | -a2 |W2 b2 |
// ----(*)---.------(*)----
// ^ | ^
// | [Delay d] |
// | | |
// | -a3 |W3 b3 |
// ----(*)---.------(*)----
// ^ | ^
// | [Delay d] |
// | | |
// | -a4 |W4 b4 |
// ----(*)---.------(*)----
//
// for each input sample x, do:
// w0 = x - a1*w1 - a2*w2 - ... aMwM
// y = b0*w0 + b1*w1 + ...bL*wL
// wi = wi-1, i = K, K-1, ..., 1
int iir_filter( int M, int *a, int L, int *b, int *w, int x )
{
int K, i, y, x0;
if( M == 0 )
return avg_filter( M, a, L, b, w, x );
y = 0;
x0 = x;
K = fmax ( M, L );
// for (i = 1; i <= M; i++) // input adder
// w[0] -= ( a[i] * w[i] ) >> PBITS;
// M is clamped between 1 and FLT_M
// change this switch statement if FLT_M changes!
switch( M )
{
case 12: x0 -= ( a[12] * w[12] ) >> PBITS;
case 11: x0 -= ( a[11] * w[11] ) >> PBITS;
case 10: x0 -= ( a[10] * w[10] ) >> PBITS;
case 9: x0 -= ( a[9] * w[9] ) >> PBITS;
case 8: x0 -= ( a[8] * w[8] ) >> PBITS;
case 7: x0 -= ( a[7] * w[7] ) >> PBITS;
case 6: x0 -= ( a[6] * w[6] ) >> PBITS;
case 5: x0 -= ( a[5] * w[5] ) >> PBITS;
case 4: x0 -= ( a[4] * w[4] ) >> PBITS;
case 3: x0 -= ( a[3] * w[3] ) >> PBITS;
case 2: x0 -= ( a[2] * w[2] ) >> PBITS;
default:
case 1: x0 -= ( a[1] * w[1] ) >> PBITS;
}
w[0] = x0;
// for( i = 0; i <= L; i++ ) // output adder
// y += ( b[i] * w[i] ) >> PBITS;
switch( L )
{
case 12: y += ( b[12] * w[12] ) >> PBITS;
case 11: y += ( b[11] * w[11] ) >> PBITS;
case 10: y += ( b[10] * w[10] ) >> PBITS;
case 9: y += ( b[9] * w[9] ) >> PBITS;
case 8: y += ( b[8] * w[8] ) >> PBITS;
case 7: y += ( b[7] * w[7] ) >> PBITS;
case 6: y += ( b[6] * w[6] ) >> PBITS;
case 5: y += ( b[5] * w[5] ) >> PBITS;
case 4: y += ( b[4] * w[4] ) >> PBITS;
case 3: y += ( b[3] * w[3] ) >> PBITS;
case 2: y += ( b[2] * w[2] ) >> PBITS;
default:
case 1: y += ( b[1] * w[1] ) >> PBITS;
case 0: y += ( b[0] * w[0] ) >> PBITS;
}
for( i = K; i >= 1; i-- ) // reverse update internal state
w[i] = w[i-1];
return y; // current output sample
}
// IIR filter, cannonical form, using dot product and delay implementation
// (may be easier to optimize this routine.)
int iir_filter2( int M, int *a, int L, int *b, int *w, int x )
{
int K, y;
K = fmax( M, L ); // K = max (M, L)
w[0] = 0; // needed for dot (M, a, w)
w[0] = x - dot( M, a, w ); // input adder
y = dot( L, b, w ); // output adder
delay( K, w ); // update delay line
return y; // current output sample
}
// fir filter - no feedback = high stability but also may be more expensive computationally
int fir_filter( int M, int *h, int *w, int x )
{
int i, y;
w[0] = x;
for( y = 0, i = 0; i <= M; i++ )
y += h[i] * w[i];
for( i = M; i >= -1; i-- )
w[i] = w[i-1];
return y;
}
// fir filter, using dot product and delay implementation
int fir_filter2( int M, int *h, int *w, int x )
{
int y;
w[0] = x;
y = dot( M, h, w );
delay( M, w );
return y;
}
// tap - i-th tap of circular delay line buffer
// D delay line size in samples
// w delay line buffer pointer, of dimension D+1
// p circular pointer
// t = 0...D
int tap( int D, int *w, int *p, int t )
{
return w[(p - w + t) % (D + 1)];
}
// tapi - interpolated tap output of a delay line
// interpolates sample between adjacent samples in delay line for 'frac' part of delay
// D delay line size in samples
// w delay line buffer pointer, of dimension D+1
// p circular pointer
// t - delay tap integer value 0...D. (complete delay is t.frac )
// frac - varying 16 bit fractional delay value 0...32767 (normalized to 0.0 - 1.0)
int tapi( int D, int *w, int *p, int t, int frac )
{
int i, j;
int si, sj;
i = t; // tap value, interpolate between adjacent samples si and sj
j = (i + 1) % (D+1); // if i = D, then j = 0; otherwise, j = i + 1
si = tap( D, w, p, i ); // si(n) = x(n - i)
sj = tap( D, w, p, j ); // sj(n) = x(n - j)
return si + (((frac) * (sj - si) ) >> 16);
}
// circular delay line, D-fold delay
// D delay line size in samples w[0..D]
// w delay line buffer pointer, dimension D+1
// p circular pointer
void cdelay( int D, int *w, int **p )
{
(*p)--; // decrement pointer and wrap modulo (D+1)
wrap ( D, w, p ); // when *p = w-1, it wraps around to *p = w+D
}
// plain reverberator with circular delay line
// D delay line size in samples
// t tap from this location - <= D
// w delay line buffer pointer of dimension D+1
// p circular pointer, must be init to &w[0] before first call
// a feedback value, 0-PMAX (normalized to 0.0-1.0)
// b gain
// x input sample
// w0(n) b
// x(n)--->(+)--------.-----(*)-> y(n)
// ^ |
// | [Delay d]
// | |
// | a |Wd(n)
// ----(*)---.
int dly_plain( int D, int t, int *w, int **p, int a, int b, int x )
{
int y, sD;
sD = tap( D, w, *p, t ); // Tth tap delay output
y = x + (( a * sD ) >> PBITS); // filter output
**p = y; // delay input
cdelay( D, w, p ); // update delay line
return (( y * b ) >> PBITS );
}
// straight delay line
//
// D delay line size in samples
// t tap from this location - <= D
// w delay line buffer pointer of dimension D+1
// p circular pointer, must be init to &w[0] before first call
// x input sample
//
// x(n)--->[Delay d]---> y(n)
//
int dly_linear ( int D, int t, int *w, int **p, int x )
{
int y;
y = tap( D, w, *p, t ); // Tth tap delay output
**p = x; // delay input
cdelay( D, w, p ); // update delay line
return y;
}
// lowpass reverberator, replace feedback multiplier 'a' in
// plain reverberator with a low pass filter
// D delay line size in samples
// t tap from this location - <= D
// w delay line buffer pointer of dimension D+1
// p circular pointer, must be init to &w[0] before first call
// a feedback gain
// b output gain
// M filter order
// bf filter numerator, 0-PMAX (normalized to 0.0-1.0), M+1 dimensional
// af filter denominator, 0-PMAX (normalized to 0.0-1.0), M+1 dimensional
// vf filter state, M+1 dimensional
// x input sample
// w0(n) b
// x(n)--->(+)--------------.----(*)--> y(n)
// ^ |
// | [Delay d]
// | |
// | a |Wd(n)
// --(*)--[Filter])-
int dly_lowpass( int D, int t, int *w, int **p, int a, int b, int M, int *af, int L, int *bf, int *vf, int x )
{
int y, sD;
sD = tap( D, w, *p, t ); // delay output is filter input
y = x + ((iir_filter ( M, af, L, bf, vf, sD ) * a) >> PBITS); // filter output with gain
**p = y; // delay input
cdelay( D, w, p ); // update delay line
return (( y * b ) >> PBITS ); // output with gain
}
// allpass reverberator with circular delay line
// D delay line size in samples
// t tap from this location - <= D
// w delay line buffer pointer of dimension D+1
// p circular pointer, must be init to &w[0] before first call
// a feedback value, 0-PMAX (normalized to 0.0-1.0)
// b gain
// w0(n) -a b
// x(n)--->(+)--------.-----(*)-->(+)--(*)-> y(n)
// ^ | ^
// | [Delay d] |
// | | |
// | a |Wd(n) |
// ----(*)---.-------------
//
// for each input sample x, do:
// w0 = x + a*Wd
// y = -a*w0 + Wd
// delay (d, W) - w is the delay buffer array
//
// or, using circular delay, for each input sample x do:
//
// Sd = tap (D,w,p,D)
// S0 = x + a*Sd
// y = -a*S0 + Sd
// *p = S0
// cdelay(D, w, &p)
int dly_allpass( int D, int t, int *w, int **p, int a, int b, int x )
{
int y, s0, sD;
sD = tap( D, w, *p, t ); // Dth tap delay output
s0 = x + (( a * sD ) >> PBITS);
y = (( -a * s0 ) >> PBITS ) + sD; // filter output
**p = s0; // delay input
cdelay( D, w, p ); // update delay line
return (( y * b ) >> PBITS );
}
///////////////////////////////////////////////////////////////////////////////////
// fixed point math for real-time wave table traversing, pitch shifting, resampling
///////////////////////////////////////////////////////////////////////////////////
#define FIX20_BITS 20 // 20 bits of fractional part
#define FIX20_SCALE (1 << FIX20_BITS)
#define FIX20_INTMAX ((1 << (32 - FIX20_BITS))-1) // maximum step integer
#define FLOAT_TO_FIX20(a) ((int)((a) * (float)FIX20_SCALE)) // convert float to fixed point
#define INT_TO_FIX20(a) (((int)(a)) << FIX20_BITS) // convert int to fixed point
#define FIX20_TO_FLOAT(a) ((float)(a) / (float)FIX20_SCALE) // convert fix20 to float
#define FIX20_INTPART(a) (((int)(a)) >> FIX20_BITS) // get integer part of fixed point
#define FIX20_FRACPART(a) ((a) - (((a) >> FIX20_BITS) << FIX20_BITS)) // get fractional part of fixed point
#define FIX20_FRACTION(a,b) (FIX(a)/(b)) // convert int a to fixed point, divide by b
typedef int fix20int;
/////////////////////////////////
// DSP processor parameter block
/////////////////////////////////
// NOTE: these prototypes must match the XXX_Params ( prc_t *pprc ) and XXX_GetNext ( XXX_t *p, int x ) functions
typedef void * (*prc_Param_t)( void *pprc ); // individual processor allocation functions
typedef int (*prc_GetNext_t)( void *pdata, int x ); // get next function for processor
typedef int (*prc_GetNextN_t)( void *pdata, portable_samplepair_t *pbuffer, int SampleCount, int op); // batch version of getnext
typedef void (*prc_Free_t)( void *pdata ); // free function for processor
typedef void (*prc_Mod_t)(void *pdata, float v); // modulation function for processor
#define OP_LEFT 0 // batch process left channel in place
#define OP_RIGHT 1 // batch process right channel in place
#define OP_LEFT_DUPLICATE 2 // batch process left channel in place, duplicate to right channel
#define PRC_NULL 0 // pass through - must be 0
#define PRC_DLY 1 // simple feedback reverb
#define PRC_RVA 2 // parallel reverbs
#define PRC_FLT 3 // lowpass or highpass filter
#define PRC_CRS 4 // chorus
#define PRC_PTC 5 // pitch shifter
#define PRC_ENV 6 // adsr envelope
#define PRC_LFO 7 // lfo
#define PRC_EFO 8 // envelope follower
#define PRC_MDY 9 // mod delay
#define PRC_DFR 10 // diffusor - n series allpass delays
#define PRC_AMP 11 // amplifier with distortion
#define QUA_LO 0 // quality of filter or reverb. Must be 0,1,2,3.
#define QUA_MED 1
#define QUA_HI 2
#define QUA_VHI 3
#define QUA_MAX QUA_VHI
#define CPRCPARAMS 16 // up to 16 floating point params for each processor type
// processor definition - one for each running instance of a dsp processor
typedef struct
{
int type; // PRC type
float prm[CPRCPARAMS]; // dsp processor parameters - array of floats
prc_Param_t pfnParam; // allocation function - takes ptr to prc, returns ptr to specialized data struct for proc type
prc_GetNext_t pfnGetNext; // get next function
prc_GetNextN_t pfnGetNextN; // batch version of get next
prc_Free_t pfnFree; // free function
prc_Mod_t pfnMod; // modulation function
void *pdata; // processor state data - ie: pdly, pflt etc.
} prc_t;
// processor parameter ranges - for validating parameters during allocation of new processor
typedef struct prm_rng_s
{
int iprm; // parameter index
float lo; // min value of parameter
float hi; // max value of parameter
} prm_rng_t;
void PRC_CheckParams( prc_t *pprc, prm_rng_t *prng );
///////////
// Filters
///////////
#define CFLTS 64 // max number of filters simultaneously active
#define FLT_M 12 // max order of any filter
#define FLT_LP 0 // lowpass filter
#define FLT_HP 1 // highpass filter
#define FTR_MAX FLT_HP
// flt parameters
typedef struct
{
qboolean fused; // true if slot in use
int b[FLT_M+1]; // filter numerator parameters (convert 0.0-1.0 to 0-PMAX representation)
int a[FLT_M+1]; // filter denominator parameters (convert 0.0-1.0 to 0-PMAX representation)
int w[FLT_M+1]; // filter state - samples (dimension of max (M, L))
int L; // filter order numerator (dimension of a[M+1])
int M; // filter order denominator (dimension of b[L+1])
} flt_t;
// flt flts
flt_t flts[CFLTS];
void FLT_Init( flt_t *pf ) { if( pf ) Q_memset( pf, 0, sizeof( flt_t )); }
void FLT_InitAll( void ) { int i; for( i = 0; i < CFLTS; i++ ) FLT_Init( &flts[i] ); }
void FLT_Free( flt_t *pf ) { if( pf ) Q_memset( pf, 0, sizeof( flt_t )); }
void FLT_FreeAll( void ) { int i; for( i = 0; i < CFLTS; i++ ) FLT_Free( &flts[i] ); }
// find a free filter from the filter pool
// initialize filter numerator, denominator b[0..M], a[0..L]
flt_t * FLT_Alloc( int M, int L, int *a, int *b )
{
int i, j;
flt_t *pf = NULL;
for( i = 0; i < CFLTS; i++ )
{
if( !flts[i].fused )
{
pf = &flts[i];
// transfer filter params into filter struct
pf->M = M;
pf->L = L;
for( j = 0; j <= M; j++ )
pf->a[j] = a[j];
for( j = 0; j <= L; j++ )
pf->b[j] = b[j];
pf->fused = true;
break;
}
}
return pf;
}
// convert filter params cutoff and type into
// iir transfer function params M, L, a[], b[]
// iir filter, 1st order, transfer function is H(z) = b0 + b1 Z^-1 / a0 + a1 Z^-1
// or H(z) = b0 - b1 Z^-1 / a0 + a1 Z^-1 for lowpass
// design cutoff filter at 3db (.5 gain) p579
void FLT_Design_3db_IIR( float cutoff, float ftype, int *pM, int *pL, int *a, int *b )
{
// ftype: FLT_LP, FLT_HP, FLT_BP
double Wc = 2.0 * M_PI * cutoff / shm->speed; // radians per sample
double Oc;
double fa;
double fb;
// calculations:
// Wc = 2pi * fc/44100 convert to radians
// Oc = tan (Wc/2) * Gc / sqt ( 1 - Gc^2) get analog version, low pass
// Oc = tan (Wc/2) * (sqt (1 - Gc^2)) / Gc analog version, high pass
// Gc = 10 ^ (-Ac/20) gain at cutoff. Ac = 3db, so Gc^2 = 0.5
// a = ( 1 - Oc ) / ( 1 + Oc )
// b = ( 1 - a ) / 2
Oc = tan( Wc / 2.0 );
fa = ( 1.0 - Oc ) / ( 1.0 + Oc );
fb = ( 1.0 - fa ) / 2.0;
if( ftype == FLT_HP )
fb = ( 1.0 + fa ) / 2.0;
a[0] = 0; // a0 always ignored
a[1] = (int)( -fa * PMAX ); // quantize params down to 0-PMAX >> PBITS
b[0] = (int)( fb * PMAX );
b[1] = b[0];
if( ftype == FLT_HP )
b[1] = -b[1];
*pM = *pL = 1;
}
// convolution of x[n] with h[n], resulting in y[n]
// h, x, y filter, input and output arrays (double precision)
// M = filter order, L = input length
// h is M+1 dimensional
// x is L dimensional
// y is L+M dimensional
void conv( int M, double *h, int L, double *x, double *y )
{
int n, m;
for( n = 0; n < L+M; n++ )
{
for( y[n] = 0, m = fmax(0, n-L+1); m <= fmin(n, M); m++ )
{
y[n] += h[m] * x[n-m];
}
}
}
// cas2can - convert cascaded, second order section parameter arrays to
// canonical numerator/denominator arrays. Canonical implementations
// have half as many multiplies as cascaded implementations.
// K is number of cascaded sections
// A is Kx3 matrix of sos params A[K] = A[0]..A[K-1]
// a is (2K + 1) -dimensional output of canonical params
#define KMAX 32 // max # of sos sections - 8 is the most we should ever see at runtime
void cas2can( int K, double A[KMAX+1][3], int *aout )
{
int i, j;
double d[2*KMAX + 1];
double a[2*KMAX + 1];
Q_memset( d, 0, sizeof( double ) * ( 2 * KMAX + 1 ));
Q_memset( a, 0, sizeof( double ) * ( 2 * KMAX + 1 ));
a[0] = 1;
for( i = 0; i < K; i++ )
{
conv( 2, A[i], 2 * i + 1, a, d );
for( j = 0; j < 2 * i + 3; j++ )
a[j] = d[j];
}
for( i = 0; i < (2*K + 1); i++ )
aout[i] = a[i] * PMAX;
}
// chebyshev IIR design, type 2, Lowpass or Highpass
#define lnf( e ) ( 2.303 * log10( e ))
#define acosh( e ) ( lnf( (e) + sqrt(( e ) * ( e ) - 1) ))
#define asinh( e ) ( lnf( (e) + sqrt(( e ) * ( e ) + 1) ))
// returns a[], b[] which are Kx3 matrices of cascaded second-order sections
// these matrices may be passed directly to the iir_cas() routine for evaluation
// Nmax - maximum order of filter
// cutoff, ftype, qwidth - filter cutoff in hz, filter type FLT_LOWPASS/HIGHPASS, qwidth in hz
// pM - denominator order
// pL - numerator order
// a - array of canonical filter params
// b - array of canonical filter params
void FLT_Design_Cheb( int Nmax, float cutoff, float ftype, float qwidth, int *pM, int *pL, int *a, int *b )
{
// p769 - converted from MATLAB
double s = (ftype == FLT_LP ? 1 : -1 ); // 1 for LP, -1 for HP
double fs = shm->speed; // sampling frequency
double fpass = cutoff; // cutoff frequency
double fstop = fpass + fmax (2000, qwidth); // stop frequency
double Apass = 0.5; // max attenuation of pass band UNDONE: use Quality to select this
double Astop = 10; // max amplitude of stop band UNDONE: use Quality to select this
double Wpass, Wstop, epass, estop, Nex, aa;
double W3, f3, W0, G, Wi2, W02, a1, a2, th, Wi, D, b1;
int i, K, r, N;
double A[KMAX+1][3]; // denominator output matrices, second order sections
double B[KMAX+1][3]; // numerator output matrices, second order sections
Wpass = tan( M_PI * fpass / fs );
Wpass = pow( Wpass, s );
Wstop = tan( M_PI * fstop / fs );
Wstop = pow( Wstop, s );
epass = sqrt( pow( (float)10.0f, (float)Apass/10.0f ) - 1 );
estop = sqrt( pow( (float)10.0f, (float)Astop/10.0f ) - 1 );
// calculate filter order N
Nex = acosh( estop/epass ) / acosh ( Wstop/Wpass );
N = fmin ( ceil(Nex), Nmax ); // don't exceed Nmax for filter order
r = ( (int)N & 1); // r == 1 if N is odd
K = (N - r ) / 2;
aa = asinh ( estop ) / N;
W3 = Wstop / cosh( acosh( estop ) / N );
f3 = (fs / M_PI) * atan( pow( W3, s ));
W0 = sinh( aa ) / Wstop;
W02 = W0 * W0;
// 1st order section for N odd
if( r == 1 )
{
G = 1 / (1 + W0);
A[0][0] = 1; A[0][1] = s * (2*G-1); A[0][2] = 0;
B[0][0] = G; B[0][1] = G * s; B[0][2] = 0;
}
else
{
A[0][0] = 1; A[0][1] = 0; A[0][2] = 0;
B[0][0] = 1; B[0][1] = 0; B[0][2] = 0;
}
for( i = 1; i <= K ; i++ )
{
th = M_PI * (N - 1 + 2 * i) / (2 * N);
Wi = sin( th ) / Wstop;
Wi2 = Wi * Wi;
D = 1 - 2 * W0 * cos( th ) + W02 + Wi2;
G = ( 1 + Wi2 ) / D;
b1 = 2 * ( 1 - Wi2 ) / ( 1 + Wi2 );
a1 = 2 * ( 1 - W02 - Wi2) / D;
a2 = ( 1 + 2 * W0 * cos( th ) + W02 + Wi2) / D;
A[i][0] = 1;
A[i][1] = s * a1;
A[i][2] = a2;
B[i][0] = G;
B[i][1] = G* s* b1;
B[i][2] = G;
}
// convert cascade parameters to canonical parameters
cas2can( K, A, a );
*pM = 2*K + 1;
cas2can( K, B, b );
*pL = 2*K + 1;
}
// filter parameter order
typedef enum
{
flt_iftype,
flt_icutoff,
flt_iqwidth,
flt_iquality,
flt_cparam // # of params
} flt_e;
// filter parameter ranges
prm_rng_t flt_rng[] =
{
{ flt_cparam, 0, 0 }, // first entry is # of parameters
{ flt_iftype, 0, FTR_MAX }, // filter type FLT_LP, FLT_HP, FLT_BP (UNDONE: FLT_BP currently ignored)
{ flt_icutoff, 10, 22050 }, // cutoff frequency in hz at -3db gain
{ flt_iqwidth, 100, 11025 }, // width of BP, or steepness of LP/HP (ie: fcutoff + qwidth = -60db gain point)
{ flt_iquality, 0, QUA_MAX }, // QUA_LO, _MED, _HI 0,1,2,3
};
// convert prc float params to iir filter params, alloc filter and return ptr to it
// filter quality set by prc quality - 0,1,2
flt_t * FLT_Params ( prc_t *pprc )
{
float qual = pprc->prm[flt_iquality];
float cutoff = pprc->prm[flt_icutoff];
float ftype = pprc->prm[flt_iftype];
float qwidth = pprc->prm[flt_iqwidth];
int L = 0; // numerator order
int M = 0; // denominator order
int b[FLT_M+1]; // numerator params 0..PMAX
int a[FLT_M+1]; // denominator params 0..PMAX
// low pass and highpass filter design
if( (int)qual == QUA_LO )
qual = QUA_MED; // disable lowest quality filter - check perf on lowend KDB
switch ( (int)qual )
{
case QUA_LO:
// lowpass averaging filter: perf KDB
M = 0;
// L is # of samples to average
L = 0;
if( cutoff <= shm->speed / 4 ) L = 1; // 11k
if( cutoff <= shm->speed / 8 ) L = 2; // 5.5k
if( cutoff <= shm->speed / 16 ) L = 4; // 2.75k
if( cutoff <= shm->speed / 32 ) L = 8; // 1.35k
if( cutoff <= shm->speed / 64 ) L = 12; // 750hz
break;
case QUA_MED:
// 1st order IIR filter, 3db cutoff at fc
FLT_Design_3db_IIR( cutoff, ftype, &M, &L, a, b );
M = bound( 1, M, FLT_M );
L = bound( 1, L, FLT_M );
break;
case QUA_HI:
// type 2 chebyshev N = 4 IIR
FLT_Design_Cheb( 4, cutoff, ftype, qwidth, &M, &L, a, b );
M = bound( 1, M, FLT_M );
L = bound( 1, L, FLT_M );
break;
case QUA_VHI:
// type 2 chebyshev N = 7 IIR
FLT_Design_Cheb( 8, cutoff, ftype, qwidth, &M, &L, a, b );
M = bound( 1, M, FLT_M );
L = bound( 1, L, FLT_M );
break;
}
return FLT_Alloc( M, L, a, b );
}
void * FLT_VParams( void *p )
{
PRC_CheckParams(( prc_t *)p, flt_rng );
return (void *)FLT_Params ((prc_t *)p);
}
void FLT_Mod( void *p, float v )
{
}
// get next filter value for filter pf and input x
int FLT_GetNext( flt_t *pf, int x )
{
return iir_filter( pf->M, pf->a, pf->L, pf->b, pf->w, x );
}
// batch version for performance
void FLT_GetNextN( flt_t *pflt, portable_samplepair_t *pbuffer, int SampleCount, int op )
{
int count = SampleCount;
portable_samplepair_t *pb = pbuffer;
switch( op )
{
default:
case OP_LEFT:
while( count-- )
{
pb->left = FLT_GetNext( pflt, pb->left );
pb++;
}
break;
case OP_RIGHT:
while( count-- )
{
pb->right = FLT_GetNext( pflt, pb->right );
pb++;
}
break;
case OP_LEFT_DUPLICATE:
while( count-- )
{
pb->left = pb->right = FLT_GetNext( pflt, pb->left );
pb++;
}
break;
}
}
///////////////////////////////////////////////////////////////////////////
// Positional updaters for pitch shift etc
///////////////////////////////////////////////////////////////////////////
// looping position within a wav, with integer and fractional parts
// used for pitch shifting, upsampling/downsampling
// 20 bits of fraction, 8+ bits of integer
typedef struct
{
fix20int step; // wave table whole and fractional step value
fix20int cstep; // current cummulative step value
int pos; // current position within wav table
int D; // max dimension of array w[0...D] ie: # of samples = D+1
} pos_t;
// circular wrap of pointer p, relative to array w
// D max buffer index w[0...D] (count of samples in buffer is D+1)
// i circular index
void POS_Wrap( int D, int *i )
{
if( *i > D ) *i -= D + 1; // when *pi = D + 1, it wraps around to *pi = 0
if( *i < 0 ) *i += D + 1; // when *pi = - 1, it wraps around to *pi = D
}
// set initial update value - fstep can have no more than 8 bits of integer and 20 bits of fract
// D is array max dimension w[0...D] (ie: size D+1)
// w is ptr to array
// p is ptr to pos_t to initialize
void POS_Init( pos_t *p, int D, float fstep )
{
float step = fstep;
// make sure int part of step is capped at fix20_intmax
if( (int)step > FIX20_INTMAX )
step = (step - (int)step) + FIX20_INTMAX;
p->step = FLOAT_TO_FIX20( step ); // convert fstep to fixed point
p->cstep = 0;
p->pos = 0; // current update value
p->D = D; // always init to end value, in case we're stepping backwards
}
// change step value - this is an instantaneous change, not smoothed.
void POS_ChangeVal( pos_t *p, float fstepnew )
{
p->step = FLOAT_TO_FIX20( fstepnew ); // convert fstep to fixed point
}
// return current integer position, then update internal position value
int POS_GetNext ( pos_t *p )
{
// float f = FIX20_TO_FLOAT( p->cstep );
// int i1 = FIX20_INTPART( p->cstep );
// float f1 = FIX20_TO_FLOAT( FIX20_FRACPART( p->cstep ));
// float f2 = FIX20_TO_FLOAT( p->step );
p->cstep += p->step; // update accumulated fraction step value (fixed point)
p->pos += FIX20_INTPART( p->cstep ); // update pos with integer part of accumulated step
p->cstep = FIX20_FRACPART( p->cstep ); // throw away the integer part of accumulated step
// wrap pos around either end of buffer if needed
POS_Wrap( p->D, &( p->pos ));
return p->pos;
}
// oneshot position within wav
typedef struct
{
pos_t p; // pos_t
qboolean fhitend; // flag indicating we hit end of oneshot wav
} pos_one_t;
// set initial update value - fstep can have no more than 8 bits of integer and 20 bits of fract
// one shot position - play only once, don't wrap, when hit end of buffer, return last position
void POS_ONE_Init( pos_one_t *p1, int D, float fstep )
{
POS_Init( &p1->p, D, fstep ) ;
p1->fhitend = false;
}
// return current integer position, then update internal position value