Let qmake generate an install Makefile target to install the binary. Doesn't handle...
[Rockbox.git] / apps / dsp.c
blob7eee7bab485dde93cdb85ec450e90dff6a889d13
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 Miika Pekkarinen
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
19 #include "config.h"
20 #include <stdbool.h>
21 #include <inttypes.h>
22 #include <string.h>
23 #include <sound.h>
24 #include "dsp.h"
25 #include "eq.h"
26 #include "kernel.h"
27 #include "playback.h"
28 #include "system.h"
29 #include "settings.h"
30 #include "replaygain.h"
31 #include "misc.h"
32 #include "debug.h"
34 /* 16-bit samples are scaled based on these constants. The shift should be
35 * no more than 15.
37 #define WORD_SHIFT 12
38 #define WORD_FRACBITS 27
40 #define NATIVE_DEPTH 16
41 /* If the buffer sizes change, check the assembly code! */
42 #define SAMPLE_BUF_COUNT 256
43 #define RESAMPLE_BUF_COUNT (256 * 4) /* Enough for 11,025 Hz -> 44,100 Hz*/
44 #define DEFAULT_GAIN 0x01000000
45 #define SAMPLE_BUF_LEFT_CHANNEL 0
46 #define SAMPLE_BUF_RIGHT_CHANNEL (SAMPLE_BUF_COUNT/2)
47 #define RESAMPLE_BUF_LEFT_CHANNEL 0
48 #define RESAMPLE_BUF_RIGHT_CHANNEL (RESAMPLE_BUF_COUNT/2)
50 /* enums to index conversion properly with stereo mode and other settings */
51 enum
53 SAMPLE_INPUT_LE_NATIVE_I_STEREO = STEREO_INTERLEAVED,
54 SAMPLE_INPUT_LE_NATIVE_NI_STEREO = STEREO_NONINTERLEAVED,
55 SAMPLE_INPUT_LE_NATIVE_MONO = STEREO_MONO,
56 SAMPLE_INPUT_GT_NATIVE_I_STEREO = STEREO_INTERLEAVED + STEREO_NUM_MODES,
57 SAMPLE_INPUT_GT_NATIVE_NI_STEREO = STEREO_NONINTERLEAVED + STEREO_NUM_MODES,
58 SAMPLE_INPUT_GT_NATIVE_MONO = STEREO_MONO + STEREO_NUM_MODES,
59 SAMPLE_INPUT_GT_NATIVE_1ST_INDEX = STEREO_NUM_MODES
62 enum
64 SAMPLE_OUTPUT_MONO = 0,
65 SAMPLE_OUTPUT_STEREO,
66 SAMPLE_OUTPUT_DITHERED_MONO,
67 SAMPLE_OUTPUT_DITHERED_STEREO
70 /****************************************************************************
71 * NOTE: Any assembly routines that use these structures must be updated
72 * if current data members are moved or changed.
74 struct resample_data
76 uint32_t delta; /* 00h */
77 uint32_t phase; /* 04h */
78 int32_t last_sample[2]; /* 08h */
79 /* 10h */
82 /* This is for passing needed data to assembly dsp routines. If another
83 * dsp parameter needs to be passed, add to the end of the structure
84 * and remove from dsp_config.
85 * If another function type becomes assembly optimized and requires dsp
86 * config info, add a pointer paramter of type "struct dsp_data *".
87 * If removing something from other than the end, reserve the spot or
88 * else update every implementation for every target.
89 * Be sure to add the offset of the new member for easy viewing as well. :)
90 * It is the first member of dsp_config and all members can be accessesed
91 * through the main aggregate but this is intended to make a safe haven
92 * for these items whereas the c part can be rearranged at will. dsp_data
93 * could even moved within dsp_config without disurbing the order.
95 struct dsp_data
97 int output_scale; /* 00h */
98 int num_channels; /* 04h */
99 struct resample_data resample_data; /* 08h */
100 int32_t clip_min; /* 18h */
101 int32_t clip_max; /* 1ch */
102 int32_t gain; /* 20h - Note that this is in S8.23 format. */
103 /* 24h */
106 /* No asm...yet */
107 struct dither_data
109 long error[3]; /* 00h */
110 long random; /* 0ch */
111 /* 10h */
114 struct crossfeed_data
116 int32_t gain; /* 00h - Direct path gain */
117 int32_t coefs[3]; /* 04h - Coefficients for the shelving filter */
118 int32_t history[4]; /* 10h - Format is x[n - 1], y[n - 1] for both channels */
119 int32_t delay[13][2]; /* 20h */
120 int32_t *index; /* 88h - Current pointer into the delay line */
121 /* 8ch */
124 /* Current setup is one lowshelf filters three peaking filters and one
125 * highshelf filter. Varying the number of shelving filters make no sense,
126 * but adding peaking filters is possible.
128 struct eq_state
130 char enabled[5]; /* 00h - Flags for active filters */
131 struct eqfilter filters[5]; /* 08h - packing is 4? */
132 /* 10ch */
135 /* Include header with defines which functions are implemented in assembly
136 code for the target */
137 #include <dsp_asm.h>
139 /* Typedefs keep things much neater in this case */
140 typedef void (*sample_input_fn_type)(int count, const char *src[],
141 int32_t *dst[]);
142 typedef int (*resample_fn_type)(int count, struct dsp_data *data,
143 int32_t *src[], int32_t *dst[]);
144 typedef void (*sample_output_fn_type)(int count, struct dsp_data *data,
145 int32_t *src[], int16_t *dst);
146 /* Single-DSP channel processing in place */
147 typedef void (*channels_process_fn_type)(int count, int32_t *buf[]);
148 /* DSP local channel processing in place */
149 typedef void (*channels_process_dsp_fn_type)(int count, struct dsp_data *data,
150 int32_t *buf[]);
154 ***************************************************************************/
156 struct dsp_config
158 struct dsp_data data; /* Config members for use in asm routines */
159 long codec_frequency; /* Sample rate of data coming from the codec */
160 long frequency; /* Effective sample rate after pitch shift (if any) */
161 int sample_depth;
162 int sample_bytes;
163 int stereo_mode;
164 int frac_bits;
165 #ifdef HAVE_SW_TONE_CONTROLS
166 /* Filter struct for software bass/treble controls */
167 struct eqfilter tone_filter;
168 #endif
169 /* Functions that change depending upon settings - NULL if stage is
170 disabled */
171 sample_input_fn_type input_samples;
172 resample_fn_type resample;
173 sample_output_fn_type output_samples;
174 /* These will be NULL for the voice codec and is more economical that
175 way */
176 channels_process_dsp_fn_type apply_gain;
177 channels_process_fn_type apply_crossfeed;
178 channels_process_fn_type eq_process;
179 channels_process_fn_type channels_process;
182 /* General DSP config */
183 static struct dsp_config dsp_conf[2] IBSS_ATTR; /* 0=A, 1=V */
184 /* Dithering */
185 static struct dither_data dither_data[2] IBSS_ATTR; /* 0=left, 1=right */
186 static long dither_mask IBSS_ATTR;
187 static long dither_bias IBSS_ATTR;
188 /* Crossfeed */
189 struct crossfeed_data crossfeed_data IDATA_ATTR = /* A */
191 .index = (int32_t *)crossfeed_data.delay
194 /* Equalizer */
195 static struct eq_state eq_data; /* A */
197 /* Software tone controls */
198 #ifdef HAVE_SW_TONE_CONTROLS
199 static int prescale; /* A/V */
200 static int bass; /* A/V */
201 static int treble; /* A/V */
202 #endif
204 /* Settings applicable to audio codec only */
205 static int pitch_ratio = 1000;
206 static int channels_mode;
207 long dsp_sw_gain;
208 long dsp_sw_cross;
209 static bool dither_enabled;
210 static long eq_precut;
211 static long track_gain;
212 static bool new_gain;
213 static long album_gain;
214 static long track_peak;
215 static long album_peak;
216 static long replaygain;
217 static bool crossfeed_enabled;
219 #define audio_dsp (dsp_conf[CODEC_IDX_AUDIO])
220 #define voice_dsp (dsp_conf[CODEC_IDX_VOICE])
222 /* The internal format is 32-bit samples, non-interleaved, stereo. This
223 * format is similar to the raw output from several codecs, so the amount
224 * of copying needed is minimized for that case.
227 int32_t sample_buf[SAMPLE_BUF_COUNT] IBSS_ATTR;
228 static int32_t resample_buf[RESAMPLE_BUF_COUNT] IBSS_ATTR;
230 #if 0
231 /* Clip sample to arbitrary limits where range > 0 and min + range = max */
232 static inline long clip_sample(int32_t sample, int32_t min, int32_t range)
234 if ((uint32_t)(sample - min) > (uint32_t)range)
236 int32_t c = min;
237 if (sample > min)
238 c += range;
239 sample = c;
241 return sample;
243 #endif
245 /* Clip sample to signed 16 bit range */
246 static inline int32_t clip_sample_16(int32_t sample)
248 if ((int16_t)sample != sample)
249 sample = 0x7fff ^ (sample >> 31);
250 return sample;
253 int sound_get_pitch(void)
255 return pitch_ratio;
258 void sound_set_pitch(int permille)
260 pitch_ratio = permille;
261 dsp_configure(&audio_dsp, DSP_SWITCH_FREQUENCY,
262 audio_dsp.codec_frequency);
265 /* Convert count samples to the internal format, if needed. Updates src
266 * to point past the samples "consumed" and dst is set to point to the
267 * samples to consume. Note that for mono, dst[0] equals dst[1], as there
268 * is no point in processing the same data twice.
271 /* convert count 16-bit mono to 32-bit mono */
272 static void sample_input_lte_native_mono(
273 int count, const char *src[], int32_t *dst[])
275 const int16_t *s = (int16_t *) src[0];
276 const int16_t * const send = s + count;
277 int32_t *d = dst[0] = dst[1] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
278 int scale = WORD_SHIFT;
282 *d++ = *s++ << scale;
284 while (s < send);
286 src[0] = (char *)s;
289 /* convert count 16-bit interleaved stereo to 32-bit noninterleaved */
290 static void sample_input_lte_native_i_stereo(
291 int count, const char *src[], int32_t *dst[])
293 const int32_t *s = (int32_t *) src[0];
294 const int32_t * const send = s + count;
295 int32_t *dl = dst[0] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
296 int32_t *dr = dst[1] = &sample_buf[SAMPLE_BUF_RIGHT_CHANNEL];
297 int scale = WORD_SHIFT;
301 int32_t slr = *s++;
302 #ifdef ROCKBOX_LITTLE_ENDIAN
303 *dl++ = (slr >> 16) << scale;
304 *dr++ = (int32_t)(int16_t)slr << scale;
305 #else /* ROCKBOX_BIG_ENDIAN */
306 *dl++ = (int32_t)(int16_t)slr << scale;
307 *dr++ = (slr >> 16) << scale;
308 #endif
310 while (s < send);
312 src[0] = (char *)s;
315 /* convert count 16-bit noninterleaved stereo to 32-bit noninterleaved */
316 static void sample_input_lte_native_ni_stereo(
317 int count, const char *src[], int32_t *dst[])
319 const int16_t *sl = (int16_t *) src[0];
320 const int16_t *sr = (int16_t *) src[1];
321 const int16_t * const slend = sl + count;
322 int32_t *dl = dst[0] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
323 int32_t *dr = dst[1] = &sample_buf[SAMPLE_BUF_RIGHT_CHANNEL];
324 int scale = WORD_SHIFT;
328 *dl++ = *sl++ << scale;
329 *dr++ = *sr++ << scale;
331 while (sl < slend);
333 src[0] = (char *)sl;
334 src[1] = (char *)sr;
337 /* convert count 32-bit mono to 32-bit mono */
338 static void sample_input_gt_native_mono(
339 int count, const char *src[], int32_t *dst[])
341 dst[0] = dst[1] = (int32_t *)src[0];
342 src[0] = (char *)(dst[0] + count);
345 /* convert count 32-bit interleaved stereo to 32-bit noninterleaved stereo */
346 static void sample_input_gt_native_i_stereo(
347 int count, const char *src[], int32_t *dst[])
349 const int32_t *s = (int32_t *)src[0];
350 const int32_t * const send = s + 2*count;
351 int32_t *dl = dst[0] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
352 int32_t *dr = dst[1] = &sample_buf[SAMPLE_BUF_RIGHT_CHANNEL];
356 *dl++ = *s++;
357 *dr++ = *s++;
359 while (s < send);
361 src[0] = (char *)send;
364 /* convert 32 bit-noninterleaved stereo to 32-bit noninterleaved stereo */
365 static void sample_input_gt_native_ni_stereo(
366 int count, const char *src[], int32_t *dst[])
368 dst[0] = (int32_t *)src[0];
369 dst[1] = (int32_t *)src[1];
370 src[0] = (char *)(dst[0] + count);
371 src[1] = (char *)(dst[1] + count);
375 * sample_input_new_format()
377 * set the to-native sample conversion function based on dsp sample parameters
379 * !DSPPARAMSYNC
380 * needs syncing with changes to the following dsp parameters:
381 * * dsp->stereo_mode (A/V)
382 * * dsp->sample_depth (A/V)
384 static void sample_input_new_format(struct dsp_config *dsp)
386 static const sample_input_fn_type sample_input_functions[] =
388 [SAMPLE_INPUT_LE_NATIVE_MONO] = sample_input_lte_native_mono,
389 [SAMPLE_INPUT_LE_NATIVE_I_STEREO] = sample_input_lte_native_i_stereo,
390 [SAMPLE_INPUT_LE_NATIVE_NI_STEREO] = sample_input_lte_native_ni_stereo,
391 [SAMPLE_INPUT_GT_NATIVE_MONO] = sample_input_gt_native_mono,
392 [SAMPLE_INPUT_GT_NATIVE_I_STEREO] = sample_input_gt_native_i_stereo,
393 [SAMPLE_INPUT_GT_NATIVE_NI_STEREO] = sample_input_gt_native_ni_stereo,
396 int convert = dsp->stereo_mode;
398 if (dsp->sample_depth > NATIVE_DEPTH)
399 convert += SAMPLE_INPUT_GT_NATIVE_1ST_INDEX;
401 dsp->input_samples = sample_input_functions[convert];
404 #ifndef DSP_HAVE_ASM_SAMPLE_OUTPUT_MONO
405 /* write mono internal format to output format */
406 static void sample_output_mono(int count, struct dsp_data *data,
407 int32_t *src[], int16_t *dst)
409 const int32_t *s0 = src[0];
410 const int scale = data->output_scale;
411 const int dc_bias = 1 << (scale - 1);
415 int32_t lr = clip_sample_16((*s0++ + dc_bias) >> scale);
416 *dst++ = lr;
417 *dst++ = lr;
419 while (--count > 0);
421 #endif /* DSP_HAVE_ASM_SAMPLE_OUTPUT_MONO */
423 /* write stereo internal format to output format */
424 #ifndef DSP_HAVE_ASM_SAMPLE_OUTPUT_STEREO
425 static void sample_output_stereo(int count, struct dsp_data *data,
426 int32_t *src[], int16_t *dst)
428 const int32_t *s0 = src[0];
429 const int32_t *s1 = src[1];
430 const int scale = data->output_scale;
431 const int dc_bias = 1 << (scale - 1);
435 *dst++ = clip_sample_16((*s0++ + dc_bias) >> scale);
436 *dst++ = clip_sample_16((*s1++ + dc_bias) >> scale);
438 while (--count > 0);
440 #endif /* DSP_HAVE_ASM_SAMPLE_OUTPUT_STEREO */
443 * The "dither" code to convert the 24-bit samples produced by libmad was
444 * taken from the coolplayer project - coolplayer.sourceforge.net
446 * This function handles mono and stereo outputs.
448 static void sample_output_dithered(int count, struct dsp_data *data,
449 int32_t *src[], int16_t *dst)
451 const int32_t mask = dither_mask;
452 const int32_t bias = dither_bias;
453 const int scale = data->output_scale;
454 const int32_t min = data->clip_min;
455 const int32_t max = data->clip_max;
456 const int32_t range = max - min;
457 int ch;
458 int16_t *d;
460 for (ch = 0; ch < data->num_channels; ch++)
462 struct dither_data * const dither = &dither_data[ch];
463 int32_t *s = src[ch];
464 int i;
466 for (i = 0, d = &dst[ch]; i < count; i++, s++, d += 2)
468 int32_t output, sample;
469 int32_t random;
471 /* Noise shape and bias (for correct rounding later) */
472 sample = *s;
473 sample += dither->error[0] - dither->error[1] + dither->error[2];
474 dither->error[2] = dither->error[1];
475 dither->error[1] = dither->error[0]/2;
477 output = sample + bias;
479 /* Dither, highpass triangle PDF */
480 random = dither->random*0x0019660dL + 0x3c6ef35fL;
481 output += (random & mask) - (dither->random & mask);
482 dither->random = random;
484 /* Round sample to output range */
485 output &= ~mask;
487 /* Error feedback */
488 dither->error[0] = sample - output;
490 /* Clip */
491 if ((uint32_t)(output - min) > (uint32_t)range)
493 int32_t c = min;
494 if (output > min)
495 c += range;
496 output = c;
499 /* Quantize and store */
500 *d = output >> scale;
504 if (data->num_channels == 2)
505 return;
507 /* Have to duplicate left samples into the right channel since
508 pcm buffer and hardware is interleaved stereo */
509 d = &dst[0];
513 int16_t s = *d++;
514 *d++ = s;
516 while (--count > 0);
520 * sample_output_new_format()
522 * set the from-native to ouput sample conversion routine
524 * !DSPPARAMSYNC
525 * needs syncing with changes to the following dsp parameters:
526 * * dsp->stereo_mode (A/V)
527 * * dither_enabled (A)
529 static void sample_output_new_format(struct dsp_config *dsp)
531 static const sample_output_fn_type sample_output_functions[] =
533 sample_output_mono,
534 sample_output_stereo,
535 sample_output_dithered,
536 sample_output_dithered
539 int out = dsp->data.num_channels - 1;
541 if (dsp == &audio_dsp && dither_enabled)
542 out += 2;
544 dsp->output_samples = sample_output_functions[out];
548 * Linear interpolation resampling that introduces a one sample delay because
549 * of our inability to look into the future at the end of a frame.
551 #ifndef DSP_HAVE_ASM_RESAMPLING
552 static int dsp_downsample(int count, struct dsp_data *data,
553 int32_t *src[], int32_t *dst[])
555 int ch = data->num_channels - 1;
556 uint32_t delta = data->resample_data.delta;
557 uint32_t phase, pos;
558 int32_t *d;
560 /* Rolled channel loop actually showed slightly faster. */
563 /* Just initialize things and not worry too much about the relatively
564 * uncommon case of not being able to spit out a sample for the frame.
566 int32_t *s = src[ch];
567 int32_t last = data->resample_data.last_sample[ch];
569 data->resample_data.last_sample[ch] = s[count - 1];
570 d = dst[ch];
571 phase = data->resample_data.phase;
572 pos = phase >> 16;
574 /* Do we need last sample of previous frame for interpolation? */
575 if (pos > 0)
576 last = s[pos - 1];
578 while (pos < (uint32_t)count)
580 *d++ = last + FRACMUL((phase & 0xffff) << 15, s[pos] - last);
581 phase += delta;
582 pos = phase >> 16;
583 last = s[pos - 1];
586 while (--ch >= 0);
588 /* Wrap phase accumulator back to start of next frame. */
589 data->resample_data.phase = phase - (count << 16);
590 return d - dst[0];
593 static int dsp_upsample(int count, struct dsp_data *data,
594 int32_t *src[], int32_t *dst[])
596 int ch = data->num_channels - 1;
597 uint32_t delta = data->resample_data.delta;
598 uint32_t phase, pos;
599 int32_t *d;
601 /* Rolled channel loop actually showed slightly faster. */
604 /* Should always be able to output a sample for a ratio up to
605 RESAMPLE_BUF_COUNT / SAMPLE_BUF_COUNT. */
606 int32_t *s = src[ch];
607 int32_t last = data->resample_data.last_sample[ch];
609 data->resample_data.last_sample[ch] = s[count - 1];
610 d = dst[ch];
611 phase = data->resample_data.phase;
612 pos = phase >> 16;
614 while (pos == 0)
616 *d++ = last + FRACMUL((phase & 0xffff) << 15, s[0] - last);
617 phase += delta;
618 pos = phase >> 16;
621 while (pos < (uint32_t)count)
623 last = s[pos - 1];
624 *d++ = last + FRACMUL((phase & 0xffff) << 15, s[pos] - last);
625 phase += delta;
626 pos = phase >> 16;
629 while (--ch >= 0);
631 /* Wrap phase accumulator back to start of next frame. */
632 data->resample_data.phase = phase & 0xffff;
633 return d - dst[0];
635 #endif /* DSP_HAVE_ASM_RESAMPLING */
637 static void resampler_new_delta(struct dsp_config *dsp)
639 dsp->data.resample_data.delta = (unsigned long)
640 dsp->frequency * 65536LL / NATIVE_FREQUENCY;
642 if (dsp->frequency == NATIVE_FREQUENCY)
644 /* NOTE: If fully glitch-free transistions from no resampling to
645 resampling are desired, last_sample history should be maintained
646 even when not resampling. */
647 dsp->resample = NULL;
648 dsp->data.resample_data.phase = 0;
649 dsp->data.resample_data.last_sample[0] = 0;
650 dsp->data.resample_data.last_sample[1] = 0;
652 else if (dsp->frequency < NATIVE_FREQUENCY)
653 dsp->resample = dsp_upsample;
654 else
655 dsp->resample = dsp_downsample;
658 /* Resample count stereo samples. Updates the src array, if resampling is
659 * done, to refer to the resampled data. Returns number of stereo samples
660 * for further processing.
662 static inline int resample(struct dsp_config *dsp, int count, int32_t *src[])
664 int32_t *dst[2] =
666 &resample_buf[RESAMPLE_BUF_LEFT_CHANNEL],
667 &resample_buf[RESAMPLE_BUF_RIGHT_CHANNEL],
670 count = dsp->resample(count, &dsp->data, src, dst);
672 src[0] = dst[0];
673 src[1] = dst[dsp->data.num_channels - 1];
675 return count;
678 static void dither_init(struct dsp_config *dsp)
680 memset(dither_data, 0, sizeof (dither_data));
681 dither_bias = (1L << (dsp->frac_bits - NATIVE_DEPTH));
682 dither_mask = (1L << (dsp->frac_bits + 1 - NATIVE_DEPTH)) - 1;
685 void dsp_dither_enable(bool enable)
687 struct dsp_config *dsp = &audio_dsp;
688 dither_enabled = enable;
689 sample_output_new_format(dsp);
692 /* Applies crossfeed to the stereo signal in src.
693 * Crossfeed is a process where listening over speakers is simulated. This
694 * is good for old hard panned stereo records, which might be quite fatiguing
695 * to listen to on headphones with no crossfeed.
697 #ifndef DSP_HAVE_ASM_CROSSFEED
698 static void apply_crossfeed(int count, int32_t *buf[])
700 int32_t *hist_l = &crossfeed_data.history[0];
701 int32_t *hist_r = &crossfeed_data.history[2];
702 int32_t *delay = &crossfeed_data.delay[0][0];
703 int32_t *coefs = &crossfeed_data.coefs[0];
704 int32_t gain = crossfeed_data.gain;
705 int32_t *di = crossfeed_data.index;
707 int32_t acc;
708 int32_t left, right;
709 int i;
711 for (i = 0; i < count; i++)
713 left = buf[0][i];
714 right = buf[1][i];
716 /* Filter delayed sample from left speaker */
717 acc = FRACMUL(*di, coefs[0]);
718 acc += FRACMUL(hist_l[0], coefs[1]);
719 acc += FRACMUL(hist_l[1], coefs[2]);
720 /* Save filter history for left speaker */
721 hist_l[1] = acc;
722 hist_l[0] = *di;
723 *di++ = left;
724 /* Filter delayed sample from right speaker */
725 acc = FRACMUL(*di, coefs[0]);
726 acc += FRACMUL(hist_r[0], coefs[1]);
727 acc += FRACMUL(hist_r[1], coefs[2]);
728 /* Save filter history for right speaker */
729 hist_r[1] = acc;
730 hist_r[0] = *di;
731 *di++ = right;
732 /* Now add the attenuated direct sound and write to outputs */
733 buf[0][i] = FRACMUL(left, gain) + hist_r[1];
734 buf[1][i] = FRACMUL(right, gain) + hist_l[1];
736 /* Wrap delay line index if bigger than delay line size */
737 if (di >= delay + 13*2)
738 di = delay;
740 /* Write back local copies of data we've modified */
741 crossfeed_data.index = di;
743 #endif /* DSP_HAVE_ASM_CROSSFEED */
746 * dsp_set_crossfeed(bool enable)
748 * !DSPPARAMSYNC
749 * needs syncing with changes to the following dsp parameters:
750 * * dsp->stereo_mode (A)
752 void dsp_set_crossfeed(bool enable)
754 crossfeed_enabled = enable;
755 audio_dsp.apply_crossfeed = (enable && audio_dsp.data.num_channels > 1)
756 ? apply_crossfeed : NULL;
759 void dsp_set_crossfeed_direct_gain(int gain)
761 crossfeed_data.gain = get_replaygain_int(gain * 10) << 7;
762 /* If gain is negative, the calculation overflowed and we need to clamp */
763 if (crossfeed_data.gain < 0)
764 crossfeed_data.gain = 0x7fffffff;
767 /* Both gains should be below 0 dB */
768 void dsp_set_crossfeed_cross_params(long lf_gain, long hf_gain, long cutoff)
770 int32_t *c = crossfeed_data.coefs;
771 long scaler = get_replaygain_int(lf_gain * 10) << 7;
773 cutoff = 0xffffffff/NATIVE_FREQUENCY*cutoff;
774 hf_gain -= lf_gain;
775 /* Divide cutoff by sqrt(10^(hf_gain/20)) to place cutoff at the -3 dB
776 * point instead of shelf midpoint. This is for compatibility with the old
777 * crossfeed shelf filter and should be removed if crossfeed settings are
778 * ever made incompatible for any other good reason.
780 cutoff = DIV64(cutoff, get_replaygain_int(hf_gain*5), 24);
781 filter_shelf_coefs(cutoff, hf_gain, false, c);
782 /* Scale coefs by LF gain and shift them to s0.31 format. We have no gains
783 * over 1 and can do this safely
785 c[0] = FRACMUL_SHL(c[0], scaler, 4);
786 c[1] = FRACMUL_SHL(c[1], scaler, 4);
787 c[2] <<= 4;
790 /* Apply a constant gain to the samples (e.g., for ReplayGain).
791 * Note that this must be called before the resampler.
793 #ifndef DSP_HAVE_ASM_APPLY_GAIN
794 static void dsp_apply_gain(int count, struct dsp_data *data, int32_t *buf[])
796 const int32_t gain = data->gain;
797 int ch;
799 for (ch = 0; ch < data->num_channels; ch++)
801 int32_t *d = buf[ch];
802 int i;
804 for (i = 0; i < count; i++)
805 d[i] = FRACMUL_SHL(d[i], gain, 8);
808 #endif /* DSP_HAVE_ASM_APPLY_GAIN */
810 /* Combine all gains to a global gain. */
811 static void set_gain(struct dsp_config *dsp)
813 dsp->data.gain = DEFAULT_GAIN;
815 /* Replay gain not relevant to voice */
816 if (dsp == &audio_dsp && replaygain)
818 dsp->data.gain = replaygain;
821 if (dsp->eq_process && eq_precut)
823 dsp->data.gain =
824 (long) (((int64_t) dsp->data.gain * eq_precut) >> 24);
827 if (dsp->data.gain == DEFAULT_GAIN)
829 dsp->data.gain = 0;
831 else
833 dsp->data.gain >>= 1;
836 dsp->apply_gain = dsp->data.gain != 0 ? dsp_apply_gain : NULL;
840 * Update the amount to cut the audio before applying the equalizer.
842 * @param precut to apply in decibels (multiplied by 10)
844 void dsp_set_eq_precut(int precut)
846 eq_precut = get_replaygain_int(precut * -10);
847 set_gain(&audio_dsp);
851 * Synchronize the equalizer filter coefficients with the global settings.
853 * @param band the equalizer band to synchronize
855 void dsp_set_eq_coefs(int band)
857 const int *setting;
858 long gain;
859 unsigned long cutoff, q;
861 /* Adjust setting pointer to the band we actually want to change */
862 setting = &global_settings.eq_band0_cutoff + (band * 3);
864 /* Convert user settings to format required by coef generator functions */
865 cutoff = 0xffffffff / NATIVE_FREQUENCY * (*setting++);
866 q = *setting++;
867 gain = *setting++;
869 if (q == 0)
870 q = 1;
872 /* NOTE: The coef functions assume the EMAC unit is in fractional mode,
873 which it should be, since we're executed from the main thread. */
875 /* Assume a band is disabled if the gain is zero */
876 if (gain == 0)
878 eq_data.enabled[band] = 0;
880 else
882 if (band == 0)
883 eq_ls_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
884 else if (band == 4)
885 eq_hs_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
886 else
887 eq_pk_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
889 eq_data.enabled[band] = 1;
893 /* Apply EQ filters to those bands that have got it switched on. */
894 static void eq_process(int count, int32_t *buf[])
896 static const int shifts[] =
898 EQ_SHELF_SHIFT, /* low shelf */
899 EQ_PEAK_SHIFT, /* peaking */
900 EQ_PEAK_SHIFT, /* peaking */
901 EQ_PEAK_SHIFT, /* peaking */
902 EQ_SHELF_SHIFT, /* high shelf */
904 unsigned int channels = audio_dsp.data.num_channels;
905 int i;
907 /* filter configuration currently is 1 low shelf filter, 3 band peaking
908 filters and 1 high shelf filter, in that order. we need to know this
909 so we can choose the correct shift factor.
911 for (i = 0; i < 5; i++)
913 if (!eq_data.enabled[i])
914 continue;
915 eq_filter(buf, &eq_data.filters[i], count, channels, shifts[i]);
920 * Use to enable the equalizer.
922 * @param enable true to enable the equalizer
924 void dsp_set_eq(bool enable)
926 audio_dsp.eq_process = enable ? eq_process : NULL;
927 set_gain(&audio_dsp);
930 static void dsp_set_stereo_width(int value)
932 long width, straight, cross;
934 width = value * 0x7fffff / 100;
936 if (value <= 100)
938 straight = (0x7fffff + width) / 2;
939 cross = straight - width;
941 else
943 /* straight = (1 + width) / (2 * width) */
944 straight = ((int64_t)(0x7fffff + width) << 22) / width;
945 cross = straight - 0x7fffff;
948 dsp_sw_gain = straight << 8;
949 dsp_sw_cross = cross << 8;
953 * Implements the different channel configurations and stereo width.
956 /* SOUND_CHAN_STEREO mode is a noop so has no function - just outline one for
957 * completeness. */
958 #if 0
959 static void channels_process_sound_chan_stereo(int count, int32_t *buf[])
961 /* The channels are each just themselves */
962 (void)count; (void)buf;
964 #endif
966 #ifndef DSP_HAVE_ASM_SOUND_CHAN_MONO
967 static void channels_process_sound_chan_mono(int count, int32_t *buf[])
969 int32_t *sl = buf[0], *sr = buf[1];
973 int32_t lr = *sl/2 + *sr/2;
974 *sl++ = lr;
975 *sr++ = lr;
977 while (--count > 0);
979 #endif /* DSP_HAVE_ASM_SOUND_CHAN_MONO */
981 #ifndef DSP_HAVE_ASM_SOUND_CHAN_CUSTOM
982 static void channels_process_sound_chan_custom(int count, int32_t *buf[])
984 const int32_t gain = dsp_sw_gain;
985 const int32_t cross = dsp_sw_cross;
986 int32_t *sl = buf[0], *sr = buf[1];
990 int32_t l = *sl;
991 int32_t r = *sr;
992 *sl++ = FRACMUL(l, gain) + FRACMUL(r, cross);
993 *sr++ = FRACMUL(r, gain) + FRACMUL(l, cross);
995 while (--count > 0);
997 #endif /* DSP_HAVE_ASM_SOUND_CHAN_CUSTOM */
999 static void channels_process_sound_chan_mono_left(int count, int32_t *buf[])
1001 /* Just copy over the other channel */
1002 memcpy(buf[1], buf[0], count * sizeof (*buf));
1005 static void channels_process_sound_chan_mono_right(int count, int32_t *buf[])
1007 /* Just copy over the other channel */
1008 memcpy(buf[0], buf[1], count * sizeof (*buf));
1011 #ifndef DSP_HAVE_ASM_SOUND_CHAN_KARAOKE
1012 static void channels_process_sound_chan_karaoke(int count, int32_t *buf[])
1014 int32_t *sl = buf[0], *sr = buf[1];
1018 int32_t ch = *sl/2 - *sr/2;
1019 *sl++ = ch;
1020 *sr++ = -ch;
1022 while (--count > 0);
1024 #endif /* DSP_HAVE_ASM_SOUND_CHAN_KARAOKE */
1026 static void dsp_set_channel_config(int value)
1028 static const channels_process_fn_type channels_process_functions[] =
1030 /* SOUND_CHAN_STEREO = All-purpose index for no channel processing */
1031 [SOUND_CHAN_STEREO] = NULL,
1032 [SOUND_CHAN_MONO] = channels_process_sound_chan_mono,
1033 [SOUND_CHAN_CUSTOM] = channels_process_sound_chan_custom,
1034 [SOUND_CHAN_MONO_LEFT] = channels_process_sound_chan_mono_left,
1035 [SOUND_CHAN_MONO_RIGHT] = channels_process_sound_chan_mono_right,
1036 [SOUND_CHAN_KARAOKE] = channels_process_sound_chan_karaoke,
1039 if ((unsigned)value >= ARRAYLEN(channels_process_functions) ||
1040 audio_dsp.stereo_mode == STEREO_MONO)
1042 value = SOUND_CHAN_STEREO;
1045 /* This doesn't apply to voice */
1046 channels_mode = value;
1047 audio_dsp.channels_process = channels_process_functions[value];
1050 #if CONFIG_CODEC == SWCODEC
1052 #ifdef HAVE_SW_TONE_CONTROLS
1053 static void set_tone_controls(void)
1055 filter_bishelf_coefs(0xffffffff/NATIVE_FREQUENCY*200,
1056 0xffffffff/NATIVE_FREQUENCY*3500,
1057 bass, treble, -prescale,
1058 audio_dsp.tone_filter.coefs);
1059 /* Sync the voice dsp coefficients */
1060 memcpy(&voice_dsp.tone_filter.coefs, audio_dsp.tone_filter.coefs,
1061 sizeof (voice_dsp.tone_filter.coefs));
1063 #endif
1065 /* Hook back from firmware/ part of audio, which can't/shouldn't call apps/
1066 * code directly.
1068 int dsp_callback(int msg, intptr_t param)
1070 switch (msg) {
1071 #ifdef HAVE_SW_TONE_CONTROLS
1072 case DSP_CALLBACK_SET_PRESCALE:
1073 prescale = param;
1074 set_tone_controls();
1075 break;
1076 /* prescaler is always set after calling any of these, so we wait with
1077 * calculating coefs until the above case is hit.
1079 case DSP_CALLBACK_SET_BASS:
1080 bass = param;
1081 break;
1082 case DSP_CALLBACK_SET_TREBLE:
1083 treble = param;
1084 #endif
1085 case DSP_CALLBACK_SET_CHANNEL_CONFIG:
1086 dsp_set_channel_config(param);
1087 break;
1088 case DSP_CALLBACK_SET_STEREO_WIDTH:
1089 dsp_set_stereo_width(param);
1090 break;
1091 default:
1092 break;
1094 return 0;
1096 #endif
1098 /* Process and convert src audio to dst based on the DSP configuration,
1099 * reading count number of audio samples. dst is assumed to be large
1100 * enough; use dsp_output_count() to get the required number. src is an
1101 * array of pointers; for mono and interleaved stereo, it contains one
1102 * pointer to the start of the audio data and the other is ignored; for
1103 * non-interleaved stereo, it contains two pointers, one for each audio
1104 * channel. Returns number of bytes written to dst.
1106 int dsp_process(struct dsp_config *dsp, char *dst, const char *src[], int count)
1108 int32_t *tmp[2];
1109 static long last_yield;
1110 long tick;
1111 int written = 0;
1112 int samples;
1114 #if defined(CPU_COLDFIRE)
1115 /* set emac unit for dsp processing, and save old macsr, we're running in
1116 codec thread context at this point, so can't clobber it */
1117 unsigned long old_macsr = coldfire_get_macsr();
1118 coldfire_set_macsr(EMAC_FRACTIONAL | EMAC_SATURATE);
1119 #endif
1121 if (new_gain)
1122 dsp_set_replaygain(); /* Gain has changed */
1124 /* Perform at least one yield before starting */
1125 last_yield = current_tick;
1126 yield();
1128 /* Testing function pointers for NULL is preferred since the pointer
1129 will be preloaded to be used for the call if not. */
1130 while (count > 0)
1132 samples = MIN(SAMPLE_BUF_COUNT/2, count);
1133 count -= samples;
1135 dsp->input_samples(samples, src, tmp);
1137 if (dsp->apply_gain)
1138 dsp->apply_gain(samples, &dsp->data, tmp);
1140 if (dsp->resample && (samples = resample(dsp, samples, tmp)) <= 0)
1141 break; /* I'm pretty sure we're downsampling here */
1143 if (dsp->apply_crossfeed)
1144 dsp->apply_crossfeed(samples, tmp);
1146 if (dsp->eq_process)
1147 dsp->eq_process(samples, tmp);
1149 #ifdef HAVE_SW_TONE_CONTROLS
1150 if ((bass | treble) != 0)
1151 eq_filter(tmp, &dsp->tone_filter, samples,
1152 dsp->data.num_channels, FILTER_BISHELF_SHIFT);
1153 #endif
1155 if (dsp->channels_process)
1156 dsp->channels_process(samples, tmp);
1158 dsp->output_samples(samples, &dsp->data, tmp, (int16_t *)dst);
1160 written += samples;
1161 dst += samples * sizeof (int16_t) * 2;
1163 /* yield at least once each tick */
1164 tick = current_tick;
1165 if (TIME_AFTER(tick, last_yield))
1167 last_yield = tick;
1168 yield();
1172 #if defined(CPU_COLDFIRE)
1173 /* set old macsr again */
1174 coldfire_set_macsr(old_macsr);
1175 #endif
1176 return written;
1179 /* Given count number of input samples, calculate the maximum number of
1180 * samples of output data that would be generated (the calculation is not
1181 * entirely exact and rounds upwards to be on the safe side; during
1182 * resampling, the number of samples generated depends on the current state
1183 * of the resampler).
1185 /* dsp_input_size MUST be called afterwards */
1186 int dsp_output_count(struct dsp_config *dsp, int count)
1188 if (dsp->resample)
1190 count = (int)(((unsigned long)count * NATIVE_FREQUENCY
1191 + (dsp->frequency - 1)) / dsp->frequency);
1194 /* Now we have the resampled sample count which must not exceed
1195 * RESAMPLE_BUF_COUNT/2 to avoid resample buffer overflow. One
1196 * must call dsp_input_count() to get the correct input sample
1197 * count.
1199 if (count > RESAMPLE_BUF_COUNT/2)
1200 count = RESAMPLE_BUF_COUNT/2;
1202 return count;
1205 /* Given count output samples, calculate number of input samples
1206 * that would be consumed in order to fill the output buffer.
1208 int dsp_input_count(struct dsp_config *dsp, int count)
1210 /* count is now the number of resampled input samples. Convert to
1211 original input samples. */
1212 if (dsp->resample)
1214 /* Use the real resampling delta =
1215 * dsp->frequency * 65536 / NATIVE_FREQUENCY, and
1216 * round towards zero to avoid buffer overflows. */
1217 count = (int)(((unsigned long)count *
1218 dsp->data.resample_data.delta) >> 16);
1221 return count;
1224 static void dsp_set_gain_var(long *var, long value)
1226 *var = value;
1227 new_gain = true;
1230 static void dsp_update_functions(struct dsp_config *dsp)
1232 sample_input_new_format(dsp);
1233 sample_output_new_format(dsp);
1234 if (dsp == &audio_dsp)
1235 dsp_set_crossfeed(crossfeed_enabled);
1238 intptr_t dsp_configure(struct dsp_config *dsp, int setting, intptr_t value)
1240 switch (setting)
1242 case DSP_MYDSP:
1243 switch (value)
1245 case CODEC_IDX_AUDIO:
1246 return (intptr_t)&audio_dsp;
1247 case CODEC_IDX_VOICE:
1248 return (intptr_t)&voice_dsp;
1249 default:
1250 return (intptr_t)NULL;
1253 case DSP_SET_FREQUENCY:
1254 memset(&dsp->data.resample_data, 0, sizeof (dsp->data.resample_data));
1255 /* Fall through!!! */
1256 case DSP_SWITCH_FREQUENCY:
1257 dsp->codec_frequency = (value == 0) ? NATIVE_FREQUENCY : value;
1258 /* Account for playback speed adjustment when setting dsp->frequency
1259 if we're called from the main audio thread. Voice UI thread should
1260 not need this feature.
1262 if (dsp == &audio_dsp)
1263 dsp->frequency = pitch_ratio * dsp->codec_frequency / 1000;
1264 else
1265 dsp->frequency = dsp->codec_frequency;
1267 resampler_new_delta(dsp);
1268 break;
1270 case DSP_SET_SAMPLE_DEPTH:
1271 dsp->sample_depth = value;
1273 if (dsp->sample_depth <= NATIVE_DEPTH)
1275 dsp->frac_bits = WORD_FRACBITS;
1276 dsp->sample_bytes = sizeof (int16_t); /* samples are 16 bits */
1277 dsp->data.clip_max = ((1 << WORD_FRACBITS) - 1);
1278 dsp->data.clip_min = -((1 << WORD_FRACBITS));
1280 else
1282 dsp->frac_bits = value;
1283 dsp->sample_bytes = sizeof (int32_t); /* samples are 32 bits */
1284 dsp->data.clip_max = (1 << value) - 1;
1285 dsp->data.clip_min = -(1 << value);
1288 dsp->data.output_scale = dsp->frac_bits + 1 - NATIVE_DEPTH;
1289 sample_input_new_format(dsp);
1290 dither_init(dsp);
1291 break;
1293 case DSP_SET_STEREO_MODE:
1294 dsp->stereo_mode = value;
1295 dsp->data.num_channels = value == STEREO_MONO ? 1 : 2;
1296 dsp_update_functions(dsp);
1297 break;
1299 case DSP_RESET:
1300 dsp->stereo_mode = STEREO_NONINTERLEAVED;
1301 dsp->data.num_channels = 2;
1302 dsp->sample_depth = NATIVE_DEPTH;
1303 dsp->frac_bits = WORD_FRACBITS;
1304 dsp->sample_bytes = sizeof (int16_t);
1305 dsp->data.output_scale = dsp->frac_bits + 1 - NATIVE_DEPTH;
1306 dsp->data.clip_max = ((1 << WORD_FRACBITS) - 1);
1307 dsp->data.clip_min = -((1 << WORD_FRACBITS));
1308 dsp->codec_frequency = dsp->frequency = NATIVE_FREQUENCY;
1310 if (dsp == &audio_dsp)
1312 track_gain = 0;
1313 album_gain = 0;
1314 track_peak = 0;
1315 album_peak = 0;
1316 new_gain = true;
1319 dsp_update_functions(dsp);
1320 resampler_new_delta(dsp);
1321 break;
1323 case DSP_FLUSH:
1324 memset(&dsp->data.resample_data, 0,
1325 sizeof (dsp->data.resample_data));
1326 resampler_new_delta(dsp);
1327 dither_init(dsp);
1328 break;
1330 case DSP_SET_TRACK_GAIN:
1331 if (dsp == &audio_dsp)
1332 dsp_set_gain_var(&track_gain, value);
1333 break;
1335 case DSP_SET_ALBUM_GAIN:
1336 if (dsp == &audio_dsp)
1337 dsp_set_gain_var(&album_gain, value);
1338 break;
1340 case DSP_SET_TRACK_PEAK:
1341 if (dsp == &audio_dsp)
1342 dsp_set_gain_var(&track_peak, value);
1343 break;
1345 case DSP_SET_ALBUM_PEAK:
1346 if (dsp == &audio_dsp)
1347 dsp_set_gain_var(&album_peak, value);
1348 break;
1350 default:
1351 return 0;
1354 return 1;
1357 void dsp_set_replaygain(void)
1359 long gain = 0;
1361 new_gain = false;
1363 if (global_settings.replaygain || global_settings.replaygain_noclip)
1365 bool track_mode = get_replaygain_mode(track_gain != 0,
1366 album_gain != 0) == REPLAYGAIN_TRACK;
1367 long peak = (track_mode || !album_peak) ? track_peak : album_peak;
1369 if (global_settings.replaygain)
1371 gain = (track_mode || !album_gain) ? track_gain : album_gain;
1373 if (global_settings.replaygain_preamp)
1375 long preamp = get_replaygain_int(
1376 global_settings.replaygain_preamp * 10);
1378 gain = (long) (((int64_t) gain * preamp) >> 24);
1382 if (gain == 0)
1384 /* So that noclip can work even with no gain information. */
1385 gain = DEFAULT_GAIN;
1388 if (global_settings.replaygain_noclip && (peak != 0)
1389 && ((((int64_t) gain * peak) >> 24) >= DEFAULT_GAIN))
1391 gain = (((int64_t) DEFAULT_GAIN << 24) / peak);
1394 if (gain == DEFAULT_GAIN)
1396 /* Nothing to do, disable processing. */
1397 gain = 0;
1401 /* Store in S8.23 format to simplify calculations. */
1402 replaygain = gain;
1403 set_gain(&audio_dsp);