2 * Copyright (c) 1999 Cameron Grant <cg@FreeBSD.org>
3 * Copyright (c) 2003 Orion Hodson <orion@FreeBSD.org>
4 * Copyright (c) 2005 Ariff Abdullah <ariff@FreeBSD.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * *New* and rewritten soft sample rate converter supporting arbitrary sample
32 * rates, fine grained scaling/coefficients and a unified up/down stereo
33 * converter. Most of the disclaimers from orion's notes also applies
34 * here, regarding linear interpolation deficiencies and pre/post
35 * anti-aliasing filtering issues. This version comes with a much simpler and
36 * tighter interface, although it works almost exactly like the older one.
38 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
40 * This new implementation is fully dedicated in memory of Cameron Grant, *
41 * the creator of the magnificent, highly addictive feeder infrastructure. *
43 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
48 * This rate conversion code uses linear interpolation without any
49 * pre- or post- interpolation filtering to combat aliasing. This
50 * greatly limits the sound quality and should be addressed at some
51 * stage in the future.
53 * Since this accuracy of interpolation is sensitive and examination
54 * of the algorithm output is harder from the kernel, the code is
55 * designed to be compiled in the kernel and in a userland test
56 * harness. This is done by selectively including and excluding code
57 * with several portions based on whether _KERNEL is defined. It's a
58 * little ugly, but exceedingly useful. The testsuite and its
59 * revisions can be found at:
60 * http://people.freebsd.org/~orion/files/feedrate/
62 * Special thanks to Ken Marx for exposing flaws in the code and for
65 * $FreeBSD: src/sys/dev/sound/pcm/feeder_rate.c,v 1.11.2.2 2006/01/29 02:27:28 ariff Exp $
68 #include <dev/sound/pcm/sound.h>
69 #include "feeder_if.h"
71 SND_DECLARE_FILE("$DragonFly: src/sys/dev/sound/pcm/feeder_rate.c,v 1.5 2007/01/04 21:47:03 corecode Exp $");
73 #define RATE_ASSERT(x, y) /* KASSERT(x,y) */
74 #define RATE_TEST(x, y) /* if (!(x)) printf y */
75 #define RATE_TRACE(x...) /* printf(x) */
77 MALLOC_DEFINE(M_RATEFEEDER, "ratefeed", "pcm rate feeder");
79 #define FEEDBUFSZ 8192
82 /* 8000 * 138 or 11025 * 100 . This is insane, indeed! */
83 #define RATEMAX 1102500
87 #define FEEDRATE_CONVERT_64 0
88 #define FEEDRATE_CONVERT_SCALE64 1
89 #define FEEDRATE_CONVERT_SCALE32 2
90 #define FEEDRATE_CONVERT_PLAIN 3
91 #define FEEDRATE_CONVERT_FIXED 4
92 #define FEEDRATE_CONVERT_OPTIMAL 5
93 #define FEEDRATE_CONVERT_WORST 6
95 #define FEEDRATE_64_MAXROLL 32
96 #define FEEDRATE_32_MAXROLL 16
98 struct feed_rate_info {
99 uint32_t src, dst; /* rounded source / destination rates */
100 uint32_t rsrc, rdst; /* original source / destination rates */
101 uint32_t gx, gy; /* interpolation / decimation ratio */
102 uint32_t alpha; /* interpolation distance */
103 uint32_t pos, bpos; /* current sample / buffer positions */
104 uint32_t bufsz; /* total buffer size */
105 uint32_t stray; /* stray bytes */
106 int32_t scale, roll; /* scale / roll factor */
108 uint32_t (*convert)(struct feed_rate_info *, int16_t *, uint32_t);
112 feed_convert_64(struct feed_rate_info *, int16_t *, uint32_t);
114 feed_convert_scale64(struct feed_rate_info *, int16_t *, uint32_t);
116 feed_convert_scale32(struct feed_rate_info *, int16_t *, uint32_t);
118 feed_convert_plain(struct feed_rate_info *, int16_t *, uint32_t);
120 int feeder_rate_ratemin = RATEMIN;
121 int feeder_rate_ratemax = RATEMAX;
123 * See 'Feeder Scaling Type' below..
125 static int feeder_rate_scaling = FEEDRATE_CONVERT_OPTIMAL;
126 static int feeder_rate_buffersize = FEEDBUFSZ & ~1;
130 * sysctls.. I love sysctls..
132 TUNABLE_INT("hw.snd.feeder_rate_ratemin", &feeder_rate_ratemin);
133 TUNABLE_INT("hw.snd.feeder_rate_ratemax", &feeder_rate_ratemin);
134 TUNABLE_INT("hw.snd.feeder_rate_scaling", &feeder_rate_scaling);
135 TUNABLE_INT("hw.snd.feeder_rate_buffersize", &feeder_rate_buffersize);
138 sysctl_hw_snd_feeder_rate_ratemin(SYSCTL_HANDLER_ARGS)
142 val = feeder_rate_ratemin;
143 err = sysctl_handle_int(oidp, &val, sizeof(val), req);
144 if (val < 1 || val >= feeder_rate_ratemax)
147 feeder_rate_ratemin = val;
150 SYSCTL_PROC(_hw_snd, OID_AUTO, feeder_rate_ratemin, CTLTYPE_INT | CTLFLAG_RW,
151 0, sizeof(int), sysctl_hw_snd_feeder_rate_ratemin, "I", "");
154 sysctl_hw_snd_feeder_rate_ratemax(SYSCTL_HANDLER_ARGS)
158 val = feeder_rate_ratemax;
159 err = sysctl_handle_int(oidp, &val, sizeof(val), req);
160 if (val <= feeder_rate_ratemin || val > 0x7fffff)
163 feeder_rate_ratemax = val;
166 SYSCTL_PROC(_hw_snd, OID_AUTO, feeder_rate_ratemax, CTLTYPE_INT | CTLFLAG_RW,
167 0, sizeof(int), sysctl_hw_snd_feeder_rate_ratemax, "I", "");
170 sysctl_hw_snd_feeder_rate_scaling(SYSCTL_HANDLER_ARGS)
174 val = feeder_rate_scaling;
175 err = sysctl_handle_int(oidp, &val, sizeof(val), req);
177 * Feeder Scaling Type
178 * ===================
180 * 1. Plain 64bit (high precision)
181 * 2. 64bit scaling (high precision, CPU friendly, but can
182 * cause gain up/down).
183 * 3. 32bit scaling (somehow can cause hz roundup, gain
185 * 4. Plain copy (default if src == dst. Except if src == dst,
186 * this is the worst / silly conversion method!).
190 * 0 - Plain 64bit - no fallback.
191 * 1 - 64bit scaling - no fallback.
192 * 2 - 32bit scaling - no fallback.
193 * 3 - Plain copy - no fallback.
194 * 4 - Fixed rate. Means that, choose optimal conversion method
195 * without causing hz roundup.
196 * 32bit scaling (as long as hz roundup does not occur),
197 * 64bit scaling, Plain 64bit.
198 * 5 - Optimal / CPU friendly (DEFAULT).
199 * 32bit scaling, 64bit scaling, Plain 64bit
200 * 6 - Optimal to worst, no 64bit arithmetic involved.
201 * 32bit scaling, Plain copy.
203 if (val < FEEDRATE_CONVERT_64 || val > FEEDRATE_CONVERT_WORST)
206 feeder_rate_scaling = val;
209 SYSCTL_PROC(_hw_snd, OID_AUTO, feeder_rate_scaling, CTLTYPE_INT | CTLFLAG_RW,
210 0, sizeof(int), sysctl_hw_snd_feeder_rate_scaling, "I", "");
213 sysctl_hw_snd_feeder_rate_buffersize(SYSCTL_HANDLER_ARGS)
217 val = feeder_rate_buffersize;
218 err = sysctl_handle_int(oidp, &val, sizeof(val), req);
220 * Don't waste too much kernel space
222 if (val < 2 || val > 65536)
225 feeder_rate_buffersize = val & ~1;
228 SYSCTL_PROC(_hw_snd, OID_AUTO, feeder_rate_buffersize, CTLTYPE_INT | CTLFLAG_RW,
229 0, sizeof(int), sysctl_hw_snd_feeder_rate_buffersize, "I", "");
233 feed_speed_ratio(uint32_t x, uint32_t y, uint32_t *gx, uint32_t *gy)
235 uint32_t w, src = x, dst = y;
247 feed_scale_roll(uint32_t dst, int32_t *scale, int32_t *roll, int32_t max)
253 for (j = MAXGAIN; j >= MINGAIN; j -= 3) {
254 for (troll = 0; troll < max; troll++) {
255 tscale = (1 << troll) / dst;
256 k = (tscale * dst * 100) >> troll;
257 if (k > j && k <= 100) {
267 feed_get_best_coef(uint32_t *src, uint32_t *dst, uint32_t *gx, uint32_t *gy,
268 int32_t *scale, int32_t *roll)
270 uint32_t tsrc, tdst, sscale, dscale;
271 int32_t tscale, troll;
272 int i, j, hzmin, hzmax;
275 for (i = 0; i < 2; i++) {
276 hzmin = (ROUNDHZ * i) + 1;
277 hzmax = hzmin + ROUNDHZ;
278 for (j = hzmin; j < hzmax; j++) {
279 tsrc = *src - (*src % j);
281 if (tsrc < 1 || tdst < 1)
283 feed_speed_ratio(tsrc, tdst, &sscale, &dscale);
284 feed_scale_roll(dscale, &tscale, &troll,
285 FEEDRATE_32_MAXROLL);
286 if (tscale != -1 && troll != -1) {
295 for (j = hzmin; j < hzmax; j++) {
296 tsrc = *src - (*src % j);
297 tdst = *dst - (*dst % j);
298 if (tsrc < 1 || tdst < 1)
300 feed_speed_ratio(tsrc, tdst, &sscale, &dscale);
301 feed_scale_roll(dscale, &tscale, &troll,
302 FEEDRATE_32_MAXROLL);
303 if (tscale != -1 && troll != -1) {
313 for (j = hzmin; j < hzmax; j++) {
315 tdst = *dst - (*dst % j);
316 if (tsrc < 1 || tdst < 1)
318 feed_speed_ratio(tsrc, tdst, &sscale, &dscale);
319 feed_scale_roll(dscale, &tscale, &troll,
320 FEEDRATE_32_MAXROLL);
321 if (tscale != -1 && troll != -1) {
333 feed_speed_ratio(*src, *dst, gx, gy);
334 feed_scale_roll(*gy, scale, roll, FEEDRATE_32_MAXROLL);
339 feed_rate_reset(struct feed_rate_info *info)
343 info->src = info->rsrc;
344 info->dst = info->rdst;
350 feed_rate_setup(struct pcm_feeder *f)
352 struct feed_rate_info *info = f->data;
359 feed_rate_reset(info);
360 if (info->src == info->dst) {
362 * No conversion ever needed. Just do plain copy.
364 info->convert = feed_convert_plain;
368 switch (feeder_rate_scaling) {
369 case FEEDRATE_CONVERT_64:
370 feed_speed_ratio(info->src, info->dst,
371 &info->gx, &info->gy);
372 info->convert = feed_convert_64;
374 case FEEDRATE_CONVERT_SCALE64:
375 feed_speed_ratio(info->src, info->dst,
376 &info->gx, &info->gy);
377 feed_scale_roll(info->gy, &info->scale,
378 &info->roll, FEEDRATE_64_MAXROLL);
379 if (info->scale == -1 || info->roll == -1)
381 info->convert = feed_convert_scale64;
383 case FEEDRATE_CONVERT_SCALE32:
384 r = feed_get_best_coef(&info->src, &info->dst,
385 &info->gx, &info->gy, &info->scale,
389 info->convert = feed_convert_scale32;
391 case FEEDRATE_CONVERT_PLAIN:
392 feed_speed_ratio(info->src, info->dst,
393 &info->gx, &info->gy);
394 info->convert = feed_convert_plain;
396 case FEEDRATE_CONVERT_FIXED:
397 r = feed_get_best_coef(&info->src, &info->dst,
398 &info->gx, &info->gy, &info->scale,
400 if (r != 0 && info->src == info->rsrc &&
401 info->dst == info->rdst)
402 info->convert = feed_convert_scale32;
405 feed_rate_reset(info);
406 feed_speed_ratio(info->src, info->dst,
407 &info->gx, &info->gy);
408 feed_scale_roll(info->gy, &info->scale,
409 &info->roll, FEEDRATE_64_MAXROLL);
410 if (info->scale != -1 && info->roll != -1)
411 info->convert = feed_convert_scale64;
413 info->convert = feed_convert_64;
416 case FEEDRATE_CONVERT_OPTIMAL:
417 r = feed_get_best_coef(&info->src, &info->dst,
418 &info->gx, &info->gy, &info->scale,
421 info->convert = feed_convert_scale32;
424 feed_rate_reset(info);
425 feed_speed_ratio(info->src, info->dst,
426 &info->gx, &info->gy);
427 feed_scale_roll(info->gy, &info->scale,
428 &info->roll, FEEDRATE_64_MAXROLL);
429 if (info->scale != -1 && info->roll != -1)
430 info->convert = feed_convert_scale64;
432 info->convert = feed_convert_64;
435 case FEEDRATE_CONVERT_WORST:
436 r = feed_get_best_coef(&info->src, &info->dst,
437 &info->gx, &info->gy, &info->scale,
440 info->convert = feed_convert_scale32;
443 feed_rate_reset(info);
444 feed_speed_ratio(info->src, info->dst,
445 &info->gx, &info->gy);
446 info->convert = feed_convert_plain;
454 if (info->gx == 0 || info->gy == 0)
457 * No need to interpolate/decimate, just do plain copy.
458 * This probably caused by Hz roundup.
460 if (info->gx == info->gy)
461 info->convert = feed_convert_plain;
467 feed_rate_set(struct pcm_feeder *f, int what, int value)
469 struct feed_rate_info *info = f->data;
471 if (value < feeder_rate_ratemin || value > feeder_rate_ratemax)
484 return feed_rate_setup(f);
488 feed_rate_get(struct pcm_feeder *f, int what)
490 struct feed_rate_info *info = f->data;
493 * Return *real* src/dst rate.
507 feed_rate_init(struct pcm_feeder *f)
509 struct feed_rate_info *info;
511 info = kmalloc(sizeof(*info), M_RATEFEEDER, M_WAITOK | M_ZERO);
513 * bufsz = sample from last cycle + conversion space
515 info->bufsz = 2 + feeder_rate_buffersize;
516 info->buffer = kmalloc(sizeof(*info->buffer) * info->bufsz,
517 M_RATEFEEDER, M_WAITOK | M_ZERO);
518 info->rsrc = DSP_DEFAULT_SPEED;
519 info->rdst = DSP_DEFAULT_SPEED;
521 return feed_rate_setup(f);
525 feed_rate_free(struct pcm_feeder *f)
527 struct feed_rate_info *info = f->data;
531 kfree(info->buffer, M_RATEFEEDER);
532 kfree(info, M_RATEFEEDER);
539 feed_convert_64(struct feed_rate_info *info, int16_t *dst, uint32_t max)
541 int64_t x, alpha, distance;
543 int32_t pos, bpos, gx, gy;
546 * Plain, straight forward 64bit arith. No bit-magic applied here.
563 distance = gy - alpha;
564 x = (alpha * src[pos - 2]) + (distance * src[pos]);
566 x = (alpha * src[pos - 1]) + (distance * src[pos + 1]);
578 feed_convert_scale64(struct feed_rate_info *info, int16_t *dst, uint32_t max)
580 int64_t x, alpha, distance;
582 int32_t pos, bpos, gx, gy, roll;
589 alpha = info->alpha * info->scale;
590 gx = info->gx * info->scale;
591 gy = info->gy * info->scale;
603 distance = gy - alpha;
604 x = (alpha * src[pos - 2]) + (distance * src[pos]);
605 dst[ret++] = x >> roll;
606 x = (alpha * src[pos - 1]) + (distance * src[pos + 1]);
607 dst[ret++] = x >> roll;
612 info->alpha = alpha / info->scale;
618 feed_convert_scale32(struct feed_rate_info *info, int16_t *dst, uint32_t max)
621 int32_t x, pos, bpos, gx, gy, alpha, roll, distance;
628 alpha = info->alpha * info->scale;
629 gx = info->gx * info->scale;
630 gy = info->gy * info->scale;
642 distance = gy - alpha;
643 x = (alpha * src[pos - 2]) + (distance * src[pos]);
644 dst[ret++] = x >> roll;
645 x = (alpha * src[pos - 1]) + (distance * src[pos + 1]);
646 dst[ret++] = x >> roll;
651 info->alpha = alpha / info->scale;
657 feed_convert_plain(struct feed_rate_info *info, int16_t *dst, uint32_t max)
660 int32_t pos, bpos, gx, gy, alpha;
680 dst[ret++] = src[pos];
681 dst[ret++] = src[pos + 1];
692 feed_rate(struct pcm_feeder *f, struct pcm_channel *c, uint8_t *b,
693 uint32_t count, void *source)
695 struct feed_rate_info *info = f->data;
698 int16_t *dst = (int16_t *)b;
700 * This loop has been optimized to generalize both up / down
701 * sampling without causing missing samples or excessive buffer
704 RATE_TEST(count >= 4 && (count & 3) == 0,
705 ("%s: Count size not byte integral (%d)\n", __func__, count));
710 slot = (((info->gx * (count >> 1)) + info->gy - info->alpha - 1) / info->gy) << 1;
711 RATE_TEST((slot & 1) == 0, ("%s: Slot count not sample integral (%d)\n",
714 * Optimize buffer feeding aggressively to ensure calculated slot
715 * can be fitted nicely into available buffer free space, hence
716 * avoiding multiple feeding.
718 RATE_TEST(info->stray == 0, ("%s: [1] Stray bytes: %u\n",
719 __func__,info->stray));
720 if (info->pos != 2 && info->bpos - info->pos == 2 &&
721 info->bpos + slot > info->bufsz) {
723 * Copy last unit sample and its previous to
724 * beginning of buffer.
726 info->buffer[0] = info->buffer[info->pos - 2];
727 info->buffer[1] = info->buffer[info->pos - 1];
728 info->buffer[2] = info->buffer[info->pos];
729 info->buffer[3] = info->buffer[info->pos + 1];
733 RATE_ASSERT(slot >= 0, ("%s: Negative Slot: %d\n",
738 fetch = (info->bufsz - info->bpos) << 1;
739 fetch -= info->stray;
740 RATE_ASSERT(fetch >= 0,
741 ("%s: [1] Buffer overrun: %d > %d\n",
742 __func__, info->bpos, info->bufsz));
743 if ((slot << 1) < fetch)
746 RATE_ASSERT(((info->bpos << 1) - info->stray) >= 0 &&
747 ((info->bpos << 1) - info->stray) < (info->bufsz << 1),
748 ("%s: DANGER - BUFFER OVERRUN! bufsz=%d, pos=%d\n", __func__,
749 info->bufsz << 1, (info->bpos << 1) - info->stray));
750 fetch = FEEDER_FEED(f->source, c,
751 (uint8_t *)(info->buffer) + (info->bpos << 1) - info->stray,
756 RATE_TEST((fetch & 3) == 0,
757 ("%s: Fetch size not byte integral (%d)\n",
759 info->stray += fetch & 3;
760 RATE_TEST(info->stray == 0,
761 ("%s: Stray bytes detected (%d)\n",
762 __func__, info->stray));
767 RATE_ASSERT(slot >= 0,
768 ("%s: Negative Slot: %d\n", __func__,
772 if (info->bpos == info->bufsz)
777 if (info->pos == info->bpos) {
778 RATE_TEST(info->pos == 2,
779 ("%s: EOF while in progress\n", __func__));
782 RATE_ASSERT(info->pos <= info->bpos,
783 ("%s: [2] Buffer overrun: %d > %d\n", __func__,
784 info->pos, info->bpos));
785 RATE_ASSERT(info->pos < info->bpos,
786 ("%s: Zero buffer!\n", __func__));
787 RATE_ASSERT(((info->bpos - info->pos) & 1) == 0,
788 ("%s: Buffer not sample integral (%d)\n",
789 __func__, info->bpos - info->pos));
790 i += info->convert(info, dst + i, count - i);
791 RATE_ASSERT(info->pos <= info->bpos,
792 ("%s: [3] Buffer overrun: %d > %d\n",
793 __func__, info->pos, info->bpos));
794 if (info->pos == info->bpos) {
796 * End of buffer cycle. Copy last unit sample
797 * to beginning of buffer so next cycle can
798 * interpolate using it.
800 RATE_TEST(info->stray == 0, ("%s: [2] Stray bytes: %u\n", __func__, info->stray));
801 info->buffer[0] = info->buffer[info->pos - 2];
802 info->buffer[1] = info->buffer[info->pos - 1];
810 RATE_TEST(count == i, ("Expect: %u , Got: %u\n", count << 1, i << 1));
812 RATE_TEST(info->stray == 0, ("%s: [3] Stray bytes: %u\n", __func__, info->stray));
816 static struct pcm_feederdesc feeder_rate_desc[] = {
817 {FEEDER_RATE, AFMT_S16_LE | AFMT_STEREO, AFMT_S16_LE | AFMT_STEREO, 0},
820 static kobj_method_t feeder_rate_methods[] = {
821 KOBJMETHOD(feeder_init, feed_rate_init),
822 KOBJMETHOD(feeder_free, feed_rate_free),
823 KOBJMETHOD(feeder_set, feed_rate_set),
824 KOBJMETHOD(feeder_get, feed_rate_get),
825 KOBJMETHOD(feeder_feed, feed_rate),
828 FEEDER_DECLARE(feeder_rate, 2, NULL);