Fix red: remove buffer from IRAM
[kugel-rb.git] / apps / dsp.c
blobe7a6a9182a7a9b3f2e77af6173e27f4531a105e6
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 /* Include header with defines which functions are implemented in assembly
141 code for the target */
142 #include <dsp_asm.h>
144 /* Typedefs keep things much neater in this case */
145 typedef void (*sample_input_fn_type)(int count, const char *src[],
146 int32_t *dst[]);
147 typedef int (*resample_fn_type)(int count, struct dsp_data *data,
148 const int32_t *src[], int32_t *dst[]);
149 typedef void (*sample_output_fn_type)(int count, struct dsp_data *data,
150 const int32_t *src[], int16_t *dst);
152 /* Single-DSP channel processing in place */
153 typedef void (*channels_process_fn_type)(int count, int32_t *buf[]);
154 /* DSP local channel processing in place */
155 typedef void (*channels_process_dsp_fn_type)(int count, struct dsp_data *data,
156 int32_t *buf[]);
157 /* DSP processes that return a value */
158 typedef int (*return_fn_type)(int count, int32_t *buf[]);
161 ***************************************************************************/
163 struct dsp_config
165 struct dsp_data data; /* Config members for use in asm routines */
166 long codec_frequency; /* Sample rate of data coming from the codec */
167 long frequency; /* Effective sample rate after pitch shift (if any) */
168 int sample_depth;
169 int sample_bytes;
170 int stereo_mode;
171 int32_t tdspeed_percent; /* Speed% * PITCH_SPEED_PRECISION */
172 bool tdspeed_active; /* Timestretch is in use */
173 int frac_bits;
174 long limiter_preamp; /* limiter amp gain in S7.24 format */
175 #ifdef HAVE_SW_TONE_CONTROLS
176 /* Filter struct for software bass/treble controls */
177 struct eqfilter tone_filter;
178 #endif
179 /* Functions that change depending upon settings - NULL if stage is
180 disabled */
181 sample_input_fn_type input_samples;
182 resample_fn_type resample;
183 sample_output_fn_type output_samples;
184 /* These will be NULL for the voice codec and is more economical that
185 way */
186 channels_process_dsp_fn_type apply_gain;
187 channels_process_fn_type apply_crossfeed;
188 channels_process_fn_type eq_process;
189 channels_process_fn_type channels_process;
190 return_fn_type limiter_process;
193 /* General DSP config */
194 static struct dsp_config dsp_conf[2] IBSS_ATTR; /* 0=A, 1=V */
195 /* Dithering */
196 static struct dither_data dither_data[2] IBSS_ATTR; /* 0=left, 1=right */
197 static long dither_mask IBSS_ATTR;
198 static long dither_bias IBSS_ATTR;
199 /* Crossfeed */
200 struct crossfeed_data crossfeed_data IDATA_ATTR = /* A */
202 .index = (int32_t *)crossfeed_data.delay
205 /* Equalizer */
206 static struct eq_state eq_data; /* A */
208 /* Software tone controls */
209 #ifdef HAVE_SW_TONE_CONTROLS
210 static int prescale; /* A/V */
211 static int bass; /* A/V */
212 static int treble; /* A/V */
213 #endif
215 /* Settings applicable to audio codec only */
216 static int32_t pitch_ratio = PITCH_SPEED_100;
217 static int channels_mode;
218 long dsp_sw_gain;
219 long dsp_sw_cross;
220 static bool dither_enabled;
221 static long eq_precut;
222 static long track_gain;
223 static bool new_gain;
224 static long album_gain;
225 static long track_peak;
226 static long album_peak;
227 static long replaygain;
228 static bool crossfeed_enabled;
230 #define AUDIO_DSP (dsp_conf[CODEC_IDX_AUDIO])
231 #define VOICE_DSP (dsp_conf[CODEC_IDX_VOICE])
233 /* The internal format is 32-bit samples, non-interleaved, stereo. This
234 * format is similar to the raw output from several codecs, so the amount
235 * of copying needed is minimized for that case.
238 #define RESAMPLE_RATIO 4 /* Enough for 11,025 Hz -> 44,100 Hz */
240 static int32_t small_sample_buf[SMALL_SAMPLE_BUF_COUNT] IBSS_ATTR;
241 static int32_t small_resample_buf[SMALL_SAMPLE_BUF_COUNT * RESAMPLE_RATIO] IBSS_ATTR;
243 static int32_t *big_sample_buf = NULL;
244 static int32_t *big_resample_buf = NULL;
245 static int big_sample_buf_count = -1; /* -1=unknown, 0=not available */
247 static int sample_buf_count;
248 static int32_t *sample_buf;
249 static int32_t *resample_buf;
251 #define SAMPLE_BUF_LEFT_CHANNEL 0
252 #define SAMPLE_BUF_RIGHT_CHANNEL (sample_buf_count/2)
253 #define RESAMPLE_BUF_LEFT_CHANNEL 0
254 #define RESAMPLE_BUF_RIGHT_CHANNEL (sample_buf_count/2 * RESAMPLE_RATIO)
256 /* limiter */
257 /* MAX_COUNT is largest possible sample count in limiter_process. This is
258 needed in case time stretch makes the count in dsp_process larger than
259 the limiter buffer. */
260 #define MAX_COUNT MAX(SMALL_SAMPLE_BUF_COUNT * RESAMPLE_RATIO / 2, LIMITER_BUFFER_SIZE)
261 static int count_adjust;
262 static bool limiter_buffer_active;
263 static bool limiter_buffer_full;
264 static bool limiter_buffer_emptying;
265 static int32_t limiter_buffer[2][LIMITER_BUFFER_SIZE] IBSS_ATTR;
266 static int32_t *start_lim_buf[2] IBSS_ATTR,
267 *end_lim_buf[2] IBSS_ATTR;
268 static uint16_t lim_buf_peak[LIMITER_BUFFER_SIZE] IBSS_ATTR;
269 static uint16_t *start_peak IBSS_ATTR,
270 *end_peak IBSS_ATTR;
271 static uint16_t out_buf_peak[MAX_COUNT];
272 static uint16_t *out_buf_peak_index IBSS_ATTR;
273 static uint16_t release_peak IBSS_ATTR;
274 static int32_t in_samp IBSS_ATTR,
275 samp0 IBSS_ATTR;
277 static void reset_limiter_buffer(struct dsp_config *dsp);
278 static int limiter_buffer_count(bool buf_count);
279 static int limiter_process(int count, int32_t *buf[]);
280 static uint16_t get_peak_value(int32_t sample);
282 /* The clip_steps array essentially stores the results of fp_factor from
283 * 0 to 12 dB, in 48 equal steps, in S3.28 format. */
284 const long clip_steps[49] ICONST_ATTR = { 0x10000000,
285 0x10779AFA, 0x10F2B409, 0x1171654C, 0x11F3C9A0, 0x1279FCAD,
286 0x13041AE9, 0x139241A2, 0x14248EF9, 0x14BB21F9, 0x15561A92,
287 0x15F599A0, 0x1699C0F9, 0x1742B36B, 0x17F094CE, 0x18A38A01,
288 0x195BB8F9, 0x1A1948C5, 0x1ADC619B, 0x1BA52CDC, 0x1C73D51D,
289 0x1D488632, 0x1E236D3A, 0x1F04B8A1, 0x1FEC982C, 0x20DB3D0E,
290 0x21D0D9E2, 0x22CDA2BE, 0x23D1CD41, 0x24DD9099, 0x25F12590,
291 0x270CC693, 0x2830AFD3, 0x295D1F37, 0x2A925471, 0x2BD0911F,
292 0x2D1818B3, 0x2E6930AD, 0x2FC42095, 0x312931EC, 0x3298B072,
293 0x3412EA24, 0x35982F3A, 0x3728D22E, 0x38C52808, 0x3A6D8847,
294 0x3C224CD9, 0x3DE3D264, 0x3FB2783F};
295 /* The gain_steps array essentially stores the results of fp_factor from
296 * 0 to -12 dB, in 48 equal steps, in S3.28 format. */
297 const long gain_steps[49] ICONST_ATTR = { 0x10000000,
298 0xF8BC9C0, 0xF1ADF94, 0xEAD2988, 0xE429058, 0xDDAFD68,
299 0xD765AC1, 0xD149309, 0xCB59186, 0xC594210, 0xBFF9112,
300 0xBA86B88, 0xB53BEF5, 0xB017965, 0xAB18964, 0xA63DDFE,
301 0xA1866BA, 0x9CF1397, 0x987D507, 0x9429BEE, 0x8FF599E,
302 0x8BDFFD3, 0x87E80B0, 0x840CEBE, 0x804DCE8, 0x7CA9E76,
303 0x792070E, 0x75B0AB0, 0x7259DB2, 0x6F1B4BF, 0x6BF44D5,
304 0x68E4342, 0x65EA5A0, 0x63061D6, 0x6036E15, 0x5D7C0D3,
305 0x5AD50CE, 0x5841505, 0x55C04B8, 0x535176A, 0x50F44D9,
306 0x4EA84FE, 0x4C6D00E, 0x4A41E78, 0x48268DF, 0x461A81C,
307 0x441D53E, 0x422E985, 0x404DE62};
310 /* Clip sample to signed 16 bit range */
311 static inline int32_t clip_sample_16(int32_t sample)
313 if ((int16_t)sample != sample)
314 sample = 0x7fff ^ (sample >> 31);
315 return sample;
318 int32_t sound_get_pitch(void)
320 return pitch_ratio;
323 void sound_set_pitch(int32_t percent)
325 pitch_ratio = percent;
326 dsp_configure(&AUDIO_DSP, DSP_SWITCH_FREQUENCY,
327 AUDIO_DSP.codec_frequency);
330 static void tdspeed_setup(struct dsp_config *dspc)
332 /* Assume timestretch will not be used */
333 dspc->tdspeed_active = false;
334 sample_buf = small_sample_buf;
335 resample_buf = small_resample_buf;
336 sample_buf_count = SMALL_SAMPLE_BUF_COUNT;
338 if(!dsp_timestretch_available())
339 return; /* Timestretch not enabled or buffer not allocated */
340 if (dspc->tdspeed_percent == 0)
341 dspc->tdspeed_percent = PITCH_SPEED_100;
342 if (!tdspeed_config(
343 dspc->codec_frequency == 0 ? NATIVE_FREQUENCY : dspc->codec_frequency,
344 dspc->stereo_mode != STEREO_MONO,
345 dspc->tdspeed_percent))
346 return; /* Timestretch not possible or needed with these parameters */
348 /* Timestretch is to be used */
349 dspc->tdspeed_active = true;
350 sample_buf = big_sample_buf;
351 sample_buf_count = big_sample_buf_count;
352 resample_buf = big_resample_buf;
355 void dsp_timestretch_enable(bool enabled)
357 /* Hook to set up timestretch buffer on first call to settings_apply() */
358 if (big_sample_buf_count < 0) /* Only do something on first call */
360 if (enabled)
362 /* Set up timestretch buffers */
363 big_sample_buf_count = SMALL_SAMPLE_BUF_COUNT * RESAMPLE_RATIO;
364 big_sample_buf = small_resample_buf;
365 big_resample_buf = (int32_t *) buffer_alloc(big_sample_buf_count * RESAMPLE_RATIO * sizeof(int32_t));
367 else
369 /* Not enabled at startup, "big" buffers will never be available */
370 big_sample_buf_count = 0;
372 tdspeed_setup(&AUDIO_DSP);
376 void dsp_set_timestretch(int32_t percent)
378 AUDIO_DSP.tdspeed_percent = percent;
379 tdspeed_setup(&AUDIO_DSP);
382 int32_t dsp_get_timestretch()
384 return AUDIO_DSP.tdspeed_percent;
387 bool dsp_timestretch_available()
389 return (global_settings.timestretch_enabled && big_sample_buf_count > 0);
392 /* Convert count samples to the internal format, if needed. Updates src
393 * to point past the samples "consumed" and dst is set to point to the
394 * samples to consume. Note that for mono, dst[0] equals dst[1], as there
395 * is no point in processing the same data twice.
398 /* convert count 16-bit mono to 32-bit mono */
399 static void sample_input_lte_native_mono(
400 int count, const char *src[], int32_t *dst[])
402 const int16_t *s = (int16_t *) src[0];
403 const int16_t * const send = s + count;
404 int32_t *d = dst[0] = dst[1] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
405 int scale = WORD_SHIFT;
407 while (s < send)
409 *d++ = *s++ << scale;
412 src[0] = (char *)s;
415 /* convert count 16-bit interleaved stereo to 32-bit noninterleaved */
416 static void sample_input_lte_native_i_stereo(
417 int count, const char *src[], int32_t *dst[])
419 const int32_t *s = (int32_t *) src[0];
420 const int32_t * const send = s + count;
421 int32_t *dl = dst[0] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
422 int32_t *dr = dst[1] = &sample_buf[SAMPLE_BUF_RIGHT_CHANNEL];
423 int scale = WORD_SHIFT;
425 while (s < send)
427 int32_t slr = *s++;
428 #ifdef ROCKBOX_LITTLE_ENDIAN
429 *dl++ = (slr >> 16) << scale;
430 *dr++ = (int32_t)(int16_t)slr << scale;
431 #else /* ROCKBOX_BIG_ENDIAN */
432 *dl++ = (int32_t)(int16_t)slr << scale;
433 *dr++ = (slr >> 16) << scale;
434 #endif
437 src[0] = (char *)s;
440 /* convert count 16-bit noninterleaved stereo to 32-bit noninterleaved */
441 static void sample_input_lte_native_ni_stereo(
442 int count, const char *src[], int32_t *dst[])
444 const int16_t *sl = (int16_t *) src[0];
445 const int16_t *sr = (int16_t *) src[1];
446 const int16_t * const slend = sl + count;
447 int32_t *dl = dst[0] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
448 int32_t *dr = dst[1] = &sample_buf[SAMPLE_BUF_RIGHT_CHANNEL];
449 int scale = WORD_SHIFT;
451 while (sl < slend)
453 *dl++ = *sl++ << scale;
454 *dr++ = *sr++ << scale;
457 src[0] = (char *)sl;
458 src[1] = (char *)sr;
461 /* convert count 32-bit mono to 32-bit mono */
462 static void sample_input_gt_native_mono(
463 int count, const char *src[], int32_t *dst[])
465 dst[0] = dst[1] = (int32_t *)src[0];
466 src[0] = (char *)(dst[0] + count);
469 /* convert count 32-bit interleaved stereo to 32-bit noninterleaved stereo */
470 static void sample_input_gt_native_i_stereo(
471 int count, const char *src[], int32_t *dst[])
473 const int32_t *s = (int32_t *)src[0];
474 const int32_t * const send = s + 2*count;
475 int32_t *dl = dst[0] = &sample_buf[SAMPLE_BUF_LEFT_CHANNEL];
476 int32_t *dr = dst[1] = &sample_buf[SAMPLE_BUF_RIGHT_CHANNEL];
478 while (s < send)
480 *dl++ = *s++;
481 *dr++ = *s++;
484 src[0] = (char *)send;
487 /* convert 32 bit-noninterleaved stereo to 32-bit noninterleaved stereo */
488 static void sample_input_gt_native_ni_stereo(
489 int count, const char *src[], int32_t *dst[])
491 dst[0] = (int32_t *)src[0];
492 dst[1] = (int32_t *)src[1];
493 src[0] = (char *)(dst[0] + count);
494 src[1] = (char *)(dst[1] + count);
498 * sample_input_new_format()
500 * set the to-native sample conversion function based on dsp sample parameters
502 * !DSPPARAMSYNC
503 * needs syncing with changes to the following dsp parameters:
504 * * dsp->stereo_mode (A/V)
505 * * dsp->sample_depth (A/V)
507 static void sample_input_new_format(struct dsp_config *dsp)
509 static const sample_input_fn_type sample_input_functions[] =
511 [SAMPLE_INPUT_LE_NATIVE_I_STEREO] = sample_input_lte_native_i_stereo,
512 [SAMPLE_INPUT_LE_NATIVE_NI_STEREO] = sample_input_lte_native_ni_stereo,
513 [SAMPLE_INPUT_LE_NATIVE_MONO] = sample_input_lte_native_mono,
514 [SAMPLE_INPUT_GT_NATIVE_I_STEREO] = sample_input_gt_native_i_stereo,
515 [SAMPLE_INPUT_GT_NATIVE_NI_STEREO] = sample_input_gt_native_ni_stereo,
516 [SAMPLE_INPUT_GT_NATIVE_MONO] = sample_input_gt_native_mono,
519 int convert = dsp->stereo_mode;
521 if (dsp->sample_depth > NATIVE_DEPTH)
522 convert += SAMPLE_INPUT_GT_NATIVE_1ST_INDEX;
524 dsp->input_samples = sample_input_functions[convert];
528 #ifndef DSP_HAVE_ASM_SAMPLE_OUTPUT_MONO
529 /* write mono internal format to output format */
530 static void sample_output_mono(int count, struct dsp_data *data,
531 const int32_t *src[], int16_t *dst)
533 const int32_t *s0 = src[0];
534 const int scale = data->output_scale;
535 const int dc_bias = 1 << (scale - 1);
537 while (count-- > 0)
539 int32_t lr = clip_sample_16((*s0++ + dc_bias) >> scale);
540 *dst++ = lr;
541 *dst++ = lr;
544 #endif /* DSP_HAVE_ASM_SAMPLE_OUTPUT_MONO */
546 /* write stereo internal format to output format */
547 #ifndef DSP_HAVE_ASM_SAMPLE_OUTPUT_STEREO
548 static void sample_output_stereo(int count, struct dsp_data *data,
549 const int32_t *src[], int16_t *dst)
551 const int32_t *s0 = src[0];
552 const int32_t *s1 = src[1];
553 const int scale = data->output_scale;
554 const int dc_bias = 1 << (scale - 1);
556 while (count-- > 0)
558 *dst++ = clip_sample_16((*s0++ + dc_bias) >> scale);
559 *dst++ = clip_sample_16((*s1++ + dc_bias) >> scale);
562 #endif /* DSP_HAVE_ASM_SAMPLE_OUTPUT_STEREO */
565 * The "dither" code to convert the 24-bit samples produced by libmad was
566 * taken from the coolplayer project - coolplayer.sourceforge.net
568 * This function handles mono and stereo outputs.
570 static void sample_output_dithered(int count, struct dsp_data *data,
571 const int32_t *src[], int16_t *dst)
573 const int32_t mask = dither_mask;
574 const int32_t bias = dither_bias;
575 const int scale = data->output_scale;
576 const int32_t min = data->clip_min;
577 const int32_t max = data->clip_max;
578 const int32_t range = max - min;
579 int ch;
580 int16_t *d;
582 for (ch = 0; ch < data->num_channels; ch++)
584 struct dither_data * const dither = &dither_data[ch];
585 const int32_t *s = src[ch];
586 int i;
588 for (i = 0, d = &dst[ch]; i < count; i++, s++, d += 2)
590 int32_t output, sample;
591 int32_t random;
593 /* Noise shape and bias (for correct rounding later) */
594 sample = *s;
595 sample += dither->error[0] - dither->error[1] + dither->error[2];
596 dither->error[2] = dither->error[1];
597 dither->error[1] = dither->error[0]/2;
599 output = sample + bias;
601 /* Dither, highpass triangle PDF */
602 random = dither->random*0x0019660dL + 0x3c6ef35fL;
603 output += (random & mask) - (dither->random & mask);
604 dither->random = random;
606 /* Round sample to output range */
607 output &= ~mask;
609 /* Error feedback */
610 dither->error[0] = sample - output;
612 /* Clip */
613 if ((uint32_t)(output - min) > (uint32_t)range)
615 int32_t c = min;
616 if (output > min)
617 c += range;
618 output = c;
621 /* Quantize and store */
622 *d = output >> scale;
626 if (data->num_channels == 2)
627 return;
629 /* Have to duplicate left samples into the right channel since
630 pcm buffer and hardware is interleaved stereo */
631 d = &dst[0];
633 while (count-- > 0)
635 int16_t s = *d++;
636 *d++ = s;
641 * sample_output_new_format()
643 * set the from-native to ouput sample conversion routine
645 * !DSPPARAMSYNC
646 * needs syncing with changes to the following dsp parameters:
647 * * dsp->stereo_mode (A/V)
648 * * dither_enabled (A)
650 static void sample_output_new_format(struct dsp_config *dsp)
652 static const sample_output_fn_type sample_output_functions[] =
654 sample_output_mono,
655 sample_output_stereo,
656 sample_output_dithered,
657 sample_output_dithered
660 int out = dsp->data.num_channels - 1;
662 if (dsp == &AUDIO_DSP && dither_enabled)
663 out += 2;
665 dsp->output_samples = sample_output_functions[out];
669 * Linear interpolation resampling that introduces a one sample delay because
670 * of our inability to look into the future at the end of a frame.
672 #ifndef DSP_HAVE_ASM_RESAMPLING
673 static int dsp_downsample(int count, struct dsp_data *data,
674 const int32_t *src[], int32_t *dst[])
676 int ch = data->num_channels - 1;
677 uint32_t delta = data->resample_data.delta;
678 uint32_t phase, pos;
679 int32_t *d;
681 /* Rolled channel loop actually showed slightly faster. */
684 /* Just initialize things and not worry too much about the relatively
685 * uncommon case of not being able to spit out a sample for the frame.
687 const int32_t *s = src[ch];
688 int32_t last = data->resample_data.last_sample[ch];
690 data->resample_data.last_sample[ch] = s[count - 1];
691 d = dst[ch];
692 phase = data->resample_data.phase;
693 pos = phase >> 16;
695 /* Do we need last sample of previous frame for interpolation? */
696 if (pos > 0)
697 last = s[pos - 1];
699 while (pos < (uint32_t)count)
701 *d++ = last + FRACMUL((phase & 0xffff) << 15, s[pos] - last);
702 phase += delta;
703 pos = phase >> 16;
704 last = s[pos - 1];
707 while (--ch >= 0);
709 /* Wrap phase accumulator back to start of next frame. */
710 data->resample_data.phase = phase - (count << 16);
711 return d - dst[0];
714 static int dsp_upsample(int count, struct dsp_data *data,
715 const int32_t *src[], int32_t *dst[])
717 int ch = data->num_channels - 1;
718 uint32_t delta = data->resample_data.delta;
719 uint32_t phase, pos;
720 int32_t *d;
722 /* Rolled channel loop actually showed slightly faster. */
725 /* Should always be able to output a sample for a ratio up to RESAMPLE_RATIO */
726 const int32_t *s = src[ch];
727 int32_t last = data->resample_data.last_sample[ch];
729 data->resample_data.last_sample[ch] = s[count - 1];
730 d = dst[ch];
731 phase = data->resample_data.phase;
732 pos = phase >> 16;
734 while (pos == 0)
736 *d++ = last + FRACMUL((phase & 0xffff) << 15, s[0] - last);
737 phase += delta;
738 pos = phase >> 16;
741 while (pos < (uint32_t)count)
743 last = s[pos - 1];
744 *d++ = last + FRACMUL((phase & 0xffff) << 15, s[pos] - last);
745 phase += delta;
746 pos = phase >> 16;
749 while (--ch >= 0);
751 /* Wrap phase accumulator back to start of next frame. */
752 data->resample_data.phase = phase & 0xffff;
753 return d - dst[0];
755 #endif /* DSP_HAVE_ASM_RESAMPLING */
757 static void resampler_new_delta(struct dsp_config *dsp)
759 dsp->data.resample_data.delta = (unsigned long)
760 dsp->frequency * 65536LL / NATIVE_FREQUENCY;
762 if (dsp->frequency == NATIVE_FREQUENCY)
764 /* NOTE: If fully glitch-free transistions from no resampling to
765 resampling are desired, last_sample history should be maintained
766 even when not resampling. */
767 dsp->resample = NULL;
768 dsp->data.resample_data.phase = 0;
769 dsp->data.resample_data.last_sample[0] = 0;
770 dsp->data.resample_data.last_sample[1] = 0;
772 else if (dsp->frequency < NATIVE_FREQUENCY)
773 dsp->resample = dsp_upsample;
774 else
775 dsp->resample = dsp_downsample;
778 /* Resample count stereo samples. Updates the src array, if resampling is
779 * done, to refer to the resampled data. Returns number of stereo samples
780 * for further processing.
782 static inline int resample(struct dsp_config *dsp, int count, int32_t *src[])
784 int32_t *dst[2] =
786 &resample_buf[RESAMPLE_BUF_LEFT_CHANNEL],
787 &resample_buf[RESAMPLE_BUF_RIGHT_CHANNEL],
790 count = dsp->resample(count, &dsp->data, (const int32_t **)src, dst);
792 src[0] = dst[0];
793 src[1] = dst[dsp->data.num_channels - 1];
795 return count;
798 static void dither_init(struct dsp_config *dsp)
800 memset(dither_data, 0, sizeof (dither_data));
801 dither_bias = (1L << (dsp->frac_bits - NATIVE_DEPTH));
802 dither_mask = (1L << (dsp->frac_bits + 1 - NATIVE_DEPTH)) - 1;
805 void dsp_dither_enable(bool enable)
807 struct dsp_config *dsp = &AUDIO_DSP;
808 dither_enabled = enable;
809 sample_output_new_format(dsp);
812 /* Applies crossfeed to the stereo signal in src.
813 * Crossfeed is a process where listening over speakers is simulated. This
814 * is good for old hard panned stereo records, which might be quite fatiguing
815 * to listen to on headphones with no crossfeed.
817 #ifndef DSP_HAVE_ASM_CROSSFEED
818 static void apply_crossfeed(int count, int32_t *buf[])
820 int32_t *hist_l = &crossfeed_data.history[0];
821 int32_t *hist_r = &crossfeed_data.history[2];
822 int32_t *delay = &crossfeed_data.delay[0][0];
823 int32_t *coefs = &crossfeed_data.coefs[0];
824 int32_t gain = crossfeed_data.gain;
825 int32_t *di = crossfeed_data.index;
827 int32_t acc;
828 int32_t left, right;
829 int i;
831 for (i = 0; i < count; i++)
833 left = buf[0][i];
834 right = buf[1][i];
836 /* Filter delayed sample from left speaker */
837 acc = FRACMUL(*di, coefs[0]);
838 acc += FRACMUL(hist_l[0], coefs[1]);
839 acc += FRACMUL(hist_l[1], coefs[2]);
840 /* Save filter history for left speaker */
841 hist_l[1] = acc;
842 hist_l[0] = *di;
843 *di++ = left;
844 /* Filter delayed sample from right speaker */
845 acc = FRACMUL(*di, coefs[0]);
846 acc += FRACMUL(hist_r[0], coefs[1]);
847 acc += FRACMUL(hist_r[1], coefs[2]);
848 /* Save filter history for right speaker */
849 hist_r[1] = acc;
850 hist_r[0] = *di;
851 *di++ = right;
852 /* Now add the attenuated direct sound and write to outputs */
853 buf[0][i] = FRACMUL(left, gain) + hist_r[1];
854 buf[1][i] = FRACMUL(right, gain) + hist_l[1];
856 /* Wrap delay line index if bigger than delay line size */
857 if (di >= delay + 13*2)
858 di = delay;
860 /* Write back local copies of data we've modified */
861 crossfeed_data.index = di;
863 #endif /* DSP_HAVE_ASM_CROSSFEED */
866 * dsp_set_crossfeed(bool enable)
868 * !DSPPARAMSYNC
869 * needs syncing with changes to the following dsp parameters:
870 * * dsp->stereo_mode (A)
872 void dsp_set_crossfeed(bool enable)
874 crossfeed_enabled = enable;
875 AUDIO_DSP.apply_crossfeed = (enable && AUDIO_DSP.data.num_channels > 1)
876 ? apply_crossfeed : NULL;
879 void dsp_set_crossfeed_direct_gain(int gain)
881 crossfeed_data.gain = get_replaygain_int(gain * 10) << 7;
882 /* If gain is negative, the calculation overflowed and we need to clamp */
883 if (crossfeed_data.gain < 0)
884 crossfeed_data.gain = 0x7fffffff;
887 /* Both gains should be below 0 dB */
888 void dsp_set_crossfeed_cross_params(long lf_gain, long hf_gain, long cutoff)
890 int32_t *c = crossfeed_data.coefs;
891 long scaler = get_replaygain_int(lf_gain * 10) << 7;
893 cutoff = 0xffffffff/NATIVE_FREQUENCY*cutoff;
894 hf_gain -= lf_gain;
895 /* Divide cutoff by sqrt(10^(hf_gain/20)) to place cutoff at the -3 dB
896 * point instead of shelf midpoint. This is for compatibility with the old
897 * crossfeed shelf filter and should be removed if crossfeed settings are
898 * ever made incompatible for any other good reason.
900 cutoff = fp_div(cutoff, get_replaygain_int(hf_gain*5), 24);
901 filter_shelf_coefs(cutoff, hf_gain, false, c);
902 /* Scale coefs by LF gain and shift them to s0.31 format. We have no gains
903 * over 1 and can do this safely
905 c[0] = FRACMUL_SHL(c[0], scaler, 4);
906 c[1] = FRACMUL_SHL(c[1], scaler, 4);
907 c[2] <<= 4;
910 /* Apply a constant gain to the samples (e.g., for ReplayGain).
911 * Note that this must be called before the resampler.
913 #ifndef DSP_HAVE_ASM_APPLY_GAIN
914 static void dsp_apply_gain(int count, struct dsp_data *data, int32_t *buf[])
916 const int32_t gain = data->gain;
917 int ch;
919 for (ch = 0; ch < data->num_channels; ch++)
921 int32_t *d = buf[ch];
922 int i;
924 for (i = 0; i < count; i++)
925 d[i] = FRACMUL_SHL(d[i], gain, 8);
928 #endif /* DSP_HAVE_ASM_APPLY_GAIN */
930 /* Combine all gains to a global gain. */
931 static void set_gain(struct dsp_config *dsp)
933 /* gains are in S7.24 format */
934 dsp->data.gain = DEFAULT_GAIN;
936 /* Replay gain not relevant to voice */
937 if (dsp == &AUDIO_DSP && replaygain)
939 dsp->data.gain = replaygain;
942 if (dsp->eq_process && eq_precut)
944 dsp->data.gain = fp_mul(dsp->data.gain, eq_precut, 24);
947 /* only preamp for the limiter if limiter is active and sample depth
948 * allows safe pre-amping (12 dB is OK with 29 or less frac bits) */
949 if ((dsp->limiter_preamp) && (dsp->frac_bits <= 29))
951 dsp->data.gain = fp_mul(dsp->data.gain, dsp->limiter_preamp, 24);
954 #ifdef HAVE_SW_VOLUME_CONTROL
955 if (global_settings.volume < SW_VOLUME_MAX ||
956 global_settings.volume > SW_VOLUME_MIN)
958 int vol_gain = get_replaygain_int(global_settings.volume * 100);
959 dsp->data.gain = (long) (((int64_t) dsp->data.gain * vol_gain) >> 24);
961 #endif
963 if (dsp->data.gain == DEFAULT_GAIN)
965 dsp->data.gain = 0;
967 else
969 dsp->data.gain >>= 1; /* convert gain to S8.23 format */
972 dsp->apply_gain = dsp->data.gain != 0 ? dsp_apply_gain : NULL;
976 * Update the amount to cut the audio before applying the equalizer.
978 * @param precut to apply in decibels (multiplied by 10)
980 void dsp_set_eq_precut(int precut)
982 eq_precut = get_replaygain_int(precut * -10);
983 set_gain(&AUDIO_DSP);
987 * Synchronize the equalizer filter coefficients with the global settings.
989 * @param band the equalizer band to synchronize
991 void dsp_set_eq_coefs(int band)
993 const int *setting;
994 long gain;
995 unsigned long cutoff, q;
997 /* Adjust setting pointer to the band we actually want to change */
998 setting = &global_settings.eq_band0_cutoff + (band * 3);
1000 /* Convert user settings to format required by coef generator functions */
1001 cutoff = 0xffffffff / NATIVE_FREQUENCY * (*setting++);
1002 q = *setting++;
1003 gain = *setting++;
1005 if (q == 0)
1006 q = 1;
1008 /* NOTE: The coef functions assume the EMAC unit is in fractional mode,
1009 which it should be, since we're executed from the main thread. */
1011 /* Assume a band is disabled if the gain is zero */
1012 if (gain == 0)
1014 eq_data.enabled[band] = 0;
1016 else
1018 if (band == 0)
1019 eq_ls_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
1020 else if (band == 4)
1021 eq_hs_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
1022 else
1023 eq_pk_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
1025 eq_data.enabled[band] = 1;
1029 /* Apply EQ filters to those bands that have got it switched on. */
1030 static void eq_process(int count, int32_t *buf[])
1032 static const int shifts[] =
1034 EQ_SHELF_SHIFT, /* low shelf */
1035 EQ_PEAK_SHIFT, /* peaking */
1036 EQ_PEAK_SHIFT, /* peaking */
1037 EQ_PEAK_SHIFT, /* peaking */
1038 EQ_SHELF_SHIFT, /* high shelf */
1040 unsigned int channels = AUDIO_DSP.data.num_channels;
1041 int i;
1043 /* filter configuration currently is 1 low shelf filter, 3 band peaking
1044 filters and 1 high shelf filter, in that order. we need to know this
1045 so we can choose the correct shift factor.
1047 for (i = 0; i < 5; i++)
1049 if (!eq_data.enabled[i])
1050 continue;
1051 eq_filter(buf, &eq_data.filters[i], count, channels, shifts[i]);
1056 * Use to enable the equalizer.
1058 * @param enable true to enable the equalizer
1060 void dsp_set_eq(bool enable)
1062 AUDIO_DSP.eq_process = enable ? eq_process : NULL;
1063 set_gain(&AUDIO_DSP);
1066 static void dsp_set_stereo_width(int value)
1068 long width, straight, cross;
1070 width = value * 0x7fffff / 100;
1072 if (value <= 100)
1074 straight = (0x7fffff + width) / 2;
1075 cross = straight - width;
1077 else
1079 /* straight = (1 + width) / (2 * width) */
1080 straight = ((int64_t)(0x7fffff + width) << 22) / width;
1081 cross = straight - 0x7fffff;
1084 dsp_sw_gain = straight << 8;
1085 dsp_sw_cross = cross << 8;
1089 * Implements the different channel configurations and stereo width.
1092 /* SOUND_CHAN_STEREO mode is a noop so has no function - just outline one for
1093 * completeness. */
1094 #if 0
1095 static void channels_process_sound_chan_stereo(int count, int32_t *buf[])
1097 /* The channels are each just themselves */
1098 (void)count; (void)buf;
1100 #endif
1102 #ifndef DSP_HAVE_ASM_SOUND_CHAN_MONO
1103 static void channels_process_sound_chan_mono(int count, int32_t *buf[])
1105 int32_t *sl = buf[0], *sr = buf[1];
1107 while (count-- > 0)
1109 int32_t lr = *sl/2 + *sr/2;
1110 *sl++ = lr;
1111 *sr++ = lr;
1114 #endif /* DSP_HAVE_ASM_SOUND_CHAN_MONO */
1116 #ifndef DSP_HAVE_ASM_SOUND_CHAN_CUSTOM
1117 static void channels_process_sound_chan_custom(int count, int32_t *buf[])
1119 const int32_t gain = dsp_sw_gain;
1120 const int32_t cross = dsp_sw_cross;
1121 int32_t *sl = buf[0], *sr = buf[1];
1123 while (count-- > 0)
1125 int32_t l = *sl;
1126 int32_t r = *sr;
1127 *sl++ = FRACMUL(l, gain) + FRACMUL(r, cross);
1128 *sr++ = FRACMUL(r, gain) + FRACMUL(l, cross);
1131 #endif /* DSP_HAVE_ASM_SOUND_CHAN_CUSTOM */
1133 static void channels_process_sound_chan_mono_left(int count, int32_t *buf[])
1135 /* Just copy over the other channel */
1136 memcpy(buf[1], buf[0], count * sizeof (*buf));
1139 static void channels_process_sound_chan_mono_right(int count, int32_t *buf[])
1141 /* Just copy over the other channel */
1142 memcpy(buf[0], buf[1], count * sizeof (*buf));
1145 #ifndef DSP_HAVE_ASM_SOUND_CHAN_KARAOKE
1146 static void channels_process_sound_chan_karaoke(int count, int32_t *buf[])
1148 int32_t *sl = buf[0], *sr = buf[1];
1150 while (count-- > 0)
1152 int32_t ch = *sl/2 - *sr/2;
1153 *sl++ = ch;
1154 *sr++ = -ch;
1157 #endif /* DSP_HAVE_ASM_SOUND_CHAN_KARAOKE */
1159 static void dsp_set_channel_config(int value)
1161 static const channels_process_fn_type channels_process_functions[] =
1163 /* SOUND_CHAN_STEREO = All-purpose index for no channel processing */
1164 [SOUND_CHAN_STEREO] = NULL,
1165 [SOUND_CHAN_MONO] = channels_process_sound_chan_mono,
1166 [SOUND_CHAN_CUSTOM] = channels_process_sound_chan_custom,
1167 [SOUND_CHAN_MONO_LEFT] = channels_process_sound_chan_mono_left,
1168 [SOUND_CHAN_MONO_RIGHT] = channels_process_sound_chan_mono_right,
1169 [SOUND_CHAN_KARAOKE] = channels_process_sound_chan_karaoke,
1172 if ((unsigned)value >= ARRAYLEN(channels_process_functions) ||
1173 AUDIO_DSP.stereo_mode == STEREO_MONO)
1175 value = SOUND_CHAN_STEREO;
1178 /* This doesn't apply to voice */
1179 channels_mode = value;
1180 AUDIO_DSP.channels_process = channels_process_functions[value];
1183 #if CONFIG_CODEC == SWCODEC
1185 #ifdef HAVE_SW_TONE_CONTROLS
1186 static void set_tone_controls(void)
1188 filter_bishelf_coefs(0xffffffff/NATIVE_FREQUENCY*200,
1189 0xffffffff/NATIVE_FREQUENCY*3500,
1190 bass, treble, -prescale,
1191 AUDIO_DSP.tone_filter.coefs);
1192 /* Sync the voice dsp coefficients */
1193 memcpy(&VOICE_DSP.tone_filter.coefs, AUDIO_DSP.tone_filter.coefs,
1194 sizeof (VOICE_DSP.tone_filter.coefs));
1196 #endif
1198 /* Hook back from firmware/ part of audio, which can't/shouldn't call apps/
1199 * code directly.
1201 int dsp_callback(int msg, intptr_t param)
1203 switch (msg)
1205 #ifdef HAVE_SW_TONE_CONTROLS
1206 case DSP_CALLBACK_SET_PRESCALE:
1207 prescale = param;
1208 set_tone_controls();
1209 break;
1210 /* prescaler is always set after calling any of these, so we wait with
1211 * calculating coefs until the above case is hit.
1213 case DSP_CALLBACK_SET_BASS:
1214 bass = param;
1215 break;
1216 case DSP_CALLBACK_SET_TREBLE:
1217 treble = param;
1218 break;
1219 #ifdef HAVE_SW_VOLUME_CONTROL
1220 case DSP_CALLBACK_SET_SW_VOLUME:
1221 set_gain(&AUDIO_DSP);
1222 break;
1223 #endif
1224 #endif
1225 case DSP_CALLBACK_SET_CHANNEL_CONFIG:
1226 dsp_set_channel_config(param);
1227 break;
1228 case DSP_CALLBACK_SET_STEREO_WIDTH:
1229 dsp_set_stereo_width(param);
1230 break;
1231 default:
1232 break;
1234 return 0;
1236 #endif
1238 /* Process and convert src audio to dst based on the DSP configuration,
1239 * reading count number of audio samples. dst is assumed to be large
1240 * enough; use dsp_output_count() to get the required number. src is an
1241 * array of pointers; for mono and interleaved stereo, it contains one
1242 * pointer to the start of the audio data and the other is ignored; for
1243 * non-interleaved stereo, it contains two pointers, one for each audio
1244 * channel. Returns number of bytes written to dst.
1246 int dsp_process(struct dsp_config *dsp, char *dst, const char *src[], int count)
1248 int32_t *tmp[2];
1249 static long last_yield;
1250 long tick;
1251 int written = 0;
1253 #if defined(CPU_COLDFIRE)
1254 /* set emac unit for dsp processing, and save old macsr, we're running in
1255 codec thread context at this point, so can't clobber it */
1256 unsigned long old_macsr = coldfire_get_macsr();
1257 coldfire_set_macsr(EMAC_FRACTIONAL | EMAC_SATURATE);
1258 #endif
1260 if (new_gain)
1261 dsp_set_replaygain(); /* Gain has changed */
1263 /* Perform at least one yield before starting */
1264 last_yield = current_tick;
1265 yield();
1267 /* Testing function pointers for NULL is preferred since the pointer
1268 will be preloaded to be used for the call if not. */
1269 while (count > 0)
1271 int samples = MIN(sample_buf_count/2, count);
1272 count -= samples;
1274 dsp->input_samples(samples, src, tmp);
1276 if (dsp->tdspeed_active)
1277 samples = tdspeed_doit(tmp, samples);
1279 int chunk_offset = 0;
1280 while (samples > 0)
1282 int32_t *t2[2];
1283 t2[0] = tmp[0]+chunk_offset;
1284 t2[1] = tmp[1]+chunk_offset;
1286 int chunk = MIN(sample_buf_count/2, samples);
1287 chunk_offset += chunk;
1288 samples -= chunk;
1290 if (dsp->apply_gain)
1291 dsp->apply_gain(chunk, &dsp->data, t2);
1293 if (dsp->resample && (chunk = resample(dsp, chunk, t2)) <= 0)
1294 break; /* I'm pretty sure we're downsampling here */
1296 if (dsp->apply_crossfeed)
1297 dsp->apply_crossfeed(chunk, t2);
1299 if (dsp->eq_process)
1300 dsp->eq_process(chunk, t2);
1302 #ifdef HAVE_SW_TONE_CONTROLS
1303 if ((bass | treble) != 0)
1304 eq_filter(t2, &dsp->tone_filter, chunk,
1305 dsp->data.num_channels, FILTER_BISHELF_SHIFT);
1306 #endif
1308 if (dsp->channels_process)
1309 dsp->channels_process(chunk, t2);
1311 if (dsp->limiter_process)
1312 chunk = dsp->limiter_process(chunk, t2);
1314 dsp->output_samples(chunk, &dsp->data, (const int32_t **)t2, (int16_t *)dst);
1316 written += chunk;
1317 dst += chunk * sizeof (int16_t) * 2;
1319 /* yield at least once each tick */
1320 tick = current_tick;
1321 if (TIME_AFTER(tick, last_yield))
1323 last_yield = tick;
1324 yield();
1329 #if defined(CPU_COLDFIRE)
1330 /* set old macsr again */
1331 coldfire_set_macsr(old_macsr);
1332 #endif
1333 return written;
1336 /* Given count number of input samples, calculate the maximum number of
1337 * samples of output data that would be generated (the calculation is not
1338 * entirely exact and rounds upwards to be on the safe side; during
1339 * resampling, the number of samples generated depends on the current state
1340 * of the resampler).
1342 /* dsp_input_size MUST be called afterwards */
1343 int dsp_output_count(struct dsp_config *dsp, int count)
1345 if (dsp->tdspeed_active)
1346 count = tdspeed_est_output_size();
1347 if (dsp->resample)
1349 count = (int)(((unsigned long)count * NATIVE_FREQUENCY
1350 + (dsp->frequency - 1)) / dsp->frequency);
1353 /* Now we have the resampled sample count which must not exceed
1354 * RESAMPLE_BUF_RIGHT_CHANNEL to avoid resample buffer overflow. One
1355 * must call dsp_input_count() to get the correct input sample
1356 * count.
1358 if (count > RESAMPLE_BUF_RIGHT_CHANNEL)
1359 count = RESAMPLE_BUF_RIGHT_CHANNEL;
1361 /* If the limiter buffer is filling, some or all samples will
1362 * be captured by it, so expect fewer samples coming out. */
1363 if (limiter_buffer_active && !limiter_buffer_full)
1365 int empty_space = limiter_buffer_count(false);
1366 count_adjust = MIN(empty_space, count);
1367 count -= count_adjust;
1370 return count;
1373 /* Given count output samples, calculate number of input samples
1374 * that would be consumed in order to fill the output buffer.
1376 int dsp_input_count(struct dsp_config *dsp, int count)
1378 /* If the limiter buffer is filling, the output count was
1379 * adjusted downward. This adjusts it back so that input
1380 * count is not affected.
1382 if (limiter_buffer_active && !limiter_buffer_full)
1383 count += count_adjust;
1385 /* count is now the number of resampled input samples. Convert to
1386 original input samples. */
1387 if (dsp->resample)
1389 /* Use the real resampling delta =
1390 * dsp->frequency * 65536 / NATIVE_FREQUENCY, and
1391 * round towards zero to avoid buffer overflows. */
1392 count = (int)(((unsigned long)count *
1393 dsp->data.resample_data.delta) >> 16);
1396 if (dsp->tdspeed_active)
1397 count = tdspeed_est_input_size(count);
1399 return count;
1402 static void dsp_set_gain_var(long *var, long value)
1404 *var = value;
1405 new_gain = true;
1408 static void dsp_update_functions(struct dsp_config *dsp)
1410 sample_input_new_format(dsp);
1411 sample_output_new_format(dsp);
1412 if (dsp == &AUDIO_DSP)
1413 dsp_set_crossfeed(crossfeed_enabled);
1416 intptr_t dsp_configure(struct dsp_config *dsp, int setting, intptr_t value)
1418 switch (setting)
1420 case DSP_MYDSP:
1421 switch (value)
1423 case CODEC_IDX_AUDIO:
1424 return (intptr_t)&AUDIO_DSP;
1425 case CODEC_IDX_VOICE:
1426 return (intptr_t)&VOICE_DSP;
1427 default:
1428 return (intptr_t)NULL;
1431 case DSP_SET_FREQUENCY:
1432 memset(&dsp->data.resample_data, 0, sizeof (dsp->data.resample_data));
1433 /* Fall through!!! */
1434 case DSP_SWITCH_FREQUENCY:
1435 dsp->codec_frequency = (value == 0) ? NATIVE_FREQUENCY : value;
1436 /* Account for playback speed adjustment when setting dsp->frequency
1437 if we're called from the main audio thread. Voice UI thread should
1438 not need this feature.
1440 if (dsp == &AUDIO_DSP)
1441 dsp->frequency = pitch_ratio * dsp->codec_frequency / PITCH_SPEED_100;
1442 else
1443 dsp->frequency = dsp->codec_frequency;
1445 resampler_new_delta(dsp);
1446 tdspeed_setup(dsp);
1447 break;
1449 case DSP_SET_SAMPLE_DEPTH:
1450 dsp->sample_depth = value;
1452 if (dsp->sample_depth <= NATIVE_DEPTH)
1454 dsp->frac_bits = WORD_FRACBITS;
1455 dsp->sample_bytes = sizeof (int16_t); /* samples are 16 bits */
1456 dsp->data.clip_max = ((1 << WORD_FRACBITS) - 1);
1457 dsp->data.clip_min = -((1 << WORD_FRACBITS));
1459 else
1461 dsp->frac_bits = value;
1462 dsp->sample_bytes = sizeof (int32_t); /* samples are 32 bits */
1463 dsp->data.clip_max = (1 << value) - 1;
1464 dsp->data.clip_min = -(1 << value);
1467 dsp->data.output_scale = dsp->frac_bits + 1 - NATIVE_DEPTH;
1468 sample_input_new_format(dsp);
1469 dither_init(dsp);
1470 break;
1472 case DSP_SET_STEREO_MODE:
1473 dsp->stereo_mode = value;
1474 dsp->data.num_channels = value == STEREO_MONO ? 1 : 2;
1475 dsp_update_functions(dsp);
1476 tdspeed_setup(dsp);
1477 break;
1479 case DSP_RESET:
1480 dsp->stereo_mode = STEREO_NONINTERLEAVED;
1481 dsp->data.num_channels = 2;
1482 dsp->sample_depth = NATIVE_DEPTH;
1483 dsp->frac_bits = WORD_FRACBITS;
1484 dsp->sample_bytes = sizeof (int16_t);
1485 dsp->data.output_scale = dsp->frac_bits + 1 - NATIVE_DEPTH;
1486 dsp->data.clip_max = ((1 << WORD_FRACBITS) - 1);
1487 dsp->data.clip_min = -((1 << WORD_FRACBITS));
1488 dsp->codec_frequency = dsp->frequency = NATIVE_FREQUENCY;
1490 if (dsp == &AUDIO_DSP)
1492 track_gain = 0;
1493 album_gain = 0;
1494 track_peak = 0;
1495 album_peak = 0;
1496 new_gain = true;
1499 dsp_update_functions(dsp);
1500 resampler_new_delta(dsp);
1501 tdspeed_setup(dsp);
1502 reset_limiter_buffer(dsp);
1503 break;
1505 case DSP_FLUSH:
1506 memset(&dsp->data.resample_data, 0,
1507 sizeof (dsp->data.resample_data));
1508 resampler_new_delta(dsp);
1509 dither_init(dsp);
1510 tdspeed_setup(dsp);
1511 reset_limiter_buffer(dsp);
1512 break;
1514 case DSP_SET_TRACK_GAIN:
1515 if (dsp == &AUDIO_DSP)
1516 dsp_set_gain_var(&track_gain, value);
1517 break;
1519 case DSP_SET_ALBUM_GAIN:
1520 if (dsp == &AUDIO_DSP)
1521 dsp_set_gain_var(&album_gain, value);
1522 break;
1524 case DSP_SET_TRACK_PEAK:
1525 if (dsp == &AUDIO_DSP)
1526 dsp_set_gain_var(&track_peak, value);
1527 break;
1529 case DSP_SET_ALBUM_PEAK:
1530 if (dsp == &AUDIO_DSP)
1531 dsp_set_gain_var(&album_peak, value);
1532 break;
1534 default:
1535 return 0;
1538 return 1;
1541 void dsp_set_replaygain(void)
1543 long gain = 0;
1545 new_gain = false;
1547 if ((global_settings.replaygain_type != REPLAYGAIN_OFF) ||
1548 global_settings.replaygain_noclip)
1550 bool track_mode = get_replaygain_mode(track_gain != 0,
1551 album_gain != 0) == REPLAYGAIN_TRACK;
1552 long peak = (track_mode || !album_peak) ? track_peak : album_peak;
1554 if (global_settings.replaygain_type != REPLAYGAIN_OFF)
1556 gain = (track_mode || !album_gain) ? track_gain : album_gain;
1558 if (global_settings.replaygain_preamp)
1560 long preamp = get_replaygain_int(
1561 global_settings.replaygain_preamp * 10);
1563 gain = (long) (((int64_t) gain * preamp) >> 24);
1567 if (gain == 0)
1569 /* So that noclip can work even with no gain information. */
1570 gain = DEFAULT_GAIN;
1573 if (global_settings.replaygain_noclip && (peak != 0)
1574 && ((((int64_t) gain * peak) >> 24) >= DEFAULT_GAIN))
1576 gain = (((int64_t) DEFAULT_GAIN << 24) / peak);
1579 if (gain == DEFAULT_GAIN)
1581 /* Nothing to do, disable processing. */
1582 gain = 0;
1586 /* Store in S7.24 format to simplify calculations. */
1587 replaygain = gain;
1588 set_gain(&AUDIO_DSP);
1591 /** RESET THE LIMITER BUFFER
1592 * Force the limiter buffer to its initial state and discard
1593 * any samples held there. */
1594 static void reset_limiter_buffer(struct dsp_config *dsp)
1596 if (dsp == &AUDIO_DSP)
1598 int i;
1599 logf(" reset_limiter_buffer");
1600 for (i = 0; i < 2; i++)
1601 start_lim_buf[i] = end_lim_buf[i] = limiter_buffer[i];
1602 start_peak = end_peak = lim_buf_peak;
1603 limiter_buffer_full = false;
1604 limiter_buffer_emptying = false;
1605 release_peak = 0;
1609 /** OPERATE THE LIMITER BUFFER
1610 * Handle all samples entering or exiting the limiter buffer. */
1611 static inline int set_limiter_buffer(int count, int32_t *buf[])
1613 int32_t *in_buf[] = {buf[0], buf[1]},
1614 *out_buf[] = {buf[0], buf[1]};
1615 int empty_space, i, out_count;
1616 const long clip_max = AUDIO_DSP.data.clip_max;
1617 const int ch = AUDIO_DSP.data.num_channels - 1;
1618 out_buf_peak_index = out_buf_peak;
1620 if (limiter_buffer_emptying)
1621 /** EMPTY THE BUFFER
1622 * since the empty flag has been set, assume no inbound samples and
1623 return all samples in the limiter buffer to the outbound buffer */
1625 count = limiter_buffer_count(true);
1626 out_count = count;
1627 logf(" Emptying limiter buffer: %d", count);
1628 while (count-- > 0)
1630 for (i = 0; i <= ch; i++)
1632 /* move samples in limiter buffer to output buffer */
1633 *out_buf[i]++ = *start_lim_buf[i]++;
1634 if (start_lim_buf[i] == &limiter_buffer[i][LIMITER_BUFFER_SIZE])
1635 start_lim_buf[i] = limiter_buffer[i];
1636 /* move limiter buffer peak values to output peak values */
1637 if (i == 0)
1639 *out_buf_peak_index++ = *start_peak++;
1640 if (start_peak == &lim_buf_peak[LIMITER_BUFFER_SIZE])
1641 start_peak = lim_buf_peak;
1645 limiter_buffer_full = false;
1646 limiter_buffer_emptying = false;
1648 else /* limiter buffer NOT emptying */
1650 if (count <= 0) return 0;
1652 empty_space = limiter_buffer_count(false);
1654 if (empty_space > 0)
1655 /** FILL BUFFER
1656 * use as many inbound samples as necessary to fill the buffer */
1658 /* don't try to fill with more samples than available */
1659 if (empty_space > count)
1660 empty_space = count;
1661 logf(" Filling limiter buffer: %d", empty_space);
1662 while (empty_space-- > 0)
1664 for (i = 0; i <= ch; i++)
1666 /* put inbound samples in the limiter buffer */
1667 in_samp = *in_buf[i]++;
1668 *end_lim_buf[i]++ = in_samp;
1669 if (end_lim_buf[i] == &limiter_buffer[i][LIMITER_BUFFER_SIZE])
1670 end_lim_buf[i] = limiter_buffer[i];
1671 if (in_samp < 0) /* make positive for comparison */
1672 in_samp = -in_samp - 1;
1673 if (in_samp <= clip_max)
1674 in_samp = 0; /* disregard if not clipped */
1675 if (i == 0)
1676 samp0 = in_samp;
1677 if (i == ch)
1679 /* assign peak value for each inbound sample pair */
1680 *end_peak++ = ((samp0 > 0) || (in_samp > 0)) ?
1681 get_peak_value(MAX(samp0, in_samp)) : 0;
1682 if (end_peak == &lim_buf_peak[LIMITER_BUFFER_SIZE])
1683 end_peak = lim_buf_peak;
1686 count--;
1688 /* after buffer fills, the remaining inbound samples are cycled */
1691 limiter_buffer_full = (end_lim_buf[0] == start_lim_buf[0]);
1692 out_count = count;
1694 /** CYCLE BUFFER
1695 * return buffered samples and backfill limiter buffer with new ones.
1696 * The buffer is always full when cycling. */
1697 while (count-- > 0)
1699 for (i = 0; i <= ch; i++)
1701 /* copy incoming sample */
1702 in_samp = *in_buf[i]++;
1703 /* put limiter buffer sample into outbound buffer */
1704 *out_buf[i]++ = *start_lim_buf[i]++;
1705 /* put incoming sample on the end of the limiter buffer */
1706 *end_lim_buf[i]++ = in_samp;
1707 /* ring buffer pointer wrap */
1708 if (start_lim_buf[i] == &limiter_buffer[i][LIMITER_BUFFER_SIZE])
1709 start_lim_buf[i] = limiter_buffer[i];
1710 if (end_lim_buf[i] == &limiter_buffer[i][LIMITER_BUFFER_SIZE])
1711 end_lim_buf[i] = limiter_buffer[i];
1712 if (in_samp < 0) /* make positive for comparison */
1713 in_samp = -in_samp - 1;
1714 if (in_samp <= clip_max)
1715 in_samp = 0; /* disregard if not clipped */
1716 if (i == 0)
1718 samp0 = in_samp;
1719 /* assign outgoing sample its associated peak value */
1720 *out_buf_peak_index++ = *start_peak++;
1721 if (start_peak == &lim_buf_peak[LIMITER_BUFFER_SIZE])
1722 start_peak = lim_buf_peak;
1724 if (i == ch)
1726 /* assign peak value for each inbound sample pair */
1727 *end_peak++ = ((samp0 > 0) || (in_samp > 0)) ?
1728 get_peak_value(MAX(samp0, in_samp)) : 0;
1729 if (end_peak == &lim_buf_peak[LIMITER_BUFFER_SIZE])
1730 end_peak = lim_buf_peak;
1736 return out_count;
1739 /** RETURN LIMITER BUFFER COUNT
1740 * If argument is true, returns number of samples in the buffer,
1741 * otherwise, returns empty space remaining */
1742 static int limiter_buffer_count(bool buf_count)
1744 int count;
1745 if (limiter_buffer_full)
1746 count = LIMITER_BUFFER_SIZE;
1747 else if (end_lim_buf[0] >= start_lim_buf[0])
1748 count = (end_lim_buf[0] - start_lim_buf[0]);
1749 else
1750 count = (end_lim_buf[0] - start_lim_buf[0]) + LIMITER_BUFFER_SIZE;
1751 return buf_count ? count : (LIMITER_BUFFER_SIZE - count);
1754 /** FLUSH THE LIMITER BUFFER
1755 * Empties the limiter buffer into the buffer pointed to by the argument
1756 * and returns the number of samples in that buffer */
1757 int dsp_flush_limiter_buffer(char *dest)
1759 if ((!limiter_buffer_active) || (limiter_buffer_count(true) <= 0))
1760 return 0;
1762 logf(" dsp_flush_limiter_buffer");
1763 int32_t flush_buf[2][LIMITER_BUFFER_SIZE];
1764 int32_t *src[2] = {flush_buf[0], flush_buf[1]};
1766 limiter_buffer_emptying = true;
1767 int count = limiter_process(0, src);
1768 AUDIO_DSP.output_samples(count, &AUDIO_DSP.data,
1769 (const int32_t **)src, (int16_t *)dest);
1770 return count;
1773 /** GET PEAK VALUE
1774 * Return a small value representing how much the sample is clipped. This
1775 * should only be called if a sample is actually clipped. Sample is a
1776 * positive value.
1778 static uint16_t get_peak_value(int32_t sample)
1780 const int frac_bits = AUDIO_DSP.frac_bits;
1781 int mid,
1782 hi = 48,
1783 lo = 0;
1785 /* shift sample into 28 frac bit range for comparison */
1786 if (frac_bits > 28)
1787 sample >>= (frac_bits - 28);
1788 if (frac_bits < 28)
1789 sample <<= (28 - frac_bits);
1791 /* if clipped out of range, return maximum value */
1792 if (sample >= clip_steps[48])
1793 return 48 * 90;
1795 /* find amount of sample clipping on the table */
1798 mid = (hi + lo) / 2;
1799 if (sample < clip_steps[mid])
1800 hi = mid;
1801 else if (sample > clip_steps[mid])
1802 lo = mid;
1803 else
1804 return mid * 90;
1806 while (hi > (lo + 1));
1808 /* interpolate linearly between steps (less accurate but faster) */
1809 return ((hi-1) * 90) + (((sample - clip_steps[hi-1]) * 90) /
1810 (clip_steps[hi] - clip_steps[hi-1]));
1813 /** SET LIMITER
1814 * Called by the menu system to configure the limiter process */
1815 void dsp_set_limiter(int limiter_level)
1817 if (limiter_level > 0)
1819 if (!limiter_buffer_active)
1821 /* enable limiter process */
1822 AUDIO_DSP.limiter_process = limiter_process;
1823 limiter_buffer_active = true;
1825 /* limiter preamp is a gain factor in S7.24 format */
1826 long old_preamp = AUDIO_DSP.limiter_preamp;
1827 long new_preamp = fp_factor((((long)limiter_level << 24) / 10), 24);
1828 if (old_preamp != new_preamp)
1830 AUDIO_DSP.limiter_preamp = new_preamp;
1831 set_gain(&AUDIO_DSP);
1832 logf(" Limiter enable: Yes\tLimiter amp: %.8f",
1833 (float)AUDIO_DSP.limiter_preamp / (1 << 24));
1836 else
1838 /* disable limiter process*/
1839 if (limiter_buffer_active)
1841 AUDIO_DSP.limiter_preamp = (1 << 24);
1842 set_gain(&AUDIO_DSP);
1843 /* pcmbuf_flush_limiter_buffer(); */
1844 limiter_buffer_active = false;
1845 AUDIO_DSP.limiter_process = NULL;
1846 reset_limiter_buffer(&AUDIO_DSP);
1847 logf(" Limiter enable: No\tLimiter amp: %.8f",
1848 (float)AUDIO_DSP.limiter_preamp / (1 << 24));
1853 /** LIMITER PROCESS
1854 * Checks pre-amplified signal for clipped samples and smoothly reduces gain
1855 * around the clipped samples using a preset attack/release schedule.
1857 static int limiter_process(int count, int32_t *buf[])
1859 /* Limiter process passes through if limiter buffer isn't active, or the
1860 * sample depth is too large for safe pre-amping */
1861 if ((!limiter_buffer_active) || (AUDIO_DSP.frac_bits > 29))
1862 return count;
1864 count = set_limiter_buffer(count, buf);
1866 if (count <= 0)
1867 return 0;
1869 const int attack_slope = 15; /* 15:1 ratio between attack and release */
1870 const int buffer_count = limiter_buffer_count(true);
1872 int i, ch;
1873 uint16_t max_peak = 0,
1874 gain_peak,
1875 gain_rem;
1876 long gain;
1878 /* step through limiter buffer in reverse order, in order to find the
1879 * appropriate max_peak for modifying the output buffer */
1880 for (i = buffer_count - 1; i >= 0; i--)
1882 const uint16_t peak_i = lim_buf_peak[(start_peak - lim_buf_peak + i) %
1883 LIMITER_BUFFER_SIZE];
1884 /* if no attack slope, nothing to do */
1885 if ((peak_i == 0) && (max_peak == 0)) continue;
1886 /* if new peak, start attack slope */
1887 if (peak_i >= max_peak)
1889 max_peak = peak_i;
1891 /* keep sloping */
1892 else
1894 if (max_peak > attack_slope)
1895 max_peak -= attack_slope;
1896 else
1897 max_peak = 0;
1900 /* step through output buffer the same way, but this time modifying peak
1901 * values to create a smooth attack slope. */
1902 for (i = count - 1; i >= 0; i--)
1904 /* if no attack slope, nothing to do */
1905 if ((out_buf_peak[i] == 0) && (max_peak == 0)) continue;
1906 /* if new peak, start attack slope */
1907 if (out_buf_peak[i] >= max_peak)
1909 max_peak = out_buf_peak[i];
1911 /* keep sloping */
1912 else
1914 if (max_peak > attack_slope)
1915 max_peak -= attack_slope;
1916 else
1917 max_peak = 0;
1918 out_buf_peak[i] = max_peak;
1921 /* Now step forward through the output buffer, and modify the peak values
1922 * to establish a smooth, slow release slope.*/
1923 for (i = 0; i < count; i++)
1925 /* if no release slope, nothing to do */
1926 if ((out_buf_peak[i] == 0) && (release_peak == 0)) continue;
1927 /* if new peak, start release slope */
1928 if (out_buf_peak[i] >= release_peak)
1930 release_peak = out_buf_peak[i];
1932 /* keep sloping */
1933 else
1935 release_peak--;
1936 out_buf_peak[i] = release_peak;
1939 /* Implement the limiter: adjust gain of the outbound samples by the gain
1940 * amounts in the gain steps array corresponding to the peak values. */
1941 for (i = 0; i < count; i++)
1943 if (out_buf_peak[i] > 0)
1945 gain_peak = (out_buf_peak[i] + 1) / 90;
1946 gain_rem = (out_buf_peak[i] + 1) % 90;
1947 gain = gain_steps[gain_peak];
1948 if ((gain_peak < 48) && (gain_rem > 0))
1949 gain -= gain_rem * ((gain_steps[gain_peak] -
1950 gain_steps[gain_peak + 1]) / 90);
1951 for (ch = 0; ch < AUDIO_DSP.data.num_channels; ch++)
1952 buf[ch][i] = FRACMUL_SHL(buf[ch][i], gain, 3);
1955 return count;