Update several codec Makefiles so that the codec libs build again on Coldfire targets...
[Rockbox.git] / apps / dsp.c
blob94e825c532f44f78b6ff6e339517ef58ccdee8d5
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 Miika Pekkarinen
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
19 #include <inttypes.h>
20 #include <string.h>
21 #include <sound.h>
22 #include "dsp.h"
23 #include "eq.h"
24 #include "kernel.h"
25 #include "playback.h"
26 #include "system.h"
27 #include "settings.h"
28 #include "replaygain.h"
29 #include "debug.h"
31 #ifndef SIMULATOR
32 #include <dsp_asm.h>
33 #endif
35 /* 16-bit samples are scaled based on these constants. The shift should be
36 * no more than 15.
38 #define WORD_SHIFT 12
39 #define WORD_FRACBITS 27
41 #define NATIVE_DEPTH 16
42 #define SAMPLE_BUF_SIZE 256
43 #define RESAMPLE_BUF_SIZE (256 * 4) /* Enough for 11,025 Hz -> 44,100 Hz*/
44 #define DEFAULT_GAIN 0x01000000
46 #if defined(CPU_COLDFIRE) && !defined(SIMULATOR)
48 /* Multiply two S.31 fractional integers and return the sign bit and the
49 * 31 most significant bits of the result.
51 #define FRACMUL(x, y) \
52 ({ \
53 long t; \
54 asm volatile ("mac.l %[a], %[b], %%acc0\n\t" \
55 "movclr.l %%acc0, %[t]\n\t" \
56 : [t] "=r" (t) : [a] "r" (x), [b] "r" (y)); \
57 t; \
60 /* Multiply one S.31-bit and one S8.23 fractional integer and return the
61 * sign bit and the 31 most significant bits of the result.
63 #define FRACMUL_8(x, y) \
64 ({ \
65 long t; \
66 long u; \
67 asm volatile ("mac.l %[a], %[b], %%acc0\n\t" \
68 "move.l %%accext01, %[u]\n\t" \
69 "movclr.l %%acc0, %[t]\n\t" \
70 : [t] "=r" (t), [u] "=r" (u) : [a] "r" (x), [b] "r" (y)); \
71 (t << 8) | (u & 0xff); \
74 /* Multiply one S.31-bit and one S8.23 fractional integer and return the
75 * sign bit and the 31 most significant bits of the result. Load next value
76 * to multiply with into x from s (and increase s); x must contain the
77 * initial value.
79 #define FRACMUL_8_LOOP_PART(x, s, d, y) \
80 { \
81 long u; \
82 asm volatile ("mac.l %[a], %[b], (%[c])+, %[a], %%acc0\n\t" \
83 "move.l %%accext01, %[u]\n\t" \
84 "movclr.l %%acc0, %[t]" \
85 : [a] "+r" (x), [c] "+a" (s), [t] "=r" (d), [u] "=r" (u) \
86 : [b] "r" (y)); \
87 d = (d << 8) | (u & 0xff); \
90 #define FRACMUL_8_LOOP(x, y, s, d) \
91 { \
92 long t; \
93 FRACMUL_8_LOOP_PART(x, s, t, y); \
94 asm volatile ("move.l %[t],(%[d])+" \
95 : [d] "+a" (d)\
96 : [t] "r" (t)); \
99 #define ACC(acc, x, y) \
100 (void)acc; \
101 asm volatile ("mac.l %[a], %[b], %%acc0" \
102 : : [a] "i,r" (x), [b] "i,r" (y));
103 #define GET_ACC(acc) \
104 ({ \
105 long t; \
106 (void)acc; \
107 asm volatile ("movclr.l %%acc0, %[t]" \
108 : [t] "=r" (t)); \
109 t; \
112 #define ACC_INIT(acc, x, y) ACC(acc, x, y)
114 #elif defined(CPU_ARM) && !defined(SIMULATOR)
116 /* Multiply two S.31 fractional integers and return the sign bit and the
117 * 31 most significant bits of the result.
119 #define FRACMUL(x, y) \
120 ({ \
121 long t; \
122 asm volatile ("smull r0, r1, %[a], %[b]\n\t" \
123 "mov %[t], r1, asl #1\n\t" \
124 "orr %[t], %[t], r0, lsr #31\n\t" \
125 : [t] "=r" (t) : [a] "r" (x), [b] "r" (y) : "r0", "r1"); \
126 t; \
129 #define ACC_INIT(acc, x, y) acc = FRACMUL(x, y)
130 #define ACC(acc, x, y) acc += FRACMUL(x, y)
131 #define GET_ACC(acc) acc
133 /* Multiply one S.31-bit and one S8.23 fractional integer and store the
134 * sign bit and the 31 most significant bits of the result to d (and
135 * increase d). Load next value to multiply with into x from s (and
136 * increase s); x must contain the initial value.
138 #define FRACMUL_8_LOOP(x, y, s, d) \
139 ({ \
140 asm volatile ("smull r0, r1, %[a], %[b]\n\t" \
141 "mov %[t], r1, asl #9\n\t" \
142 "orr %[t], %[t], r0, lsr #23\n\t" \
143 : [t] "=r" (*(d)++) : [a] "r" (x), [b] "r" (y) : "r0", "r1"); \
144 x = *(s)++; \
147 #else
149 #define ACC_INIT(acc, x, y) acc = FRACMUL(x, y)
150 #define ACC(acc, x, y) acc += FRACMUL(x, y)
151 #define GET_ACC(acc) acc
152 #define FRACMUL(x, y) (long) (((((long long) (x)) * ((long long) (y))) >> 31))
153 #define FRACMUL_8(x, y) (long) (((((long long) (x)) * ((long long) (y))) >> 23))
154 #define FRACMUL_8_LOOP(x, y, s, d) \
155 ({ \
156 long t = x; \
157 x = *(s)++; \
158 *(d)++ = (long) (((((long long) (t)) * ((long long) (y))) >> 23)); \
161 #endif
163 struct dsp_config
165 long codec_frequency; /* Sample rate of data coming from the codec */
166 long frequency; /* Effective sample rate after pitch shift (if any) */
167 long clip_min;
168 long clip_max;
169 long track_gain;
170 long album_gain;
171 long track_peak;
172 long album_peak;
173 long replaygain;
174 int sample_depth;
175 int sample_bytes;
176 int stereo_mode;
177 int frac_bits;
178 bool dither_enabled;
179 long dither_bias;
180 long dither_mask;
181 bool new_gain;
182 bool crossfeed_enabled;
183 bool eq_enabled;
184 long eq_precut;
185 long gain; /* Note that this is in S8.23 format. */
188 struct resample_data
190 long phase, delta;
191 int32_t last_sample[2];
194 struct dither_data
196 long error[3];
197 long random;
200 struct crossfeed_data
202 int32_t gain; /* Direct path gain */
203 int32_t coefs[3]; /* Coefficients for the shelving filter */
204 int32_t history[4]; /* Format is x[n - 1], y[n - 1] for both channels */
205 int32_t delay[13][2];
206 int index; /* Current index into the delay line */
209 /* Current setup is one lowshelf filters, three peaking filters and one
210 highshelf filter. Varying the number of shelving filters make no sense,
211 but adding peaking filters is possible. */
212 struct eq_state {
213 char enabled[5]; /* Flags for active filters */
214 struct eqfilter filters[5];
217 static struct dsp_config dsp_conf[2] IBSS_ATTR;
218 static struct dither_data dither_data[2] IBSS_ATTR;
219 static struct resample_data resample_data[2] IBSS_ATTR;
220 struct crossfeed_data crossfeed_data IBSS_ATTR;
221 static struct eq_state eq_data;
223 static int pitch_ratio = 1000;
224 static int channels_mode = 0;
225 static int32_t sw_gain, sw_cross;
227 extern int current_codec;
228 struct dsp_config *dsp;
230 /* The internal format is 32-bit samples, non-interleaved, stereo. This
231 * format is similar to the raw output from several codecs, so the amount
232 * of copying needed is minimized for that case.
235 static int32_t sample_buf[SAMPLE_BUF_SIZE] IBSS_ATTR;
236 static int32_t resample_buf[RESAMPLE_BUF_SIZE] IBSS_ATTR;
238 int sound_get_pitch(void)
240 return pitch_ratio;
243 void sound_set_pitch(int permille)
245 pitch_ratio = permille;
247 dsp_configure(DSP_SWITCH_FREQUENCY, (int *)dsp->codec_frequency);
250 /* Convert at most count samples to the internal format, if needed. Returns
251 * number of samples ready for further processing. Updates src to point
252 * past the samples "consumed" and dst is set to point to the samples to
253 * consume. Note that for mono, dst[0] equals dst[1], as there is no point
254 * in processing the same data twice.
256 static int convert_to_internal(const char* src[], int count, int32_t* dst[])
258 count = MIN(SAMPLE_BUF_SIZE / 2, count);
260 if ((dsp->sample_depth <= NATIVE_DEPTH)
261 || (dsp->stereo_mode == STEREO_INTERLEAVED))
263 dst[0] = &sample_buf[0];
264 dst[1] = (dsp->stereo_mode == STEREO_MONO)
265 ? dst[0] : &sample_buf[SAMPLE_BUF_SIZE / 2];
267 else
269 dst[0] = (int32_t*) src[0];
270 dst[1] = (int32_t*) ((dsp->stereo_mode == STEREO_MONO) ? src[0] : src[1]);
273 if (dsp->sample_depth <= NATIVE_DEPTH)
275 short* s0 = (short*) src[0];
276 int32_t* d0 = dst[0];
277 int32_t* d1 = dst[1];
278 int scale = WORD_SHIFT;
279 int i;
281 if (dsp->stereo_mode == STEREO_INTERLEAVED)
283 for (i = 0; i < count; i++)
285 *d0++ = *s0++ << scale;
286 *d1++ = *s0++ << scale;
289 else if (dsp->stereo_mode == STEREO_NONINTERLEAVED)
291 short* s1 = (short*) src[1];
293 for (i = 0; i < count; i++)
295 *d0++ = *s0++ << scale;
296 *d1++ = *s1++ << scale;
299 else
301 for (i = 0; i < count; i++)
303 *d0++ = *s0++ << scale;
307 else if (dsp->stereo_mode == STEREO_INTERLEAVED)
309 int32_t* s0 = (int32_t*) src[0];
310 int32_t* d0 = dst[0];
311 int32_t* d1 = dst[1];
312 int i;
314 for (i = 0; i < count; i++)
316 *d0++ = *s0++;
317 *d1++ = *s0++;
321 if (dsp->stereo_mode == STEREO_NONINTERLEAVED)
323 src[0] += count * dsp->sample_bytes;
324 src[1] += count * dsp->sample_bytes;
326 else if (dsp->stereo_mode == STEREO_INTERLEAVED)
328 src[0] += count * dsp->sample_bytes * 2;
330 else
332 src[0] += count * dsp->sample_bytes;
335 return count;
338 static void resampler_set_delta(int frequency)
340 resample_data[current_codec].delta = (unsigned long)
341 frequency * 65536LL / NATIVE_FREQUENCY;
344 /* Linear interpolation resampling that introduces a one sample delay because
345 * of our inability to look into the future at the end of a frame.
348 /* TODO: we really should have a separate set of resample functions for both
349 mono and stereo to avoid all this internal branching and looping. */
350 static long downsample(int32_t **dst, int32_t **src, int count,
351 struct resample_data *r)
353 long phase = r->phase;
354 long delta = r->delta;
355 int32_t last_sample;
356 int32_t *d[2] = { dst[0], dst[1] };
357 int pos = phase >> 16;
358 int i = 1, j;
359 int num_channels = dsp->stereo_mode == STEREO_MONO ? 1 : 2;
361 for (j = 0; j < num_channels; j++) {
362 last_sample = r->last_sample[j];
363 /* Do we need last sample of previous frame for interpolation? */
364 if (pos > 0)
366 last_sample = src[j][pos - 1];
368 *d[j]++ = last_sample + FRACMUL((phase & 0xffff) << 15,
369 src[j][pos] - last_sample);
371 phase += delta;
373 while ((pos = phase >> 16) < count)
375 for (j = 0; j < num_channels; j++)
376 *d[j]++ = src[j][pos - 1] + FRACMUL((phase & 0xffff) << 15,
377 src[j][pos] - src[j][pos - 1]);
378 phase += delta;
379 i++;
382 /* Wrap phase accumulator back to start of next frame. */
383 r->phase = phase - (count << 16);
384 r->delta = delta;
385 r->last_sample[0] = src[0][count - 1];
386 r->last_sample[1] = src[1][count - 1];
387 return i;
390 static long upsample(int32_t **dst, int32_t **src, int count, struct resample_data *r)
392 long phase = r->phase;
393 long delta = r->delta;
394 int32_t *d[2] = { dst[0], dst[1] };
395 int i = 0, j;
396 int pos;
397 int num_channels = dsp->stereo_mode == STEREO_MONO ? 1 : 2;
399 while ((pos = phase >> 16) == 0)
401 for (j = 0; j < num_channels; j++)
402 *d[j]++ = r->last_sample[j] + FRACMUL((phase & 0xffff) << 15,
403 src[j][pos] - r->last_sample[j]);
404 phase += delta;
405 i++;
408 while ((pos = phase >> 16) < count)
410 for (j = 0; j < num_channels; j++)
411 *d[j]++ = src[j][pos - 1] + FRACMUL((phase & 0xffff) << 15,
412 src[j][pos] - src[j][pos - 1]);
413 phase += delta;
414 i++;
417 /* Wrap phase accumulator back to start of next frame. */
418 r->phase = phase - (count << 16);
419 r->delta = delta;
420 r->last_sample[0] = src[0][count - 1];
421 r->last_sample[1] = src[1][count - 1];
422 return i;
425 /* Resample count stereo samples. Updates the src array, if resampling is
426 * done, to refer to the resampled data. Returns number of stereo samples
427 * for further processing.
429 static inline int resample(int32_t* src[], int count)
431 long new_count;
433 if (dsp->frequency != NATIVE_FREQUENCY)
435 int32_t* dst[2] = {&resample_buf[0], &resample_buf[RESAMPLE_BUF_SIZE / 2]};
437 if (dsp->frequency < NATIVE_FREQUENCY)
439 new_count = upsample(dst, src, count,
440 &resample_data[current_codec]);
442 else
444 new_count = downsample(dst, src, count,
445 &resample_data[current_codec]);
448 src[0] = dst[0];
449 if (dsp->stereo_mode != STEREO_MONO)
450 src[1] = dst[1];
451 else
452 src[1] = dst[0];
454 else
456 new_count = count;
459 return new_count;
462 static inline long clip_sample(int32_t sample, int32_t min, int32_t max)
464 if (sample > max)
466 sample = max;
468 else if (sample < min)
470 sample = min;
473 return sample;
476 /* The "dither" code to convert the 24-bit samples produced by libmad was
477 * taken from the coolplayer project - coolplayer.sourceforge.net
480 void dsp_dither_enable(bool enable)
482 dsp->dither_enabled = enable;
485 static void dither_init(void)
487 memset(&dither_data[0], 0, sizeof(dither_data));
488 memset(&dither_data[1], 0, sizeof(dither_data));
489 dsp->dither_bias = (1L << (dsp->frac_bits - NATIVE_DEPTH));
490 dsp->dither_mask = (1L << (dsp->frac_bits + 1 - NATIVE_DEPTH)) - 1;
493 static void dither_samples(int32_t* src, int num, struct dither_data* dither)
495 int32_t output, sample;
496 int32_t random;
497 int32_t min, max;
498 long mask = dsp->dither_mask;
499 long bias = dsp->dither_bias;
500 int i;
502 for (i = 0; i < num; ++i) {
503 /* Noise shape and bias */
504 sample = src[i];
505 sample += dither->error[0] - dither->error[1] + dither->error[2];
506 dither->error[2] = dither->error[1];
507 dither->error[1] = dither->error[0]/2;
509 output = sample + bias;
511 /* Dither */
512 random = dither->random*0x0019660dL + 0x3c6ef35fL;
513 output += (random & mask) - (dither->random & mask);
514 dither->random = random;
516 /* Clip and quantize */
517 min = dsp->clip_min;
518 max = dsp->clip_max;
519 if (output > max) {
520 output = max;
521 if (sample > max)
522 sample = max;
523 } else if (output < min) {
524 output = min;
525 if (sample < min)
526 sample = min;
528 output &= ~mask;
530 /* Error feedback */
531 dither->error[0] = sample - output;
532 src[i] = output;
536 void dsp_set_crossfeed(bool enable)
538 dsp->crossfeed_enabled = enable;
541 void dsp_set_crossfeed_direct_gain(int gain)
543 /* Work around bug in get_replaygain_int which returns 0 for 0 dB */
544 if (gain == 0)
545 crossfeed_data.gain = 0x7fffffff;
546 else
547 crossfeed_data.gain = get_replaygain_int(gain * -10) << 7;
550 void dsp_set_crossfeed_cross_params(long lf_gain, long hf_gain, long cutoff)
552 long g1 = get_replaygain_int(lf_gain * -10) << 3;
553 long g2 = get_replaygain_int(hf_gain * -10) << 3;
555 filter_bishelf_coefs(0xffffffff/NATIVE_FREQUENCY*cutoff, g1, g2,
556 crossfeed_data.coefs);
559 /* Applies crossfeed to the stereo signal in src.
560 * Crossfeed is a process where listening over speakers is simulated. This
561 * is good for old hard panned stereo records, which might be quite fatiguing
562 * to listen to on headphones with no crossfeed.
564 #ifndef DSP_HAVE_ASM_CROSSFEED
565 void apply_crossfeed(int32_t* src[], int count)
567 int32_t *hist_l = &crossfeed_data.history[0];
568 int32_t *hist_r = &crossfeed_data.history[2];
569 int32_t *delay = &crossfeed_data.delay[0][0];
570 int32_t *coefs = &crossfeed_data.coefs[0];
571 int32_t gain = crossfeed_data.gain;
572 int di = crossfeed_data.index;
574 int32_t acc;
575 int32_t left, right;
576 int i;
578 for (i = 0; i < count; i++) {
579 left = src[0][i];
580 right = src[1][i];
582 /* Filter delayed sample from left speaker */
583 ACC_INIT(acc, delay[di*2], coefs[0]);
584 ACC(acc, hist_l[0], coefs[1]);
585 ACC(acc, hist_l[1], coefs[2]);
586 /* Save filter history for left speaker */
587 hist_l[1] = GET_ACC(acc);
588 hist_l[0] = delay[di*2];
589 /* Filter delayed sample from right speaker */
590 ACC_INIT(acc, delay[di*2 + 1], coefs[0]);
591 ACC(acc, hist_r[0], coefs[1]);
592 ACC(acc, hist_r[1], coefs[2]);
593 /* Save filter history for right speaker */
594 hist_r[1] = GET_ACC(acc);
595 hist_r[0] = delay[di*2 + 1];
596 delay[di*2] = left;
597 delay[di*2 + 1] = right;
598 /* Now add the attenuated direct sound and write to outputs */
599 src[0][i] = FRACMUL(left, gain) + hist_r[1];
600 src[1][i] = FRACMUL(right, gain) + hist_l[1];
602 /* Wrap delay line index if bigger than delay line size */
603 if (++di > 12)
604 di = 0;
606 /* Write back local copies of data we've modified */
607 crossfeed_data.index = di;
609 #endif
611 /* Combine all gains to a global gain. */
612 static void set_gain(void)
614 dsp->gain = DEFAULT_GAIN;
616 if (dsp->replaygain)
618 dsp->gain = dsp->replaygain;
621 if (dsp->eq_enabled && dsp->eq_precut)
623 dsp->gain = (long) (((int64_t) dsp->gain * dsp->eq_precut) >> 24);
626 if (dsp->gain == DEFAULT_GAIN)
628 dsp->gain = 0;
630 else
632 dsp->gain >>= 1;
637 * Use to enable the equalizer.
639 * @param enable true to enable the equalizer
641 void dsp_set_eq(bool enable)
643 dsp->eq_enabled = enable;
647 * Update the amount to cut the audio before applying the equalizer.
649 * @param precut to apply in decibels (multiplied by 10)
651 void dsp_set_eq_precut(int precut)
653 dsp->eq_precut = get_replaygain_int(precut * -10);
654 set_gain();
658 * Synchronize the equalizer filter coefficients with the global settings.
660 * @param band the equalizer band to synchronize
662 void dsp_set_eq_coefs(int band)
664 const int *setting;
665 long gain;
666 unsigned long cutoff, q;
668 /* Adjust setting pointer to the band we actually want to change */
669 setting = &global_settings.eq_band0_cutoff + (band * 3);
671 /* Convert user settings to format required by coef generator functions */
672 cutoff = 0xffffffff / NATIVE_FREQUENCY * (*setting++);
673 q = ((*setting++) << 16) / 10; /* 16.16 */
674 gain = ((*setting++) << 16) / 10; /* s15.16 */
676 if (q == 0)
677 q = 1;
679 /* NOTE: The coef functions assume the EMAC unit is in fractional mode,
680 which it should be, since we're executed from the main thread. */
682 /* Assume a band is disabled if the gain is zero */
683 if (gain == 0) {
684 eq_data.enabled[band] = 0;
685 } else {
686 if (band == 0)
687 eq_ls_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
688 else if (band == 4)
689 eq_hs_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
690 else
691 eq_pk_coefs(cutoff, q, gain, eq_data.filters[band].coefs);
693 eq_data.enabled[band] = 1;
697 /* Apply EQ filters to those bands that have got it switched on. */
698 static void eq_process(int32_t **x, unsigned num)
700 int i;
701 unsigned int channels = dsp->stereo_mode != STEREO_MONO ? 2 : 1;
702 unsigned shift;
704 /* filter configuration currently is 1 low shelf filter, 3 band peaking
705 filters and 1 high shelf filter, in that order. we need to know this
706 so we can choose the correct shift factor.
708 for (i = 0; i < 5; i++) {
709 if (eq_data.enabled[i]) {
710 if (i == 0 || i == 4) /* shelving filters */
711 shift = EQ_SHELF_SHIFT;
712 else
713 shift = EQ_PEAK_SHIFT;
714 eq_filter(x, &eq_data.filters[i], num, channels, shift);
719 /* Apply a constant gain to the samples (e.g., for ReplayGain). May update
720 * the src array if gain was applied.
721 * Note that this must be called before the resampler.
723 static void apply_gain(int32_t* _src[], int _count)
725 if (dsp->gain)
727 int32_t** src = _src;
728 int count = _count;
729 int32_t* s0 = src[0];
730 int32_t* s1 = src[1];
731 long gain = dsp->gain;
732 int32_t s;
733 int i;
734 int32_t *d;
736 if (s0 != s1)
738 d = &sample_buf[SAMPLE_BUF_SIZE / 2];
739 src[1] = d;
740 s = *s1++;
742 for (i = 0; i < count; i++)
743 FRACMUL_8_LOOP(s, gain, s1, d);
745 else
747 src[1] = &sample_buf[0];
750 d = &sample_buf[0];
751 src[0] = d;
752 s = *s0++;
754 for (i = 0; i < count; i++)
755 FRACMUL_8_LOOP(s, gain, s0, d);
759 void channels_set(int value)
761 channels_mode = value;
764 void stereo_width_set(int value)
766 long width, straight, cross;
768 width = value * 0x7fffff / 100;
769 if (value <= 100) {
770 straight = (0x7fffff + width) / 2;
771 cross = straight - width;
772 } else {
773 /* straight = (1 + width) / (2 * width) */
774 straight = ((int64_t)(0x7fffff + width) << 22) / width;
775 cross = straight - 0x7fffff;
777 sw_gain = straight << 8;
778 sw_cross = cross << 8;
781 /* Implements the different channel configurations and stereo width.
782 * We might want to combine this with the write_samples stage for efficiency,
783 * but for now we'll just let it stay as a stage of its own.
785 static void channels_process(int32_t **src, int num)
787 int i;
788 int32_t *sl = src[0], *sr = src[1];
790 if (channels_mode == SOUND_CHAN_STEREO)
791 return;
792 switch (channels_mode) {
793 case SOUND_CHAN_MONO:
794 for (i = 0; i < num; i++)
795 sl[i] = sr[i] = sl[i]/2 + sr[i]/2;
796 break;
797 case SOUND_CHAN_CUSTOM:
798 for (i = 0; i < num; i++) {
799 int32_t left_sample = sl[i];
801 sl[i] = FRACMUL(sl[i], sw_gain) + FRACMUL(sr[i], sw_cross);
802 sr[i] = FRACMUL(sr[i], sw_gain) + FRACMUL(left_sample, sw_cross);
804 break;
805 case SOUND_CHAN_MONO_LEFT:
806 for (i = 0; i < num; i++)
807 sr[i] = sl[i];
808 break;
809 case SOUND_CHAN_MONO_RIGHT:
810 for (i = 0; i < num; i++)
811 sl[i] = sr[i];
812 break;
813 case SOUND_CHAN_KARAOKE:
814 for (i = 0; i < num; i++) {
815 int32_t left_sample = sl[i]/2;
817 sl[i] = left_sample - sr[i]/2;
818 sr[i] = sr[i]/2 - left_sample;
820 break;
824 static void write_samples(short* dst, int32_t* src[], int count)
826 int32_t* s0 = src[0];
827 int32_t* s1 = src[1];
828 int scale = dsp->frac_bits + 1 - NATIVE_DEPTH;
830 if (dsp->dither_enabled)
832 dither_samples(src[0], count, &dither_data[0]);
833 dither_samples(src[1], count, &dither_data[1]);
835 while (count-- > 0)
837 *dst++ = (short) (*s0++ >> scale);
838 *dst++ = (short) (*s1++ >> scale);
841 else
843 long min = dsp->clip_min;
844 long max = dsp->clip_max;
846 while (count-- > 0)
848 *dst++ = (short) (clip_sample(*s0++, min, max) >> scale);
849 *dst++ = (short) (clip_sample(*s1++, min, max) >> scale);
854 /* Process and convert src audio to dst based on the DSP configuration,
855 * reading size bytes of audio data. dst is assumed to be large enough; use
856 * dst_get_dest_size() to get the required size. src is an array of
857 * pointers; for mono and interleaved stereo, it contains one pointer to the
858 * start of the audio data; for non-interleaved stereo, it contains two
859 * pointers, one for each audio channel. Returns number of bytes written to
860 * dest.
862 long dsp_process(char* dst, const char* src[], long size)
864 int32_t* tmp[2];
865 long written = 0;
866 long factor;
867 int samples;
869 #if defined(CPU_COLDFIRE) && !defined(SIMULATOR)
870 /* set emac unit for dsp processing, and save old macsr, we're running in
871 codec thread context at this point, so can't clobber it */
872 unsigned long old_macsr = coldfire_get_macsr();
873 coldfire_set_macsr(EMAC_FRACTIONAL | EMAC_SATURATE);
874 #endif
876 dsp = &dsp_conf[current_codec];
878 factor = (dsp->stereo_mode != STEREO_MONO) ? 2 : 1;
879 size /= dsp->sample_bytes * factor;
880 dsp_set_replaygain(false);
882 while (size > 0)
884 samples = convert_to_internal(src, size, tmp);
885 size -= samples;
886 apply_gain(tmp, samples);
887 samples = resample(tmp, samples);
888 if (dsp->crossfeed_enabled && dsp->stereo_mode != STEREO_MONO)
889 apply_crossfeed(tmp, samples);
890 if (dsp->eq_enabled)
891 eq_process(tmp, samples);
892 if (dsp->stereo_mode != STEREO_MONO)
893 channels_process(tmp, samples);
894 write_samples((short*) dst, tmp, samples);
895 written += samples;
896 dst += samples * sizeof(short) * 2;
897 yield();
899 #if defined(CPU_COLDFIRE) && !defined(SIMULATOR)
900 /* set old macsr again */
901 coldfire_set_macsr(old_macsr);
902 #endif
903 return written * sizeof(short) * 2;
906 /* Given size bytes of input data, calculate the maximum number of bytes of
907 * output data that would be generated (the calculation is not entirely
908 * exact and rounds upwards to be on the safe side; during resampling,
909 * the number of samples generated depends on the current state of the
910 * resampler).
912 /* dsp_input_size MUST be called afterwards */
913 long dsp_output_size(long size)
915 dsp = &dsp_conf[current_codec];
917 if (dsp->sample_depth > NATIVE_DEPTH)
919 size /= 2;
922 if (dsp->frequency != NATIVE_FREQUENCY)
924 size = (long) ((((unsigned long) size * NATIVE_FREQUENCY)
925 + (dsp->frequency - 1)) / dsp->frequency);
928 /* round to the next multiple of 2 (these are shorts) */
929 size = (size + 1) & ~1;
931 if (dsp->stereo_mode == STEREO_MONO)
933 size *= 2;
936 /* now we have the size in bytes for two resampled channels,
937 * and the size in (short) must not exceed RESAMPLE_BUF_SIZE to
938 * avoid resample buffer overflow. One must call dsp_input_size()
939 * to get the correct input buffer size. */
940 if (size > RESAMPLE_BUF_SIZE*2)
941 size = RESAMPLE_BUF_SIZE*2;
943 return size;
946 /* Given size bytes of output buffer, calculate number of bytes of input
947 * data that would be consumed in order to fill the output buffer.
949 long dsp_input_size(long size)
951 dsp = &dsp_conf[current_codec];
953 /* convert to number of output stereo samples. */
954 size /= 2;
956 /* Mono means we need half input samples to fill the output buffer */
957 if (dsp->stereo_mode == STEREO_MONO)
958 size /= 2;
960 /* size is now the number of resampled input samples. Convert to
961 original input samples. */
962 if (dsp->frequency != NATIVE_FREQUENCY)
964 /* Use the real resampling delta =
965 * (unsigned long) dsp->frequency * 65536 / NATIVE_FREQUENCY, and
966 * round towards zero to avoid buffer overflows. */
967 size = ((unsigned long)size *
968 resample_data[current_codec].delta) >> 16;
971 /* Convert back to bytes. */
972 if (dsp->sample_depth > NATIVE_DEPTH)
973 size *= 4;
974 else
975 size *= 2;
977 return size;
980 int dsp_stereo_mode(void)
982 dsp = &dsp_conf[current_codec];
984 return dsp->stereo_mode;
987 bool dsp_configure(int setting, void *value)
989 dsp = &dsp_conf[current_codec];
991 switch (setting)
993 case DSP_SET_FREQUENCY:
994 memset(&resample_data[current_codec], 0,
995 sizeof(struct resample_data));
996 /* Fall through!!! */
997 case DSP_SWITCH_FREQUENCY:
998 dsp->codec_frequency = ((long) value == 0) ? NATIVE_FREQUENCY : (long) value;
999 /* Account for playback speed adjustment when setting dsp->frequency
1000 if we're called from the main audio thread. Voice UI thread should
1001 not need this feature.
1003 if (current_codec == CODEC_IDX_AUDIO)
1004 dsp->frequency = pitch_ratio * dsp->codec_frequency / 1000;
1005 else
1006 dsp->frequency = dsp->codec_frequency;
1007 resampler_set_delta(dsp->frequency);
1008 break;
1010 case DSP_SET_CLIP_MIN:
1011 dsp->clip_min = (long) value;
1012 break;
1014 case DSP_SET_CLIP_MAX:
1015 dsp->clip_max = (long) value;
1016 break;
1018 case DSP_SET_SAMPLE_DEPTH:
1019 dsp->sample_depth = (long) value;
1021 if (dsp->sample_depth <= NATIVE_DEPTH)
1023 dsp->frac_bits = WORD_FRACBITS;
1024 dsp->sample_bytes = sizeof(short);
1025 dsp->clip_max = ((1 << WORD_FRACBITS) - 1);
1026 dsp->clip_min = -((1 << WORD_FRACBITS));
1028 else
1030 dsp->frac_bits = (long) value;
1031 dsp->sample_bytes = 4; /* samples are 32 bits */
1032 dsp->clip_max = (1 << (long)value) - 1;
1033 dsp->clip_min = -(1 << (long)value);
1036 dither_init();
1037 break;
1039 case DSP_SET_STEREO_MODE:
1040 dsp->stereo_mode = (long) value;
1041 break;
1043 case DSP_RESET:
1044 dsp->stereo_mode = STEREO_NONINTERLEAVED;
1045 dsp->clip_max = ((1 << WORD_FRACBITS) - 1);
1046 dsp->clip_min = -((1 << WORD_FRACBITS));
1047 dsp->track_gain = 0;
1048 dsp->album_gain = 0;
1049 dsp->track_peak = 0;
1050 dsp->album_peak = 0;
1051 dsp->codec_frequency = dsp->frequency = NATIVE_FREQUENCY;
1052 dsp->sample_depth = NATIVE_DEPTH;
1053 dsp->frac_bits = WORD_FRACBITS;
1054 dsp->new_gain = true;
1055 break;
1057 case DSP_SET_TRACK_GAIN:
1058 dsp->track_gain = (long) value;
1059 dsp->new_gain = true;
1060 break;
1062 case DSP_SET_ALBUM_GAIN:
1063 dsp->album_gain = (long) value;
1064 dsp->new_gain = true;
1065 break;
1067 case DSP_SET_TRACK_PEAK:
1068 dsp->track_peak = (long) value;
1069 dsp->new_gain = true;
1070 break;
1072 case DSP_SET_ALBUM_PEAK:
1073 dsp->album_peak = (long) value;
1074 dsp->new_gain = true;
1075 break;
1077 default:
1078 return 0;
1081 return 1;
1084 void dsp_set_replaygain(bool always)
1086 dsp = &dsp_conf[current_codec];
1088 if (always || dsp->new_gain)
1090 long gain = 0;
1092 dsp->new_gain = false;
1094 if (global_settings.replaygain || global_settings.replaygain_noclip)
1096 bool track_mode
1097 = ((global_settings.replaygain_type == REPLAYGAIN_TRACK)
1098 || ((global_settings.replaygain_type == REPLAYGAIN_SHUFFLE)
1099 && global_settings.playlist_shuffle));
1100 long peak = (track_mode || !dsp->album_peak)
1101 ? dsp->track_peak : dsp->album_peak;
1103 if (global_settings.replaygain)
1105 gain = (track_mode || !dsp->album_gain)
1106 ? dsp->track_gain : dsp->album_gain;
1108 if (global_settings.replaygain_preamp)
1110 long preamp = get_replaygain_int(
1111 global_settings.replaygain_preamp * 10);
1113 gain = (long) (((int64_t) gain * preamp) >> 24);
1117 if (gain == 0)
1119 /* So that noclip can work even with no gain information. */
1120 gain = DEFAULT_GAIN;
1123 if (global_settings.replaygain_noclip && (peak != 0)
1124 && ((((int64_t) gain * peak) >> 24) >= DEFAULT_GAIN))
1126 gain = (((int64_t) DEFAULT_GAIN << 24) / peak);
1129 if (gain == DEFAULT_GAIN)
1131 /* Nothing to do, disable processing. */
1132 gain = 0;
1137 /* Store in S8.23 format to simplify calculations. */
1138 dsp->replaygain = gain;
1139 set_gain();