1 /* Effect module for UADE2 frontends.
2 
3    Copyright 2005 (C) Antti S. Lankila <alankila@bel.fi>
4 
5    This module is licensed under the GNU LGPL.
6 */
7 
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <assert.h>
11 #include <string.h>
12 #include <math.h>
13 
14 #include <compilersupport.h>
15 
16 #include "effects.h"
17 
18 /*** old headphone effect ***/
19 #define UADE_EFFECT_HEADPHONES_DELAY_LENGTH 22
20 #define UADE_EFFECT_HEADPHONES_DELAY_DIRECT 0.3
21 #define UADE_EFFECT_HEADPHONES_CROSSMIX_VOL 0.80
22 
23 static float headphones_ap_l[UADE_EFFECT_HEADPHONES_DELAY_LENGTH];
24 static float headphones_ap_r[UADE_EFFECT_HEADPHONES_DELAY_LENGTH];
25 static float headphones_rc_l[4];
26 static float headphones_rc_r[4];
27 
28 /*** new headphone effect ***/
29 
30 /* delay time defines the width of the head. 0.5 ms gives us 15 cm virtual distance
31  * between sound arriving to either ear. */
32 #define HEADPHONE2_DELAY_TIME 0.49e-3
33 #define HEADPHONE2_DELAY_K 0.15
34 /* head shadow frequency cutoff */
35 #define HEADPHONE2_SHADOW_FREQ 8000.0
36 /* high shelve keeps frequencies below cutoff intact and attenuates
37  * the rest in an uniform way. The effect is to make bass more "mono" than "stereo". */
38 #define HEADPHONE2_SHELVE_FREQ 100.0
39 #define HEADPHONE2_SHELVE_LEVEL -2.0
40 
41 #define MAXIMUM_SAMPLING_RATE 96000
42 #define HEADPHONE2_DELAY_MAX_LENGTH ((int)(MAXIMUM_SAMPLING_RATE*HEADPHONE2_DELAY_TIME+1))
43 #define DENORMAL_OFFSET 1E-10
44 
45 #define NORMALISE_RESOLUTION 10	/* in bits */
46 #define NORMALISE_DEFAULT_GAIN 8.0
47 #define NORMALISE_MAXIMUM_GAIN 8.0
48 
49 /* Headphone variables */
50 typedef struct {
51 	float b0, b1, b2, a1, a2, x[2], y[2];
52 } biquad_t;
53 
54 static float headphone2_ap_l[HEADPHONE2_DELAY_MAX_LENGTH];
55 static float headphone2_ap_r[HEADPHONE2_DELAY_MAX_LENGTH];
56 static int headphone2_delay_length;
57 static biquad_t headphone2_shelve_l;
58 static biquad_t headphone2_shelve_r;
59 static biquad_t headphone2_rc_l;
60 static biquad_t headphone2_rc_r;
61 
62 /* Normalise variables */
63 static int normalise_peak_level;
64 static int normalise_historic_maximum_peak;
65 static int normalise_oldlevel;
66 
67 static void gain(int gain_amount, int16_t * sm, int frames);
68 static void pan(int pan_amount, int16_t * sm, int frames);
69 static void headphones(int16_t * sm, int frames);
70 static void headphones2(int16_t * sm, int frames);
71 static void normalise(int change_level, int16_t * sm, int frames);
72 static int normalise_compute_gain(int peak);
73 
sampleclip(int x)74 static inline int sampleclip(int x)
75 {
76 	if (unlikely(x > 32767 || x < -32768)) {
77 		if (x > 32767)
78 			x = 32767;
79 		else
80 			x = -32768;
81 	}
82 	return x;
83 }
84 
85 /* calculate a high shelve filter */
calculate_shelve(double fs,double fc,double g,biquad_t * bq)86 static void calculate_shelve(double fs, double fc, double g, biquad_t * bq)
87 {
88 	float A, omega, sn, cs, beta, b0, b1, b2, a0, a1, a2;
89 
90 	A = powf(10, g / 40);
91 	omega = 2 * M_PI * fc / fs;
92 	omega = tan(omega / 2) * 2;
93 	sn = sin(omega);
94 	cs = cos(omega);
95 	beta = sqrt(A + A);
96 
97 	b0 = A * ((A + 1) + (A - 1) * cs + beta * sn);
98 	b1 = -2 * A * ((A - 1) + (A + 1) * cs);
99 	b2 = A * ((A + 1) + (A - 1) * cs - beta * sn);
100 	a0 = (A + 1) - (A - 1) * cs + beta * sn;
101 	a1 = 2 * ((A - 1) - (A + 1) * cs);
102 	a2 = (A + 1) - (A - 1) * cs - beta * sn;
103 
104 	bq->b0 = b0 / a0;
105 	bq->b1 = b1 / a0;
106 	bq->b2 = b2 / a0;
107 	bq->a1 = a1 / a0;
108 	bq->a2 = a2 / a0;
109 }
110 
111 /* calculate 1st order lowpass filter */
calculate_rc(double fs,double fc,biquad_t * bq)112 static void calculate_rc(double fs, double fc, biquad_t * bq)
113 {
114 	float omega;
115 
116 	if (fc >= fs / 2) {
117 		bq->b0 = 1.0;
118 		bq->b1 = 0.0;
119 		bq->b2 = 0.0;
120 		bq->a1 = 0.0;
121 		bq->a2 = 0.0;
122 		return;
123 	}
124 	omega = 2 * M_PI * fc / fs;
125 	omega = tan(omega / 2) * 2;
126 
127 	bq->b0 = 1 / (1 + 1 / omega);
128 	bq->b1 = 0;
129 	bq->b2 = 0;
130 	bq->a1 = -1 + bq->b0;
131 	bq->a2 = 0;
132 }
133 
evaluate_biquad(float input,biquad_t * bq)134 static inline float evaluate_biquad(float input, biquad_t * bq)
135 {
136 	float output = DENORMAL_OFFSET;
137 
138 	output += input * bq->b0 + bq->x[0] * bq->b1 + bq->x[1] * bq->b2;
139 	output -= bq->y[0] * bq->a1 + bq->y[1] * bq->a2;
140 
141 	bq->x[1] = bq->x[0];
142 	bq->x[0] = input;
143 
144 	bq->y[1] = bq->y[0];
145 	bq->y[0] = output;
146 
147 	return output;
148 }
149 
reset_biquad(biquad_t * bq)150 static void reset_biquad(biquad_t * bq)
151 {
152 	bq->x[0] = bq->x[1] = bq->y[0] = bq->y[1] = 0;
153 }
154 
155 /* Reset effects' state variables.
156  * Call this method between before starting playback */
uade_effect_reset_internals(void)157 void uade_effect_reset_internals(void)
158 {
159 	/* old headphones */
160 	memset(headphones_ap_l, 0, sizeof(headphones_ap_l));
161 	memset(headphones_ap_r, 0, sizeof(headphones_ap_r));
162 	memset(headphones_rc_l, 0, sizeof(headphones_rc_l));
163 	memset(headphones_rc_r, 0, sizeof(headphones_rc_r));
164 
165 	/* new headphones */
166 	memset(headphone2_ap_l, 0, sizeof(headphone2_ap_l));
167 	memset(headphone2_ap_r, 0, sizeof(headphone2_ap_r));
168 	reset_biquad(&headphone2_shelve_l);
169 	reset_biquad(&headphone2_shelve_r);
170 	reset_biquad(&headphone2_rc_l);
171 	reset_biquad(&headphone2_rc_r);
172 
173 	normalise_peak_level = 0;
174 	normalise_historic_maximum_peak = 0;
175 	normalise_oldlevel = 1 << NORMALISE_RESOLUTION;
176 }
177 
uade_effect_disable_all(struct uade_effect * ue)178 void uade_effect_disable_all(struct uade_effect *ue)
179 {
180 	ue->enabled = 0;
181 }
182 
uade_effect_disable(struct uade_effect * ue,uade_effect_t effect)183 void uade_effect_disable(struct uade_effect *ue, uade_effect_t effect)
184 {
185 	ue->enabled &= ~(1 << effect);
186 }
187 
uade_effect_enable(struct uade_effect * ue,uade_effect_t effect)188 void uade_effect_enable(struct uade_effect *ue, uade_effect_t effect)
189 {
190 	ue->enabled |= 1 << effect;
191 }
192 
193 /* Returns 1 if effect is enabled, and zero otherwise. Ignores
194    UADE_EFFECT_ALLOW. */
uade_effect_is_enabled(struct uade_effect * ue,uade_effect_t effect)195 int uade_effect_is_enabled(struct uade_effect *ue, uade_effect_t effect)
196 {
197 	return (ue->enabled & (1 << effect)) != 0;
198 }
199 
uade_effect_run(struct uade_effect * ue,int16_t * samples,int frames)200 void uade_effect_run(struct uade_effect *ue, int16_t * samples, int frames)
201 {
202 	if (ue->enabled & (1 << UADE_EFFECT_ALLOW)) {
203 		normalise(ue->enabled & (1 << UADE_EFFECT_NORMALISE), samples,
204 			  frames);
205 		if (ue->enabled & (1 << UADE_EFFECT_PAN))
206 			pan(ue->pan, samples, frames);
207 		if (ue->enabled & (1 << UADE_EFFECT_HEADPHONES))
208 			headphones(samples, frames);
209 		if (ue->enabled & (1 << UADE_EFFECT_HEADPHONES2) && ue->rate)
210 			headphones2(samples, frames);
211 		if (ue->enabled & (1 << UADE_EFFECT_GAIN))
212 			gain(ue->gain, samples, frames);
213 	}
214 }
215 
uade_effect_toggle(struct uade_effect * ue,uade_effect_t effect)216 void uade_effect_toggle(struct uade_effect *ue, uade_effect_t effect)
217 {
218 	ue->enabled ^= 1 << effect;
219 }
220 
uade_effect_set_defaults(struct uade_effect * ue)221 void uade_effect_set_defaults(struct uade_effect *ue)
222 {
223 	memset(ue, 0, sizeof(*ue));
224 	uade_effect_disable_all(ue);
225 	uade_effect_enable(ue, UADE_EFFECT_ALLOW);
226 	uade_effect_gain_set_amount(ue, 1.0);
227 	uade_effect_pan_set_amount(ue, 0.7);
228 }
229 
230 /* Rate of 0 means undefined. Effects that depend on sample rate must
231    self-check against this because they can not implemented properly */
uade_effect_set_sample_rate(struct uade_effect * ue,int rate)232 void uade_effect_set_sample_rate(struct uade_effect *ue, int rate)
233 {
234 	assert(rate >= 0);
235 	ue->rate = rate;
236 
237 	if (rate == 0)
238 		return;
239 
240 	calculate_shelve(rate, HEADPHONE2_SHELVE_FREQ, HEADPHONE2_SHELVE_LEVEL,
241 			 &headphone2_shelve_l);
242 	calculate_shelve(rate, HEADPHONE2_SHELVE_FREQ, HEADPHONE2_SHELVE_LEVEL,
243 			 &headphone2_shelve_r);
244 	calculate_rc(rate, HEADPHONE2_SHADOW_FREQ, &headphone2_rc_l);
245 	calculate_rc(rate, HEADPHONE2_SHADOW_FREQ, &headphone2_rc_r);
246 	headphone2_delay_length = HEADPHONE2_DELAY_TIME * rate + 0.5;
247 	if (headphone2_delay_length > HEADPHONE2_DELAY_MAX_LENGTH) {
248 		fprintf(stderr,	"effects.c: truncating headphone delay line due to samplerate exceeding 96 kHz.\n");
249 		headphone2_delay_length = HEADPHONE2_DELAY_MAX_LENGTH;
250 	}
251 }
252 
uade_effect_gain_set_amount(struct uade_effect * ue,float amount)253 void uade_effect_gain_set_amount(struct uade_effect *ue, float amount)
254 {
255 	assert(amount >= 0.0 && amount <= 128.0);
256 	ue->gain = amount * 256.0;
257 }
258 
uade_effect_pan_set_amount(struct uade_effect * ue,float amount)259 void uade_effect_pan_set_amount(struct uade_effect *ue, float amount)
260 {
261 	assert(amount >= 0.0 && amount <= 2.0);
262 	ue->pan = amount * 256.0 / 2.0;
263 }
264 
normalise_compute_gain(int peak)265 static int normalise_compute_gain(int peak)
266 {
267 	if (normalise_historic_maximum_peak == 0) {
268 		/* if the peak is not known, we cap gain in an attempt to avoid
269 		 * boosting silent intros too much. */
270 		if (peak < 32768 / NORMALISE_DEFAULT_GAIN)
271 			return NORMALISE_DEFAULT_GAIN *
272 			    (1 << NORMALISE_RESOLUTION);
273 		else
274 			return (32768 << NORMALISE_RESOLUTION) / peak;
275 	} else {
276 		int largerpeak;
277 		if (peak < normalise_historic_maximum_peak)
278 			largerpeak = normalise_historic_maximum_peak;
279 		else
280 			largerpeak = peak;
281 		/* if the peak is known, we use the recorded value but adapt
282 		   if this rendition comes out louder for some reason (for
283 		   instance, updated UADE) */
284 		if (largerpeak < 32768 / NORMALISE_MAXIMUM_GAIN)
285 			return NORMALISE_MAXIMUM_GAIN *
286 			    (1 << NORMALISE_RESOLUTION);
287 		else
288 			return (32768 << NORMALISE_RESOLUTION) / largerpeak;
289 	}
290 }
291 
292 /* We save gain from maximum known level. This is an one-way street,
293    the gain can * only decrease with time. If the historic level is
294    known and larger, we prefer it. */
uade_effect_normalise_serialise(char * buf,size_t len)295 void uade_effect_normalise_serialise(char *buf, size_t len)
296 {
297 	int peak = normalise_peak_level;
298 
299 	assert(len > 0);
300 
301 	if (normalise_historic_maximum_peak > normalise_peak_level)
302 		peak = normalise_historic_maximum_peak;
303 
304 	if (snprintf(buf, len, "v=1,p=%d", peak) >= len) {
305 		fprintf(stderr,	"normalise effect: buffer too short, gain would be truncated. This is a bug in UADE.\n");
306 		exit(-1);
307 	}
308 }
309 
310 /* similarly, this should only be called if gain has a positive value,
311  * but we try to recover from misuse. */
uade_effect_normalise_unserialise(const char * buf)312 void uade_effect_normalise_unserialise(const char *buf)
313 {
314 	int version, readcount;
315 	float peak;
316 
317 	normalise_historic_maximum_peak = 0;
318 
319 	if (buf == NULL)
320 		return;
321 
322 	readcount = sscanf(buf, "v=%d,p=%f", &version, &peak);
323 
324 	if (readcount == 0) {
325 		fprintf(stderr, "normalise effect: gain string invalid: '%s'\n", buf);
326 		exit(-1);
327 	}
328 
329 	if (version != 1) {
330 		fprintf(stderr,	"normalise effect: unrecognized gain version: '%s'\n", buf);
331 		exit(-1);
332 	}
333 
334 	if (readcount != 2) {
335 		fprintf(stderr,	"Could not read peak value for version 1: '%s'\n", buf);
336 		exit(-1);
337 	}
338 
339 	if (peak >= 0.0 && peak <= 1.0) {
340 		normalise_oldlevel = normalise_historic_maximum_peak =
341 		    32768 * peak;
342 	} else {
343 		fprintf(stderr, "normalise effect: invalid peak level: '%s'\n", buf);
344 	}
345 }
346 
normalise(int change_level,int16_t * sm,int frames)347 static void normalise(int change_level, int16_t * sm, int frames)
348 {
349 	int i;
350 
351 	/* Negative side is mirrored. but positive side gains by 1.
352 	 * This is to make both semiwaves have same max. */
353 	for (i = 0; i < 2 * frames; i += 1) {
354 		int tmp = sm[i];
355 		tmp = (tmp >= 0) ? tmp + 1 : -tmp;
356 		if (tmp > normalise_peak_level)
357 			normalise_peak_level = tmp;
358 	}
359 
360 	/* Slight clipping may result in first playback while the system
361 	 * adjusts.  With a bit of "advance warning" of clipping about to
362 	 * occur, the level begins to adjust as soon as the buffer
363 	 * begins. Typical adjustment times are not large -- a few hundred
364 	 * samples are to be expected -- and the clipping should only
365 	 * occur on the first rendition of the song, if at all. */
366 	if (change_level) {
367 		int newlevel = normalise_compute_gain(normalise_peak_level);
368 
369 		for (i = 0; i < 2 * frames; i += 1) {
370 			/* same gain for the frame */
371 			if ((i & 1) == 0) {
372 				if (normalise_oldlevel < newlevel)
373 					normalise_oldlevel += 1;
374 				if (normalise_oldlevel > newlevel)
375 					normalise_oldlevel -= 1;
376 			}
377 			sm[i] =
378 			    sampleclip((sm[i] *
379 					normalise_oldlevel) >>
380 				       NORMALISE_RESOLUTION);
381 		}
382 	}
383 }
384 
gain(int gain_amount,int16_t * sm,int frames)385 static void gain(int gain_amount, int16_t * sm, int frames)
386 {
387 	int i;
388 	for (i = 0; i < 2 * frames; i += 1)
389 		sm[i] = sampleclip((sm[i] * gain_amount) >> 8);
390 }
391 
392 /* Panning effect. Turns stereo into mono in a specific degree */
pan(int pan_amount,int16_t * sm,int frames)393 static void pan(int pan_amount, int16_t * sm, int frames)
394 {
395 	int i, l, r, m;
396 	for (i = 0; i < frames; i += 1) {
397 		l = sm[0];
398 		r = sm[1];
399 		m = (r - l) * pan_amount;
400 		sm[0] = ((l << 8) + m) >> 8;
401 		sm[1] = ((r << 8) - m) >> 8;
402 		sm += 2;
403 	}
404 }
405 
406 /* All-pass delay. Its purpose is to confuse the phase of the sound a bit
407  * and also provide some delay to locate the source outside the head. This
408  * seems to work better than a pure delay line. */
headphones_allpass_delay(float in,float * state)409 static float headphones_allpass_delay(float in, float *state)
410 {
411 	int i;
412 	float tmp, output;
413 
414 	tmp = in - UADE_EFFECT_HEADPHONES_DELAY_DIRECT * state[0];
415 	output = state[0] + UADE_EFFECT_HEADPHONES_DELAY_DIRECT * tmp;
416 
417 	/* FIXME: use modulo and index */
418 	for (i = 1; i < UADE_EFFECT_HEADPHONES_DELAY_LENGTH; i += 1)
419 		state[i - 1] = state[i];
420 	state[UADE_EFFECT_HEADPHONES_DELAY_LENGTH - 1] = tmp;
421 
422 	return output;
423 }
424 
headphones_lpf(float in,float * state)425 static float headphones_lpf(float in, float *state)
426 {
427 	float out = in * 0.53;
428 	out += 0.47 * state[0];
429 	state[0] = out;
430 
431 	return out;
432 }
433 
434 /* A real implementation would simply perform FIR with recorded HRTF data. */
headphones(int16_t * sm,int frames)435 static void headphones(int16_t * sm, int frames)
436 {
437 	int i;
438 	float ld, rd;
439 	int l_final, r_final;
440 	for (i = 0; i < frames; i += 1) {
441 		ld = headphones_allpass_delay(sm[0], headphones_ap_l);
442 		rd = headphones_allpass_delay(sm[1], headphones_ap_r);
443 		ld = headphones_lpf(ld, headphones_rc_l);
444 		rd = headphones_lpf(rd, headphones_rc_r);
445 
446 		l_final =
447 		    (sm[0] + rd * UADE_EFFECT_HEADPHONES_CROSSMIX_VOL) / 2;
448 		r_final =
449 		    (sm[1] + ld * UADE_EFFECT_HEADPHONES_CROSSMIX_VOL) / 2;
450 		sm[0] = sampleclip(l_final);
451 		sm[1] = sampleclip(r_final);
452 
453 		sm += 2;
454 	}
455 }
456 
headphone2_allpass_delay(float in,float * state)457 static float headphone2_allpass_delay(float in, float *state)
458 {
459 	int i;
460 	float tmp, output;
461 
462 	tmp = in - HEADPHONE2_DELAY_K * state[0];
463 	output = state[0] + HEADPHONE2_DELAY_K * tmp;
464 
465 	/* FIXME: use modulo and index */
466 	for (i = 1; i < headphone2_delay_length; i += 1)
467 		state[i - 1] = state[i];
468 	state[headphone2_delay_length - 1] = tmp;
469 
470 	return output;
471 }
472 
headphones2(int16_t * sm,int frames)473 static void headphones2(int16_t * sm, int frames)
474 {
475 	int i;
476 	for (i = 0; i < frames; i += 1) {
477 		float ld, rd;
478 
479 		ld = headphone2_allpass_delay(sm[0], headphone2_ap_l);
480 		rd = headphone2_allpass_delay(sm[1], headphone2_ap_r);
481 		ld = evaluate_biquad(ld, &headphone2_rc_l);
482 		rd = evaluate_biquad(rd, &headphone2_rc_r);
483 		ld = evaluate_biquad(ld, &headphone2_shelve_l);
484 		rd = evaluate_biquad(rd, &headphone2_shelve_r);
485 
486 		sm[0] = sampleclip((sm[0] + rd) / 2);
487 		sm[1] = sampleclip((sm[1] + ld) / 2);
488 		sm += 2;
489 	}
490 }
491