rbutil: store the voice language in the correct setting.
[kugel-rb.git] / apps / dsp.c
blob0f7f8b12bcc40ae8e47a2b4f1e5275cfdd32dded
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 Miika Pekkarinen
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
21 #include "config.h"
22 #include <stdbool.h>
23 #include <inttypes.h>
24 #include <string.h>
25 #include <sound.h>
26 #include "dsp.h"
27 #include "eq.h"
28 #include "kernel.h"
29 #include "playback.h"
30 #include "system.h"
31 #include "settings.h"
32 #include "replaygain.h"
33 #include "misc.h"
34 #include "tdspeed.h"
35 #include "buffer.h"
36 #include "fixedpoint.h"
37 #include "fracmul.h"
38 #include "pcmbuf.h"
40 /* Define LOGF_ENABLE to enable logf output in this file */
41 /*#define LOGF_ENABLE*/
42 #include "logf.h"
44 /* 16-bit samples are scaled based on these constants. The shift should be
45 * no more than 15.
47 #define WORD_SHIFT 12
48 #define WORD_FRACBITS 27
50 #define NATIVE_DEPTH 16
51 /* If the small buffer size changes, check the assembly code! */
52 #define SMALL_SAMPLE_BUF_COUNT 256
53 #define DEFAULT_GAIN 0x01000000
55 /* enums to index conversion properly with stereo mode and other settings */
56 enum
58 SAMPLE_INPUT_LE_NATIVE_I_STEREO = STEREO_INTERLEAVED,
59 SAMPLE_INPUT_LE_NATIVE_NI_STEREO = STEREO_NONINTERLEAVED,
60 SAMPLE_INPUT_LE_NATIVE_MONO = STEREO_MONO,
61 SAMPLE_INPUT_GT_NATIVE_I_STEREO = STEREO_INTERLEAVED + STEREO_NUM_MODES,
62 SAMPLE_INPUT_GT_NATIVE_NI_STEREO = STEREO_NONINTERLEAVED + STEREO_NUM_MODES,
63 SAMPLE_INPUT_GT_NATIVE_MONO = STEREO_MONO + STEREO_NUM_MODES,
64 SAMPLE_INPUT_GT_NATIVE_1ST_INDEX = STEREO_NUM_MODES
67 enum
69 SAMPLE_OUTPUT_MONO = 0,
70 SAMPLE_OUTPUT_STEREO,
71 SAMPLE_OUTPUT_DITHERED_MONO,
72 SAMPLE_OUTPUT_DITHERED_STEREO
75 /****************************************************************************
76 * NOTE: Any assembly routines that use these structures must be updated
77 * if current data members are moved or changed.
79 struct resample_data
81 uint32_t delta; /* 00h */
82 uint32_t phase; /* 04h */
83 int32_t last_sample[2]; /* 08h */
84 /* 10h */
87 /* This is for passing needed data to assembly dsp routines. If another
88 * dsp parameter needs to be passed, add to the end of the structure
89 * and remove from dsp_config.
90 * If another function type becomes assembly optimized and requires dsp
91 * config info, add a pointer paramter of type "struct dsp_data *".
92 * If removing something from other than the end, reserve the spot or
93 * else update every implementation for every target.
94 * Be sure to add the offset of the new member for easy viewing as well. :)
95 * It is the first member of dsp_config and all members can be accessesed
96 * through the main aggregate but this is intended to make a safe haven
97 * for these items whereas the c part can be rearranged at will. dsp_data
98 * could even moved within dsp_config without disurbing the order.
100 struct dsp_data
102 int output_scale; /* 00h */
103 int num_channels; /* 04h */
104 struct resample_data resample_data; /* 08h */
105 int32_t clip_min; /* 18h */
106 int32_t clip_max; /* 1ch */
107 int32_t gain; /* 20h - Note that this is in S8.23 format. */
108 /* 24h */
111 /* No asm...yet */
112 struct dither_data
114 long error[3]; /* 00h */
115 long random; /* 0ch */
116 /* 10h */
119 struct crossfeed_data
121 int32_t gain; /* 00h - Direct path gain */
122 int32_t coefs[3]; /* 04h - Coefficients for the shelving filter */
123 int32_t history[4]; /* 10h - Format is x[n - 1], y[n - 1] for both channels */
124 int32_t delay[13][2]; /* 20h */
125 int32_t *index; /* 88h - Current pointer into the delay line */
126 /* 8ch */
129 /* Current setup is one lowshelf filters three peaking filters and one
130 * highshelf filter. Varying the number of shelving filters make no sense,
131 * but adding peaking filters is possible.
133 struct eq_state
135 char enabled[5]; /* 00h - Flags for active filters */
136 struct eqfilter filters[5]; /* 08h - packing is 4? */
137 /* 10ch */
140 struct compressor_menu
142 int threshold; /* dB - from menu */
143 int ratio; /* from menu */
144 int gain; /* dB - from menu */
145 bool soft_knee; /* 0 = hard knee, 1 = soft knee */
146 int release; /* samples - from menu */
149 /* Include header with defines which functions are implemented in assembly
150 code for the target */
151 #include <dsp_asm.h>
153 /* Typedefs keep things much neater in this case */
154 typedef void (*sample_input_fn_type)(int count, const char *src[],
155 int32_t *dst[]);
156 typedef int (*resample_fn_type)(int count, struct dsp_data *data,
157 const int32_t *src[], int32_t *dst[]);
158 typedef void (*sample_output_fn_type)(int count, struct dsp_data *data,
159 const int32_t *src[], int16_t *dst);
161 /* Single-DSP channel processing in place */
162 typedef void (*channels_process_fn_type)(int count, int32_t *buf[]);
163 /* DSP local channel processing in place */
164 typedef void (*channels_process_dsp_fn_type)(int count, struct dsp_data *data,
165 int32_t *buf[]);
166 /* DSP processes that return a value */
167 typedef int (*return_fn_type)(int count, int32_t *buf[]);
170 ***************************************************************************/
172 struct dsp_config
174 struct dsp_data data; /* Config members for use in asm routines */
175 long codec_frequency; /* Sample rate of data coming from the codec */
176 long frequency; /* Effective sample rate after pitch shift (if any) */
177 int sample_depth;
178 int sample_bytes;
179 int stereo_mode;
180 int32_t tdspeed_percent; /* Speed% * PITCH_SPEED_PRECISION */
181 bool tdspeed_active; /* Timestretch is in use */
182 int frac_bits;
183 #ifdef HAVE_SW_TONE_CONTROLS
184 /* Filter struct for software bass/treble controls */
185 struct eqfilter tone_filter;
186 #endif
187 /* Functions that change depending upon settings - NULL if stage is
188 disabled */
189 sample_input_fn_type input_samples;
190 resample_fn_type resample;
191 sample_output_fn_type output_samples;
192 /* These will be NULL for the voice codec and is more economical that
193 way */
194 channels_process_dsp_fn_type apply_gain;
195 channels_process_fn_type apply_crossfeed;
196 channels_process_fn_type eq_process;
197 channels_process_fn_type channels_process;
198 return_fn_type compressor_process;
201 /* General DSP config */
202 static struct dsp_config dsp_conf[2] IBSS_ATTR; /* 0=A, 1=V */
203 /* Dithering */
204 static struct dither_data dither_data[2] IBSS_ATTR; /* 0=left, 1=right */
205 static long dither_mask IBSS_ATTR;
206 static long dither_bias IBSS_ATTR;
207 /* Crossfeed */
208 struct crossfeed_data crossfeed_data IDATA_ATTR = /* A */
210 .index = (int32_t *)crossfeed_data.delay
213 /* Equalizer */
214 static struct eq_state eq_data; /* A */
216 /* Software tone controls */
217 #ifdef HAVE_SW_TONE_CONTROLS
218 static int prescale; /* A/V */
219 static int bass; /* A/V */
220 static int treble; /* A/V */
221 #endif
223 /* Settings applicable to audio codec only */
224 static int32_t pitch_ratio = PITCH_SPEED_100;
225 static int channels_mode;
226 long dsp_sw_gain;
227 long dsp_sw_cross;
228 static bool dither_enabled;
229 static long eq_precut;
230 static long track_gain;
231 static bool new_gain;
232 static long album_gain;
233 static long track_peak;
234 static long album_peak;
235 static long replaygain;
236 static bool crossfeed_enabled;
238 #define AUDIO_DSP (dsp_conf[CODEC_IDX_AUDIO])
239 #define VOICE_DSP (dsp_conf[CODEC_IDX_VOICE])
241 /* The internal format is 32-bit samples, non-interleaved, stereo. This
242 * format is similar to the raw output from several codecs, so the amount
243 * of copying needed is minimized for that case.
246 #define RESAMPLE_RATIO 4 /* Enough for 11,025 Hz -> 44,100 Hz */
248 static int32_t small_sample_buf[SMALL_SAMPLE_BUF_COUNT] IBSS_ATTR;
249 static int32_t small_resample_buf[SMALL_SAMPLE_BUF_COUNT * RESAMPLE_RATIO] IBSS_ATTR;
251 static int32_t *big_sample_buf = NULL;
252 static int32_t *big_resample_buf = NULL;
253 static int big_sample_buf_count = -1; /* -1=unknown, 0=not available */
255 static int sample_buf_count;
256 static int32_t *sample_buf;
257 static int32_t *resample_buf;
259 #define SAMPLE_BUF_LEFT_CHANNEL 0
260 #define SAMPLE_BUF_RIGHT_CHANNEL (sample_buf_count/2)
261 #define RESAMPLE_BUF_LEFT_CHANNEL 0
262 #define RESAMPLE_BUF_RIGHT_CHANNEL (sample_buf_count/2 * RESAMPLE_RATIO)
264 /* compressor */
265 /* MAX_COUNT is largest possible sample count in compressor_process */
266 #define MAX_COUNT (SMALL_SAMPLE_BUF_COUNT * RESAMPLE_RATIO / 2)
267 static struct compressor_menu c_menu;
268 static int32_t comp_rel_slope IBSS_ATTR; /* S7.24 format */
269 static int32_t comp_makeup_gain IBSS_ATTR; /* S7.24 format */
270 static int32_t comp_curve[65] IBSS_ATTR; /* S7.24 format */
271 static int32_t gain_buffer[MAX_COUNT] IBSS_ATTR;
272 static int32_t release_gain IBSS_ATTR;
274 static int compressor_process(int count, int32_t *buf[]);
277 /* Clip sample to signed 16 bit range */
278 static inline int32_t clip_sample_16(int32_t sample)
280 if ((int16_t)sample != sample)
281 sample = 0x7fff ^ (sample >> 31);
282 return sample;
285 int32_t sound_get_pitch(void)
287 return pitch_ratio;
290 void sound_set_pitch(int32_t percent)
292 pitch_ratio = percent;
293 dsp_configure(&AUDIO_DSP, DSP_SWITCH_FREQUENCY,
294 AUDIO_DSP.codec_frequency);
297 static void tdspeed_setup(struct dsp_config *dspc)
299 /* Assume timestretch will not be used */
300 dspc->tdspeed_active = false;
301 sample_buf = small_sample_buf;
302 resample_buf = small_resample_buf;
303 sample_buf_count = SMALL_SAMPLE_BUF_COUNT;
305 if(!dsp_timestretch_available())
306 return; /* Timestretch not enabled or buffer not allocated */
307 if (dspc->tdspeed_percent == 0)
308 dspc->tdspeed_percent = PITCH_SPEED_100;
309 if (!tdspeed_config(
310 dspc->codec_frequency == 0 ? NATIVE_FREQUENCY : dspc->codec_frequency,
311 dspc->stereo_mode != STEREO_MONO,
312 dspc->tdspeed_percent))
313 return; /* Timestretch not possible or needed with these parameters */
315 /* Timestretch is to be used */
316 dspc->tdspeed_active = true;
317 sample_buf = big_sample_buf;
318 sample_buf_count = big_sample_buf_count;
319 resample_buf = big_resample_buf;
322 void dsp_timestretch_enable(bool enabled)
324 /* Hook to set up timestretch buffer on first call to settings_apply() */
325 if (big_sample_buf_count < 0) /* Only do something on first call */
327 if (enabled)
329 /* Set up timestretch buffers */
330 big_sample_buf_count = SMALL_SAMPLE_BUF_COUNT * RESAMPLE_RATIO;
331 big_sample_buf = small_resample_buf;
332 big_resample_buf = (int32_t *) buffer_alloc(big_sample_buf_count * RESAMPLE_RATIO * sizeof(int32_t));
334 else
336 /* Not enabled at startup, "big" buffers will never be available */
337 big_sample_buf_count = 0;
339 tdspeed_setup(&AUDIO_DSP);
343 void dsp_set_timestretch(int32_t percent)
345 AUDIO_DSP.tdspeed_percent = percent;
346 tdspeed_setup(&AUDIO_DSP);
349 int32_t dsp_get_timestretch()
351 return AUDIO_DSP.tdspeed_percent;
354 bool dsp_timestretch_available()
356 return (global_settings.timestretch_enabled && big_sample_buf_count > 0);
359 /* Convert count samples to the internal format, if needed. Updates src
360 * to point past the samples "consumed" and dst is set to point to the
361 * samples to consume. Note that for mono, dst[0] equals dst[1], as there
362 * is no point in processing the same data twice.
365 /* convert count 16-bit mono to 32-bit mono */
366 static void sample_input_lte_native_mono(
367 int count, const char *src[], int32_t *dst[])
369 const int16_t *s = (int16_t *) src[0];
370 const int16_t * const send = s + count;
371 int32_t *d = dst[0] = dst[1] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
372 int scale = WORD_SHIFT;
374 while (s < send)
376 *d++ = *s++ << scale;
379 src[0] = (char *)s;
382 /* convert count 16-bit interleaved stereo to 32-bit noninterleaved */
383 static void sample_input_lte_native_i_stereo(
384 int count, const char *src[], int32_t *dst[])
386 const int32_t *s = (int32_t *) src[0];
387 const int32_t * const send = s + count;
388 int32_t *dl = dst[0] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
389 int32_t *dr = dst[1] = &sample_buf[SAMPLE_BUF_RIGHT_CHANNEL];
390 int scale = WORD_SHIFT;
392 while (s < send)
394 int32_t slr = *s++;
395 #ifdef ROCKBOX_LITTLE_ENDIAN
396 *dl++ = (slr >> 16) << scale;
397 *dr++ = (int32_t)(int16_t)slr << scale;
398 #else /* ROCKBOX_BIG_ENDIAN */
399 *dl++ = (int32_t)(int16_t)slr << scale;
400 *dr++ = (slr >> 16) << scale;
401 #endif
404 src[0] = (char *)s;
407 /* convert count 16-bit noninterleaved stereo to 32-bit noninterleaved */
408 static void sample_input_lte_native_ni_stereo(
409 int count, const char *src[], int32_t *dst[])
411 const int16_t *sl = (int16_t *) src[0];
412 const int16_t *sr = (int16_t *) src[1];
413 const int16_t * const slend = sl + count;
414 int32_t *dl = dst[0] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
415 int32_t *dr = dst[1] = &sample_buf[SAMPLE_BUF_RIGHT_CHANNEL];
416 int scale = WORD_SHIFT;
418 while (sl < slend)
420 *dl++ = *sl++ << scale;
421 *dr++ = *sr++ << scale;
424 src[0] = (char *)sl;
425 src[1] = (char *)sr;
428 /* convert count 32-bit mono to 32-bit mono */
429 static void sample_input_gt_native_mono(
430 int count, const char *src[], int32_t *dst[])
432 dst[0] = dst[1] = (int32_t *)src[0];
433 src[0] = (char *)(dst[0] + count);
436 /* convert count 32-bit interleaved stereo to 32-bit noninterleaved stereo */
437 static void sample_input_gt_native_i_stereo(
438 int count, const char *src[], int32_t *dst[])
440 const int32_t *s = (int32_t *)src[0];
441 const int32_t * const send = s + 2*count;
442 int32_t *dl = dst[0] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
443 int32_t *dr = dst[1] = &sample_buf[SAMPLE_BUF_RIGHT_CHANNEL];
445 while (s < send)
447 *dl++ = *s++;
448 *dr++ = *s++;
451 src[0] = (char *)send;
454 /* convert 32 bit-noninterleaved stereo to 32-bit noninterleaved stereo */
455 static void sample_input_gt_native_ni_stereo(
456 int count, const char *src[], int32_t *dst[])
458 dst[0] = (int32_t *)src[0];
459 dst[1] = (int32_t *)src[1];
460 src[0] = (char *)(dst[0] + count);
461 src[1] = (char *)(dst[1] + count);
465 * sample_input_new_format()
467 * set the to-native sample conversion function based on dsp sample parameters
469 * !DSPPARAMSYNC
470 * needs syncing with changes to the following dsp parameters:
471 * * dsp->stereo_mode (A/V)
472 * * dsp->sample_depth (A/V)
474 static void sample_input_new_format(struct dsp_config *dsp)
476 static const sample_input_fn_type sample_input_functions[] =
478 [SAMPLE_INPUT_LE_NATIVE_I_STEREO] = sample_input_lte_native_i_stereo,
479 [SAMPLE_INPUT_LE_NATIVE_NI_STEREO] = sample_input_lte_native_ni_stereo,
480 [SAMPLE_INPUT_LE_NATIVE_MONO] = sample_input_lte_native_mono,
481 [SAMPLE_INPUT_GT_NATIVE_I_STEREO] = sample_input_gt_native_i_stereo,
482 [SAMPLE_INPUT_GT_NATIVE_NI_STEREO] = sample_input_gt_native_ni_stereo,
483 [SAMPLE_INPUT_GT_NATIVE_MONO] = sample_input_gt_native_mono,
486 int convert = dsp->stereo_mode;
488 if (dsp->sample_depth > NATIVE_DEPTH)
489 convert += SAMPLE_INPUT_GT_NATIVE_1ST_INDEX;
491 dsp->input_samples = sample_input_functions[convert];
495 #ifndef DSP_HAVE_ASM_SAMPLE_OUTPUT_MONO
496 /* write mono internal format to output format */
497 static void sample_output_mono(int count, struct dsp_data *data,
498 const int32_t *src[], int16_t *dst)
500 const int32_t *s0 = src[0];
501 const int scale = data->output_scale;
502 const int dc_bias = 1 << (scale - 1);
504 while (count-- > 0)
506 int32_t lr = clip_sample_16((*s0++ + dc_bias) >> scale);
507 *dst++ = lr;
508 *dst++ = lr;
511 #endif /* DSP_HAVE_ASM_SAMPLE_OUTPUT_MONO */
513 /* write stereo internal format to output format */
514 #ifndef DSP_HAVE_ASM_SAMPLE_OUTPUT_STEREO
515 static void sample_output_stereo(int count, struct dsp_data *data,
516 const int32_t *src[], int16_t *dst)
518 const int32_t *s0 = src[0];
519 const int32_t *s1 = src[1];
520 const int scale = data->output_scale;
521 const int dc_bias = 1 << (scale - 1);
523 while (count-- > 0)
525 *dst++ = clip_sample_16((*s0++ + dc_bias) >> scale);
526 *dst++ = clip_sample_16((*s1++ + dc_bias) >> scale);
529 #endif /* DSP_HAVE_ASM_SAMPLE_OUTPUT_STEREO */
532 * The "dither" code to convert the 24-bit samples produced by libmad was
533 * taken from the coolplayer project - coolplayer.sourceforge.net
535 * This function handles mono and stereo outputs.
537 static void sample_output_dithered(int count, struct dsp_data *data,
538 const int32_t *src[], int16_t *dst)
540 const int32_t mask = dither_mask;
541 const int32_t bias = dither_bias;
542 const int scale = data->output_scale;
543 const int32_t min = data->clip_min;
544 const int32_t max = data->clip_max;
545 const int32_t range = max - min;
546 int ch;
547 int16_t *d;
549 for (ch = 0; ch < data->num_channels; ch++)
551 struct dither_data * const dither = &dither_data[ch];
552 const int32_t *s = src[ch];
553 int i;
555 for (i = 0, d = &dst[ch]; i < count; i++, s++, d += 2)
557 int32_t output, sample;
558 int32_t random;
560 /* Noise shape and bias (for correct rounding later) */
561 sample = *s;
562 sample += dither->error[0] - dither->error[1] + dither->error[2];
563 dither->error[2] = dither->error[1];
564 dither->error[1] = dither->error[0]/2;
566 output = sample + bias;
568 /* Dither, highpass triangle PDF */
569 random = dither->random*0x0019660dL + 0x3c6ef35fL;
570 output += (random & mask) - (dither->random & mask);
571 dither->random = random;
573 /* Round sample to output range */
574 output &= ~mask;
576 /* Error feedback */
577 dither->error[0] = sample - output;
579 /* Clip */
580 if ((uint32_t)(output - min) > (uint32_t)range)
582 int32_t c = min;
583 if (output > min)
584 c += range;
585 output = c;
588 /* Quantize and store */
589 *d = output >> scale;
593 if (data->num_channels == 2)
594 return;
596 /* Have to duplicate left samples into the right channel since
597 pcm buffer and hardware is interleaved stereo */
598 d = &dst[0];
600 while (count-- > 0)
602 int16_t s = *d++;
603 *d++ = s;
608 * sample_output_new_format()
610 * set the from-native to ouput sample conversion routine
612 * !DSPPARAMSYNC
613 * needs syncing with changes to the following dsp parameters:
614 * * dsp->stereo_mode (A/V)
615 * * dither_enabled (A)
617 static void sample_output_new_format(struct dsp_config *dsp)
619 static const sample_output_fn_type sample_output_functions[] =
621 sample_output_mono,
622 sample_output_stereo,
623 sample_output_dithered,
624 sample_output_dithered
627 int out = dsp->data.num_channels - 1;
629 if (dsp == &AUDIO_DSP && dither_enabled)
630 out += 2;
632 dsp->output_samples = sample_output_functions[out];
636 * Linear interpolation resampling that introduces a one sample delay because
637 * of our inability to look into the future at the end of a frame.
639 #ifndef DSP_HAVE_ASM_RESAMPLING
640 static int dsp_downsample(int count, struct dsp_data *data,
641 const int32_t *src[], int32_t *dst[])
643 int ch = data->num_channels - 1;
644 uint32_t delta = data->resample_data.delta;
645 uint32_t phase, pos;
646 int32_t *d;
648 /* Rolled channel loop actually showed slightly faster. */
651 /* Just initialize things and not worry too much about the relatively
652 * uncommon case of not being able to spit out a sample for the frame.
654 const int32_t *s = src[ch];
655 int32_t last = data->resample_data.last_sample[ch];
657 data->resample_data.last_sample[ch] = s[count - 1];
658 d = dst[ch];
659 phase = data->resample_data.phase;
660 pos = phase >> 16;
662 /* Do we need last sample of previous frame for interpolation? */
663 if (pos > 0)
664 last = s[pos - 1];
666 while (pos < (uint32_t)count)
668 *d++ = last + FRACMUL((phase & 0xffff) << 15, s[pos] - last);
669 phase += delta;
670 pos = phase >> 16;
671 last = s[pos - 1];
674 while (--ch >= 0);
676 /* Wrap phase accumulator back to start of next frame. */
677 data->resample_data.phase = phase - (count << 16);
678 return d - dst[0];
681 static int dsp_upsample(int count, struct dsp_data *data,
682 const int32_t *src[], int32_t *dst[])
684 int ch = data->num_channels - 1;
685 uint32_t delta = data->resample_data.delta;
686 uint32_t phase, pos;
687 int32_t *d;
689 /* Rolled channel loop actually showed slightly faster. */
692 /* Should always be able to output a sample for a ratio up to RESAMPLE_RATIO */
693 const int32_t *s = src[ch];
694 int32_t last = data->resample_data.last_sample[ch];
696 data->resample_data.last_sample[ch] = s[count - 1];
697 d = dst[ch];
698 phase = data->resample_data.phase;
699 pos = phase >> 16;
701 while (pos == 0)
703 *d++ = last + FRACMUL((phase & 0xffff) << 15, s[0] - last);
704 phase += delta;
705 pos = phase >> 16;
708 while (pos < (uint32_t)count)
710 last = s[pos - 1];
711 *d++ = last + FRACMUL((phase & 0xffff) << 15, s[pos] - last);
712 phase += delta;
713 pos = phase >> 16;
716 while (--ch >= 0);
718 /* Wrap phase accumulator back to start of next frame. */
719 data->resample_data.phase = phase & 0xffff;
720 return d - dst[0];
722 #endif /* DSP_HAVE_ASM_RESAMPLING */
724 static void resampler_new_delta(struct dsp_config *dsp)
726 dsp->data.resample_data.delta = (unsigned long)
727 dsp->frequency * 65536LL / NATIVE_FREQUENCY;
729 if (dsp->frequency == NATIVE_FREQUENCY)
731 /* NOTE: If fully glitch-free transistions from no resampling to
732 resampling are desired, last_sample history should be maintained
733 even when not resampling. */
734 dsp->resample = NULL;
735 dsp->data.resample_data.phase = 0;
736 dsp->data.resample_data.last_sample[0] = 0;
737 dsp->data.resample_data.last_sample[1] = 0;
739 else if (dsp->frequency < NATIVE_FREQUENCY)
740 dsp->resample = dsp_upsample;
741 else
742 dsp->resample = dsp_downsample;
745 /* Resample count stereo samples. Updates the src array, if resampling is
746 * done, to refer to the resampled data. Returns number of stereo samples
747 * for further processing.
749 static inline int resample(struct dsp_config *dsp, int count, int32_t *src[])
751 int32_t *dst[2] =
753 &resample_buf[RESAMPLE_BUF_LEFT_CHANNEL],
754 &resample_buf[RESAMPLE_BUF_RIGHT_CHANNEL],
757 count = dsp->resample(count, &dsp->data, (const int32_t **)src, dst);
759 src[0] = dst[0];
760 src[1] = dst[dsp->data.num_channels - 1];
762 return count;
765 static void dither_init(struct dsp_config *dsp)
767 memset(dither_data, 0, sizeof (dither_data));
768 dither_bias = (1L << (dsp->frac_bits - NATIVE_DEPTH));
769 dither_mask = (1L << (dsp->frac_bits + 1 - NATIVE_DEPTH)) - 1;
772 void dsp_dither_enable(bool enable)
774 struct dsp_config *dsp = &AUDIO_DSP;
775 dither_enabled = enable;
776 sample_output_new_format(dsp);
779 /* Applies crossfeed to the stereo signal in src.
780 * Crossfeed is a process where listening over speakers is simulated. This
781 * is good for old hard panned stereo records, which might be quite fatiguing
782 * to listen to on headphones with no crossfeed.
784 #ifndef DSP_HAVE_ASM_CROSSFEED
785 static void apply_crossfeed(int count, int32_t *buf[])
787 int32_t *hist_l = &crossfeed_data.history[0];
788 int32_t *hist_r = &crossfeed_data.history[2];
789 int32_t *delay = &crossfeed_data.delay[0][0];
790 int32_t *coefs = &crossfeed_data.coefs[0];
791 int32_t gain = crossfeed_data.gain;
792 int32_t *di = crossfeed_data.index;
794 int32_t acc;
795 int32_t left, right;
796 int i;
798 for (i = 0; i < count; i++)
800 left = buf[0][i];
801 right = buf[1][i];
803 /* Filter delayed sample from left speaker */
804 acc = FRACMUL(*di, coefs[0]);
805 acc += FRACMUL(hist_l[0], coefs[1]);
806 acc += FRACMUL(hist_l[1], coefs[2]);
807 /* Save filter history for left speaker */
808 hist_l[1] = acc;
809 hist_l[0] = *di;
810 *di++ = left;
811 /* Filter delayed sample from right speaker */
812 acc = FRACMUL(*di, coefs[0]);
813 acc += FRACMUL(hist_r[0], coefs[1]);
814 acc += FRACMUL(hist_r[1], coefs[2]);
815 /* Save filter history for right speaker */
816 hist_r[1] = acc;
817 hist_r[0] = *di;
818 *di++ = right;
819 /* Now add the attenuated direct sound and write to outputs */
820 buf[0][i] = FRACMUL(left, gain) + hist_r[1];
821 buf[1][i] = FRACMUL(right, gain) + hist_l[1];
823 /* Wrap delay line index if bigger than delay line size */
824 if (di >= delay + 13*2)
825 di = delay;
827 /* Write back local copies of data we've modified */
828 crossfeed_data.index = di;
830 #endif /* DSP_HAVE_ASM_CROSSFEED */
833 * dsp_set_crossfeed(bool enable)
835 * !DSPPARAMSYNC
836 * needs syncing with changes to the following dsp parameters:
837 * * dsp->stereo_mode (A)
839 void dsp_set_crossfeed(bool enable)
841 crossfeed_enabled = enable;
842 AUDIO_DSP.apply_crossfeed = (enable && AUDIO_DSP.data.num_channels > 1)
843 ? apply_crossfeed : NULL;
846 void dsp_set_crossfeed_direct_gain(int gain)
848 crossfeed_data.gain = get_replaygain_int(gain * 10) << 7;
849 /* If gain is negative, the calculation overflowed and we need to clamp */
850 if (crossfeed_data.gain < 0)
851 crossfeed_data.gain = 0x7fffffff;
854 /* Both gains should be below 0 dB */
855 void dsp_set_crossfeed_cross_params(long lf_gain, long hf_gain, long cutoff)
857 int32_t *c = crossfeed_data.coefs;
858 long scaler = get_replaygain_int(lf_gain * 10) << 7;
860 cutoff = 0xffffffff/NATIVE_FREQUENCY*cutoff;
861 hf_gain -= lf_gain;
862 /* Divide cutoff by sqrt(10^(hf_gain/20)) to place cutoff at the -3 dB
863 * point instead of shelf midpoint. This is for compatibility with the old
864 * crossfeed shelf filter and should be removed if crossfeed settings are
865 * ever made incompatible for any other good reason.
867 cutoff = fp_div(cutoff, get_replaygain_int(hf_gain*5), 24);
868 filter_shelf_coefs(cutoff, hf_gain, false, c);
869 /* Scale coefs by LF gain and shift them to s0.31 format. We have no gains
870 * over 1 and can do this safely
872 c[0] = FRACMUL_SHL(c[0], scaler, 4);
873 c[1] = FRACMUL_SHL(c[1], scaler, 4);
874 c[2] <<= 4;
877 /* Apply a constant gain to the samples (e.g., for ReplayGain).
878 * Note that this must be called before the resampler.
880 #ifndef DSP_HAVE_ASM_APPLY_GAIN
881 static void dsp_apply_gain(int count, struct dsp_data *data, int32_t *buf[])
883 const int32_t gain = data->gain;
884 int ch;
886 for (ch = 0; ch < data->num_channels; ch++)
888 int32_t *d = buf[ch];
889 int i;
891 for (i = 0; i < count; i++)
892 d[i] = FRACMUL_SHL(d[i], gain, 8);
895 #endif /* DSP_HAVE_ASM_APPLY_GAIN */
897 /* Combine all gains to a global gain. */
898 static void set_gain(struct dsp_config *dsp)
900 /* gains are in S7.24 format */
901 dsp->data.gain = DEFAULT_GAIN;
903 /* Replay gain not relevant to voice */
904 if (dsp == &AUDIO_DSP && replaygain)
906 dsp->data.gain = replaygain;
909 if (dsp->eq_process && eq_precut)
911 dsp->data.gain = fp_mul(dsp->data.gain, eq_precut, 24);
914 #ifdef HAVE_SW_VOLUME_CONTROL
915 if (global_settings.volume < SW_VOLUME_MAX ||
916 global_settings.volume > SW_VOLUME_MIN)
918 int vol_gain = get_replaygain_int(global_settings.volume * 100);
919 dsp->data.gain = (long) (((int64_t) dsp->data.gain * vol_gain) >> 24);
921 #endif
923 if (dsp->data.gain == DEFAULT_GAIN)
925 dsp->data.gain = 0;
927 else
929 dsp->data.gain >>= 1; /* convert gain to S8.23 format */
932 dsp->apply_gain = dsp->data.gain != 0 ? dsp_apply_gain : NULL;
936 * Update the amount to cut the audio before applying the equalizer.
938 * @param precut to apply in decibels (multiplied by 10)
940 void dsp_set_eq_precut(int precut)
942 eq_precut = get_replaygain_int(precut * -10);
943 set_gain(&AUDIO_DSP);
947 * Synchronize the equalizer filter coefficients with the global settings.
949 * @param band the equalizer band to synchronize
951 void dsp_set_eq_coefs(int band)
953 const int *setting;
954 long gain;
955 unsigned long cutoff, q;
957 /* Adjust setting pointer to the band we actually want to change */
958 setting = &global_settings.eq_band0_cutoff + (band * 3);
960 /* Convert user settings to format required by coef generator functions */
961 cutoff = 0xffffffff / NATIVE_FREQUENCY * (*setting++);
962 q = *setting++;
963 gain = *setting++;
965 if (q == 0)
966 q = 1;
968 /* NOTE: The coef functions assume the EMAC unit is in fractional mode,
969 which it should be, since we're executed from the main thread. */
971 /* Assume a band is disabled if the gain is zero */
972 if (gain == 0)
974 eq_data.enabled[band] = 0;
976 else
978 if (band == 0)
979 eq_ls_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
980 else if (band == 4)
981 eq_hs_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
982 else
983 eq_pk_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
985 eq_data.enabled[band] = 1;
989 /* Apply EQ filters to those bands that have got it switched on. */
990 static void eq_process(int count, int32_t *buf[])
992 static const int shifts[] =
994 EQ_SHELF_SHIFT, /* low shelf */
995 EQ_PEAK_SHIFT, /* peaking */
996 EQ_PEAK_SHIFT, /* peaking */
997 EQ_PEAK_SHIFT, /* peaking */
998 EQ_SHELF_SHIFT, /* high shelf */
1000 unsigned int channels = AUDIO_DSP.data.num_channels;
1001 int i;
1003 /* filter configuration currently is 1 low shelf filter, 3 band peaking
1004 filters and 1 high shelf filter, in that order. we need to know this
1005 so we can choose the correct shift factor.
1007 for (i = 0; i < 5; i++)
1009 if (!eq_data.enabled[i])
1010 continue;
1011 eq_filter(buf, &eq_data.filters[i], count, channels, shifts[i]);
1016 * Use to enable the equalizer.
1018 * @param enable true to enable the equalizer
1020 void dsp_set_eq(bool enable)
1022 AUDIO_DSP.eq_process = enable ? eq_process : NULL;
1023 set_gain(&AUDIO_DSP);
1026 static void dsp_set_stereo_width(int value)
1028 long width, straight, cross;
1030 width = value * 0x7fffff / 100;
1032 if (value <= 100)
1034 straight = (0x7fffff + width) / 2;
1035 cross = straight - width;
1037 else
1039 /* straight = (1 + width) / (2 * width) */
1040 straight = ((int64_t)(0x7fffff + width) << 22) / width;
1041 cross = straight - 0x7fffff;
1044 dsp_sw_gain = straight << 8;
1045 dsp_sw_cross = cross << 8;
1049 * Implements the different channel configurations and stereo width.
1052 /* SOUND_CHAN_STEREO mode is a noop so has no function - just outline one for
1053 * completeness. */
1054 #if 0
1055 static void channels_process_sound_chan_stereo(int count, int32_t *buf[])
1057 /* The channels are each just themselves */
1058 (void)count; (void)buf;
1060 #endif
1062 #ifndef DSP_HAVE_ASM_SOUND_CHAN_MONO
1063 static void channels_process_sound_chan_mono(int count, int32_t *buf[])
1065 int32_t *sl = buf[0], *sr = buf[1];
1067 while (count-- > 0)
1069 int32_t lr = *sl/2 + *sr/2;
1070 *sl++ = lr;
1071 *sr++ = lr;
1074 #endif /* DSP_HAVE_ASM_SOUND_CHAN_MONO */
1076 #ifndef DSP_HAVE_ASM_SOUND_CHAN_CUSTOM
1077 static void channels_process_sound_chan_custom(int count, int32_t *buf[])
1079 const int32_t gain = dsp_sw_gain;
1080 const int32_t cross = dsp_sw_cross;
1081 int32_t *sl = buf[0], *sr = buf[1];
1083 while (count-- > 0)
1085 int32_t l = *sl;
1086 int32_t r = *sr;
1087 *sl++ = FRACMUL(l, gain) + FRACMUL(r, cross);
1088 *sr++ = FRACMUL(r, gain) + FRACMUL(l, cross);
1091 #endif /* DSP_HAVE_ASM_SOUND_CHAN_CUSTOM */
1093 static void channels_process_sound_chan_mono_left(int count, int32_t *buf[])
1095 /* Just copy over the other channel */
1096 memcpy(buf[1], buf[0], count * sizeof (*buf));
1099 static void channels_process_sound_chan_mono_right(int count, int32_t *buf[])
1101 /* Just copy over the other channel */
1102 memcpy(buf[0], buf[1], count * sizeof (*buf));
1105 #ifndef DSP_HAVE_ASM_SOUND_CHAN_KARAOKE
1106 static void channels_process_sound_chan_karaoke(int count, int32_t *buf[])
1108 int32_t *sl = buf[0], *sr = buf[1];
1110 while (count-- > 0)
1112 int32_t ch = *sl/2 - *sr/2;
1113 *sl++ = ch;
1114 *sr++ = -ch;
1117 #endif /* DSP_HAVE_ASM_SOUND_CHAN_KARAOKE */
1119 static void dsp_set_channel_config(int value)
1121 static const channels_process_fn_type channels_process_functions[] =
1123 /* SOUND_CHAN_STEREO = All-purpose index for no channel processing */
1124 [SOUND_CHAN_STEREO] = NULL,
1125 [SOUND_CHAN_MONO] = channels_process_sound_chan_mono,
1126 [SOUND_CHAN_CUSTOM] = channels_process_sound_chan_custom,
1127 [SOUND_CHAN_MONO_LEFT] = channels_process_sound_chan_mono_left,
1128 [SOUND_CHAN_MONO_RIGHT] = channels_process_sound_chan_mono_right,
1129 [SOUND_CHAN_KARAOKE] = channels_process_sound_chan_karaoke,
1132 if ((unsigned)value >= ARRAYLEN(channels_process_functions) ||
1133 AUDIO_DSP.stereo_mode == STEREO_MONO)
1135 value = SOUND_CHAN_STEREO;
1138 /* This doesn't apply to voice */
1139 channels_mode = value;
1140 AUDIO_DSP.channels_process = channels_process_functions[value];
1143 #if CONFIG_CODEC == SWCODEC
1145 #ifdef HAVE_SW_TONE_CONTROLS
1146 static void set_tone_controls(void)
1148 filter_bishelf_coefs(0xffffffff/NATIVE_FREQUENCY*200,
1149 0xffffffff/NATIVE_FREQUENCY*3500,
1150 bass, treble, -prescale,
1151 AUDIO_DSP.tone_filter.coefs);
1152 /* Sync the voice dsp coefficients */
1153 memcpy(&VOICE_DSP.tone_filter.coefs, AUDIO_DSP.tone_filter.coefs,
1154 sizeof (VOICE_DSP.tone_filter.coefs));
1156 #endif
1158 /* Hook back from firmware/ part of audio, which can't/shouldn't call apps/
1159 * code directly.
1161 int dsp_callback(int msg, intptr_t param)
1163 switch (msg)
1165 #ifdef HAVE_SW_TONE_CONTROLS
1166 case DSP_CALLBACK_SET_PRESCALE:
1167 prescale = param;
1168 set_tone_controls();
1169 break;
1170 /* prescaler is always set after calling any of these, so we wait with
1171 * calculating coefs until the above case is hit.
1173 case DSP_CALLBACK_SET_BASS:
1174 bass = param;
1175 break;
1176 case DSP_CALLBACK_SET_TREBLE:
1177 treble = param;
1178 break;
1179 #ifdef HAVE_SW_VOLUME_CONTROL
1180 case DSP_CALLBACK_SET_SW_VOLUME:
1181 set_gain(&AUDIO_DSP);
1182 break;
1183 #endif
1184 #endif
1185 case DSP_CALLBACK_SET_CHANNEL_CONFIG:
1186 dsp_set_channel_config(param);
1187 break;
1188 case DSP_CALLBACK_SET_STEREO_WIDTH:
1189 dsp_set_stereo_width(param);
1190 break;
1191 default:
1192 break;
1194 return 0;
1196 #endif
1198 /* Process and convert src audio to dst based on the DSP configuration,
1199 * reading count number of audio samples. dst is assumed to be large
1200 * enough; use dsp_output_count() to get the required number. src is an
1201 * array of pointers; for mono and interleaved stereo, it contains one
1202 * pointer to the start of the audio data and the other is ignored; for
1203 * non-interleaved stereo, it contains two pointers, one for each audio
1204 * channel. Returns number of bytes written to dst.
1206 int dsp_process(struct dsp_config *dsp, char *dst, const char *src[], int count)
1208 int32_t *tmp[2];
1209 static long last_yield;
1210 long tick;
1211 int written = 0;
1213 #if defined(CPU_COLDFIRE)
1214 /* set emac unit for dsp processing, and save old macsr, we're running in
1215 codec thread context at this point, so can't clobber it */
1216 unsigned long old_macsr = coldfire_get_macsr();
1217 coldfire_set_macsr(EMAC_FRACTIONAL | EMAC_SATURATE);
1218 #endif
1220 if (new_gain)
1221 dsp_set_replaygain(); /* Gain has changed */
1223 /* Perform at least one yield before starting */
1224 last_yield = current_tick;
1225 yield();
1227 /* Testing function pointers for NULL is preferred since the pointer
1228 will be preloaded to be used for the call if not. */
1229 while (count > 0)
1231 int samples = MIN(sample_buf_count/2, count);
1232 count -= samples;
1234 dsp->input_samples(samples, src, tmp);
1236 if (dsp->tdspeed_active)
1237 samples = tdspeed_doit(tmp, samples);
1239 int chunk_offset = 0;
1240 while (samples > 0)
1242 int32_t *t2[2];
1243 t2[0] = tmp[0]+chunk_offset;
1244 t2[1] = tmp[1]+chunk_offset;
1246 int chunk = MIN(sample_buf_count/2, samples);
1247 chunk_offset += chunk;
1248 samples -= chunk;
1250 if (dsp->apply_gain)
1251 dsp->apply_gain(chunk, &dsp->data, t2);
1253 if (dsp->resample && (chunk = resample(dsp, chunk, t2)) <= 0)
1254 break; /* I'm pretty sure we're downsampling here */
1256 if (dsp->apply_crossfeed)
1257 dsp->apply_crossfeed(chunk, t2);
1259 if (dsp->eq_process)
1260 dsp->eq_process(chunk, t2);
1262 #ifdef HAVE_SW_TONE_CONTROLS
1263 if ((bass | treble) != 0)
1264 eq_filter(t2, &dsp->tone_filter, chunk,
1265 dsp->data.num_channels, FILTER_BISHELF_SHIFT);
1266 #endif
1268 if (dsp->channels_process)
1269 dsp->channels_process(chunk, t2);
1271 if (dsp->compressor_process)
1272 chunk = dsp->compressor_process(chunk, t2);
1274 dsp->output_samples(chunk, &dsp->data, (const int32_t **)t2, (int16_t *)dst);
1276 written += chunk;
1277 dst += chunk * sizeof (int16_t) * 2;
1279 /* yield at least once each tick */
1280 tick = current_tick;
1281 if (TIME_AFTER(tick, last_yield))
1283 last_yield = tick;
1284 yield();
1289 #if defined(CPU_COLDFIRE)
1290 /* set old macsr again */
1291 coldfire_set_macsr(old_macsr);
1292 #endif
1293 return written;
1296 /* Given count number of input samples, calculate the maximum number of
1297 * samples of output data that would be generated (the calculation is not
1298 * entirely exact and rounds upwards to be on the safe side; during
1299 * resampling, the number of samples generated depends on the current state
1300 * of the resampler).
1302 /* dsp_input_size MUST be called afterwards */
1303 int dsp_output_count(struct dsp_config *dsp, int count)
1305 if (dsp->tdspeed_active)
1306 count = tdspeed_est_output_size();
1307 if (dsp->resample)
1309 count = (int)(((unsigned long)count * NATIVE_FREQUENCY
1310 + (dsp->frequency - 1)) / dsp->frequency);
1313 /* Now we have the resampled sample count which must not exceed
1314 * RESAMPLE_BUF_RIGHT_CHANNEL to avoid resample buffer overflow. One
1315 * must call dsp_input_count() to get the correct input sample
1316 * count.
1318 if (count > RESAMPLE_BUF_RIGHT_CHANNEL)
1319 count = RESAMPLE_BUF_RIGHT_CHANNEL;
1321 return count;
1324 /* Given count output samples, calculate number of input samples
1325 * that would be consumed in order to fill the output buffer.
1327 int dsp_input_count(struct dsp_config *dsp, int count)
1329 /* count is now the number of resampled input samples. Convert to
1330 original input samples. */
1331 if (dsp->resample)
1333 /* Use the real resampling delta =
1334 * dsp->frequency * 65536 / NATIVE_FREQUENCY, and
1335 * round towards zero to avoid buffer overflows. */
1336 count = (int)(((unsigned long)count *
1337 dsp->data.resample_data.delta) >> 16);
1340 if (dsp->tdspeed_active)
1341 count = tdspeed_est_input_size(count);
1343 return count;
1346 static void dsp_set_gain_var(long *var, long value)
1348 *var = value;
1349 new_gain = true;
1352 static void dsp_update_functions(struct dsp_config *dsp)
1354 sample_input_new_format(dsp);
1355 sample_output_new_format(dsp);
1356 if (dsp == &AUDIO_DSP)
1357 dsp_set_crossfeed(crossfeed_enabled);
1360 intptr_t dsp_configure(struct dsp_config *dsp, int setting, intptr_t value)
1362 switch (setting)
1364 case DSP_MYDSP:
1365 switch (value)
1367 case CODEC_IDX_AUDIO:
1368 return (intptr_t)&AUDIO_DSP;
1369 case CODEC_IDX_VOICE:
1370 return (intptr_t)&VOICE_DSP;
1371 default:
1372 return (intptr_t)NULL;
1375 case DSP_SET_FREQUENCY:
1376 memset(&dsp->data.resample_data, 0, sizeof (dsp->data.resample_data));
1377 /* Fall through!!! */
1378 case DSP_SWITCH_FREQUENCY:
1379 dsp->codec_frequency = (value == 0) ? NATIVE_FREQUENCY : value;
1380 /* Account for playback speed adjustment when setting dsp->frequency
1381 if we're called from the main audio thread. Voice UI thread should
1382 not need this feature.
1384 if (dsp == &AUDIO_DSP)
1385 dsp->frequency = pitch_ratio * dsp->codec_frequency / PITCH_SPEED_100;
1386 else
1387 dsp->frequency = dsp->codec_frequency;
1389 resampler_new_delta(dsp);
1390 tdspeed_setup(dsp);
1391 break;
1393 case DSP_SET_SAMPLE_DEPTH:
1394 dsp->sample_depth = value;
1396 if (dsp->sample_depth <= NATIVE_DEPTH)
1398 dsp->frac_bits = WORD_FRACBITS;
1399 dsp->sample_bytes = sizeof (int16_t); /* samples are 16 bits */
1400 dsp->data.clip_max = ((1 << WORD_FRACBITS) - 1);
1401 dsp->data.clip_min = -((1 << WORD_FRACBITS));
1403 else
1405 dsp->frac_bits = value;
1406 dsp->sample_bytes = sizeof (int32_t); /* samples are 32 bits */
1407 dsp->data.clip_max = (1 << value) - 1;
1408 dsp->data.clip_min = -(1 << value);
1411 dsp->data.output_scale = dsp->frac_bits + 1 - NATIVE_DEPTH;
1412 sample_input_new_format(dsp);
1413 dither_init(dsp);
1414 break;
1416 case DSP_SET_STEREO_MODE:
1417 dsp->stereo_mode = value;
1418 dsp->data.num_channels = value == STEREO_MONO ? 1 : 2;
1419 dsp_update_functions(dsp);
1420 tdspeed_setup(dsp);
1421 break;
1423 case DSP_RESET:
1424 dsp->stereo_mode = STEREO_NONINTERLEAVED;
1425 dsp->data.num_channels = 2;
1426 dsp->sample_depth = NATIVE_DEPTH;
1427 dsp->frac_bits = WORD_FRACBITS;
1428 dsp->sample_bytes = sizeof (int16_t);
1429 dsp->data.output_scale = dsp->frac_bits + 1 - NATIVE_DEPTH;
1430 dsp->data.clip_max = ((1 << WORD_FRACBITS) - 1);
1431 dsp->data.clip_min = -((1 << WORD_FRACBITS));
1432 dsp->codec_frequency = dsp->frequency = NATIVE_FREQUENCY;
1434 if (dsp == &AUDIO_DSP)
1436 track_gain = 0;
1437 album_gain = 0;
1438 track_peak = 0;
1439 album_peak = 0;
1440 new_gain = true;
1443 dsp_update_functions(dsp);
1444 resampler_new_delta(dsp);
1445 tdspeed_setup(dsp);
1446 if (dsp == &AUDIO_DSP)
1447 release_gain = (1 << 24);
1448 break;
1450 case DSP_FLUSH:
1451 memset(&dsp->data.resample_data, 0,
1452 sizeof (dsp->data.resample_data));
1453 resampler_new_delta(dsp);
1454 dither_init(dsp);
1455 tdspeed_setup(dsp);
1456 if (dsp == &AUDIO_DSP)
1457 release_gain = (1 << 24);
1458 break;
1460 case DSP_SET_TRACK_GAIN:
1461 if (dsp == &AUDIO_DSP)
1462 dsp_set_gain_var(&track_gain, value);
1463 break;
1465 case DSP_SET_ALBUM_GAIN:
1466 if (dsp == &AUDIO_DSP)
1467 dsp_set_gain_var(&album_gain, value);
1468 break;
1470 case DSP_SET_TRACK_PEAK:
1471 if (dsp == &AUDIO_DSP)
1472 dsp_set_gain_var(&track_peak, value);
1473 break;
1475 case DSP_SET_ALBUM_PEAK:
1476 if (dsp == &AUDIO_DSP)
1477 dsp_set_gain_var(&album_peak, value);
1478 break;
1480 default:
1481 return 0;
1484 return 1;
1487 void dsp_set_replaygain(void)
1489 long gain = 0;
1491 new_gain = false;
1493 if ((global_settings.replaygain_type != REPLAYGAIN_OFF) ||
1494 global_settings.replaygain_noclip)
1496 bool track_mode = get_replaygain_mode(track_gain != 0,
1497 album_gain != 0) == REPLAYGAIN_TRACK;
1498 long peak = (track_mode || !album_peak) ? track_peak : album_peak;
1500 if (global_settings.replaygain_type != REPLAYGAIN_OFF)
1502 gain = (track_mode || !album_gain) ? track_gain : album_gain;
1504 if (global_settings.replaygain_preamp)
1506 long preamp = get_replaygain_int(
1507 global_settings.replaygain_preamp * 10);
1509 gain = (long) (((int64_t) gain * preamp) >> 24);
1513 if (gain == 0)
1515 /* So that noclip can work even with no gain information. */
1516 gain = DEFAULT_GAIN;
1519 if (global_settings.replaygain_noclip && (peak != 0)
1520 && ((((int64_t) gain * peak) >> 24) >= DEFAULT_GAIN))
1522 gain = (((int64_t) DEFAULT_GAIN << 24) / peak);
1525 if (gain == DEFAULT_GAIN)
1527 /* Nothing to do, disable processing. */
1528 gain = 0;
1532 /* Store in S7.24 format to simplify calculations. */
1533 replaygain = gain;
1534 set_gain(&AUDIO_DSP);
1537 /** SET COMPRESSOR
1538 * Called by the menu system to configure the compressor process */
1539 void dsp_set_compressor(int c_threshold, int c_ratio, int c_gain,
1540 int c_knee, int c_release)
1542 bool changed = false;
1543 bool active = (c_threshold < 0);
1544 const int comp_ratio[] = {2, 4, 6, 10, 0};
1545 int new_ratio = comp_ratio[c_ratio];
1546 bool new_knee = (c_knee == 1);
1547 int new_release = c_release * NATIVE_FREQUENCY / 1000;
1549 if (c_menu.threshold != c_threshold)
1551 changed = true;
1552 c_menu.threshold = c_threshold;
1553 logf(" Compressor Threshold: %d dB\tEnabled: %s",
1554 c_menu.threshold, active ? "Yes" : "No");
1557 if (c_menu.ratio != new_ratio)
1559 changed = true;
1560 c_menu.ratio = new_ratio;
1561 if (c_menu.ratio)
1563 logf(" Compressor Ratio: %d:1", c_menu.ratio);
1565 else
1567 logf(" Compressor Ratio: Limit");
1571 if (c_menu.gain != c_gain)
1573 changed = true;
1574 c_menu.gain = c_gain;
1575 if (c_menu.gain >= 0)
1577 logf(" Compressor Makeup Gain: %d dB", c_menu.gain);
1579 else
1581 logf(" Compressor Makeup Gain: Auto");
1585 if (c_menu.soft_knee != new_knee)
1587 changed = true;
1588 c_menu.soft_knee = new_knee;
1589 logf(" Compressor Knee: %s", c_menu.soft_knee==1?"Soft":"Hard");
1592 if (c_menu.release != new_release)
1594 changed = true;
1595 c_menu.release = new_release;
1596 logf(" Compressor Release: %d", c_menu.release);
1599 if (changed && active)
1601 /* configure variables for compressor operation */
1602 int i;
1603 const int32_t db[] ={0x000000, /* positive db equivalents in S15.16 format */
1604 0x241FA4, 0x1E1A5E, 0x1A94C8, 0x181518, 0x1624EA, 0x148F82, 0x1338BD, 0x120FD2,
1605 0x1109EB, 0x101FA4, 0x0F4BB6, 0x0E8A3C, 0x0DD840, 0x0D3377, 0x0C9A0E, 0x0C0A8C,
1606 0x0B83BE, 0x0B04A5, 0x0A8C6C, 0x0A1A5E, 0x09ADE1, 0x094670, 0x08E398, 0x0884F6,
1607 0x082A30, 0x07D2FA, 0x077F0F, 0x072E31, 0x06E02A, 0x0694C8, 0x064BDF, 0x060546,
1608 0x05C0DA, 0x057E78, 0x053E03, 0x04FF5F, 0x04C273, 0x048726, 0x044D64, 0x041518,
1609 0x03DE30, 0x03A89B, 0x037448, 0x03412A, 0x030F32, 0x02DE52, 0x02AE80, 0x027FB0,
1610 0x0251D6, 0x0224EA, 0x01F8E2, 0x01CDB4, 0x01A359, 0x0179C9, 0x0150FC, 0x0128EB,
1611 0x010190, 0x00DAE4, 0x00B4E1, 0x008F82, 0x006AC1, 0x004699, 0x002305};
1613 struct curve_point
1615 int32_t db; /* S15.16 format */
1616 int32_t offset; /* S15.16 format */
1617 } db_curve[4];
1619 /** Set up the shape of the compression curve first as decibel values*/
1620 /* db_curve[0] = bottom of knee
1621 [1] = threshold
1622 [2] = top of knee
1623 [3] = 0 db input */
1624 db_curve[1].db = c_menu.threshold << 16;
1625 if (c_menu.soft_knee)
1627 /* bottom of knee is 3dB below the threshold for soft knee*/
1628 db_curve[0].db = db_curve[1].db - (3 << 16);
1629 /* top of knee is 3dB above the threshold for soft knee */
1630 db_curve[2].db = db_curve[1].db + (3 << 16);
1631 if (c_menu.ratio)
1632 /* offset = -3db * (ratio - 1) / ratio */
1633 db_curve[2].offset = (int32_t)((long long)(-3 << 16)
1634 * (c_menu.ratio - 1) / c_menu.ratio);
1635 else
1636 /* offset = -3db for hard limit */
1637 db_curve[2].offset = (-3 << 16);
1639 else
1641 /* bottom of knee is at the threshold for hard knee */
1642 db_curve[0].db = c_menu.threshold << 16;
1643 /* top of knee is at the threshold for hard knee */
1644 db_curve[2].db = c_menu.threshold << 16;
1645 db_curve[2].offset = 0;
1647 /* 0db input is also max offset point (most compression) */
1648 if (c_menu.ratio)
1649 /* offset = threshold * (ratio - 1) / ratio */
1650 db_curve[3].offset = (int32_t)((long long)(c_menu.threshold << 16)
1651 * (c_menu.ratio - 1) / c_menu.ratio);
1652 else
1653 /* offset = threshold for hard limit */
1654 db_curve[3].offset = (c_menu.threshold << 16);
1656 /* Now set up the comp_curve table with compression offsets in the form
1657 of gain factors in S7.24 format */
1658 comp_curve[0] = (1 << 24);
1659 for (i = 1; i < 64; i++)
1661 int32_t this_db = -db[i];
1662 /* no compression below the knee */
1663 if (this_db <= db_curve[0].db)
1664 comp_curve[i] = (1 << 24);
1666 /* if soft knee and below top of knee, interpolate along soft knee slope */
1667 else if (c_menu.soft_knee && (this_db <= db_curve[2].db))
1668 comp_curve[i] = fp_factor(fp_mul(((this_db - db_curve[0].db) / 6),
1669 db_curve[2].offset, 16), 16) << 8;
1671 /* interpolate along ratio slope above the knee */
1672 else
1673 comp_curve[i] = fp_factor(fp_mul(fp_div((this_db - db_curve[1].db),
1674 -db_curve[1].db, 16), db_curve[3].offset, 16), 16) << 8;
1676 comp_curve[64] = fp_factor(db_curve[3].offset, 16) << 8;
1678 #if defined(SIMULATOR) && defined(LOGF_ENABLE)
1679 logf("\n *** Compression Offsets ***");
1680 /* some settings for display only, not used in calculations */
1681 db_curve[0].offset = 0;
1682 db_curve[1].offset = 0;
1683 db_curve[3].db = 0;
1685 for (i = 0; i <= 3; i++)
1687 logf("Curve[%d]: db: % .1f\toffset: % .4f", i, (float)db_curve[i].db / (1 << 16),
1688 (float)db_curve[i].offset / (1 << 16));
1691 logf("\nGain factors:");
1692 for (i = 1; i <= 64; i++)
1694 debugf("%02d: %.6f ", i, (float)comp_curve[i] / (1 << 24));
1695 if (i % 4 == 0) debugf("\n");
1697 #endif
1699 /* if using auto peak, then makeup gain is max offset - .1dB headroom */
1700 int32_t db_makeup = (c_menu.gain == -1) ?
1701 -(db_curve[3].offset) - 0x199A : c_menu.gain << 16;
1702 comp_makeup_gain = fp_factor(db_makeup, 16) << 8;
1703 logf("Makeup gain:\t%.6f", (float)comp_makeup_gain / (1 << 24));
1705 /* calculate per-sample gain change a rate of 10db over release time */
1706 comp_rel_slope = 0xAF0BB2 / c_menu.release;
1707 logf("Release slope:\t%.6f", (float)comp_rel_slope / (1 << 24));
1709 release_gain = (1 << 24);
1712 /* enable/disable the compressor */
1713 AUDIO_DSP.compressor_process = active ? compressor_process : NULL;
1716 /** GET COMPRESSION GAIN
1717 * Returns the required gain factor in S7.24 format in order to compress the
1718 * sample in accordance with the compression curve. Always 1 or less.
1720 static inline int32_t get_compression_gain(int32_t sample)
1722 const int frac_bits = AUDIO_DSP.frac_bits;
1724 /* sample must be positive */
1725 if (sample < 0)
1726 sample = -sample - 1;
1728 /* shift sample into 22 frac bit range */
1729 if (frac_bits > 22)
1730 sample >>= (frac_bits - 22);
1731 if (frac_bits < 22)
1732 sample <<= (22 - frac_bits);
1734 /* index is 6 MSB, rem is 16 LSB */
1735 int index = sample >> 16;
1736 int rem = (sample & 0xFFFF) << 8;
1738 /* interpolate from the compression curve */
1739 return comp_curve[index] + (int32_t)FRACMUL_SHL((comp_curve[index + 1]
1740 - comp_curve[index]), rem, 7);
1743 /** COMPRESSOR PROCESS
1744 * Changes the gain of the samples according to the compressor curve
1746 static int compressor_process(int count, int32_t *buf[])
1748 const int num_chan = AUDIO_DSP.data.num_channels;
1749 const int32_t fp_one = (1 << 24);
1751 int32_t sample_gain, /* S7.24 format */
1752 this_gain; /* S7.24 format */
1753 int i, ch;
1755 /* Step forward through the output buffer, and modify the offset values
1756 * to establish a smooth, slow release slope.*/
1757 for (i = 0; i < count; i++)
1759 sample_gain = fp_one;
1760 for (ch = 0; ch < num_chan; ch++)
1762 this_gain = get_compression_gain(buf[ch][i]);
1763 if (this_gain < sample_gain)
1764 sample_gain = this_gain;
1766 /* if no release slope, only apply makeup gain */
1767 if ((sample_gain == fp_one) && (release_gain == fp_one))
1768 gain_buffer[i] = comp_makeup_gain;
1769 else
1771 /* if larger offset, start release slope */
1772 if (sample_gain <= release_gain)
1773 release_gain = sample_gain;
1774 else /* keep sloping */
1776 if (release_gain < (fp_one - comp_rel_slope))
1777 release_gain += comp_rel_slope;
1778 else
1779 release_gain = fp_one;
1781 /* store offset with release and also apply makeup gain */
1782 if ((release_gain == fp_one) && (comp_makeup_gain == fp_one))
1783 gain_buffer[i] = fp_one;
1784 else
1785 gain_buffer[i] = FRACMUL_SHL(release_gain, comp_makeup_gain, 7);
1789 /* Implement the compressor: apply those gain factors to the output
1790 * buffer samples */
1792 for (i = 0; i < count; i++)
1794 if (gain_buffer[i] != fp_one)
1796 for (ch = 0; ch < num_chan; ch++)
1797 buf[ch][i] = FRACMUL_SHL(buf[ch][i], gain_buffer[i], 7);
1800 return count;