dect
/
asterisk
Archived
13
0
Fork 0

Merge changes from team/russell/codec_resample

This commit imports libresample for use in Asterisk.  It also adds a new codec
module, codec_resample.  This module uses libresample to re-sample signed linear
audio between 8 kHz and 16 kHz.

It also provides an alternative for converting between 16 kHz G.722 and 8 kHz
signed linear when using G.722, which will likely be useful as some people have
complained about volume issues when the current codec_g722 converts to 8 kHz 
signed linear.  But, to test this, you will have to disable the g722-to-slin and
g722-to-slin16 translators in codec_g722.c.


git-svn-id: http://svn.digium.com/svn/asterisk/trunk@95501 f38db490-d61c-443f-a65b-d21fe96a405b
This commit is contained in:
russell 2007-12-31 21:22:31 +00:00
parent 9c384ade94
commit 04838b9d59
26 changed files with 10477 additions and 1 deletions

View File

@ -429,3 +429,6 @@ Miscellaneous
* A new option when starting a remote asterisk (rasterisk, asterisk -r) for
specifying which socket to use to connect to the running Asterisk daemon
(-s)
* Added a new codec translation module, codec_resample, which re-samples
signed linear audio between 8 kHz and 16 kHz to help support wideband
codecs.

View File

@ -54,3 +54,5 @@ $(LIBG722):
@$(MAKE) -C g722 all
$(if $(filter codec_g722,$(EMBEDDED_MODS)),modules.link,codec_g722.so): $(LIBG722)
codec_resample.o: ASTCFLAGS+=-I$(ASTTOPDIR)/main/libresample/include

234
codecs/codec_resample.c Normal file
View File

@ -0,0 +1,234 @@
/*
* Asterisk -- An open source telephony toolkit.
*
* Copyright (C) 2007, Digium, Inc.
*
* Russell Bryant <russell@digium.com>
*
* See http://www.asterisk.org for more information about
* the Asterisk project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, mailing lists and IRC
* channels for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
/*!
* \file
*
* \brief Resample slinear audio
*
* \ingroup codecs
*/
#include "asterisk.h"
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
/* These are for SHRT_MAX and FLT_MAX -- { */
#ifdef __Darwin__
#include <float.h>
#else
#include <values.h>
#endif
#include <limits.h>
/* } */
#include "asterisk/module.h"
#include "asterisk/translate.h"
#include "libresample.h"
#include "slin_resample_ex.h"
#define RESAMPLER_QUALITY 0
#define OUTBUF_SIZE 8096
struct slin16_to_slin8_pvt {
void *resampler;
double resample_factor;
};
struct slin8_to_slin16_pvt {
void *resampler;
double resample_factor;
};
static int slin16_to_slin8_new(struct ast_trans_pvt *pvt)
{
struct slin16_to_slin8_pvt *resamp_pvt = pvt->pvt;
resamp_pvt->resample_factor = 0.5;
if (!(resamp_pvt->resampler = resample_open(RESAMPLER_QUALITY, 0.5, 0.5)))
return -1;
return 0;
}
static int slin8_to_slin16_new(struct ast_trans_pvt *pvt)
{
struct slin8_to_slin16_pvt *resamp_pvt = pvt->pvt;
resamp_pvt->resample_factor = 2.0;
if (!(resamp_pvt->resampler = resample_open(RESAMPLER_QUALITY, 2.0, 2.0)))
return -1;
return 0;
}
static void slin16_to_slin8_destroy(struct ast_trans_pvt *pvt)
{
struct slin16_to_slin8_pvt *resamp_pvt = pvt->pvt;
if (resamp_pvt->resampler)
resample_close(resamp_pvt->resampler);
}
static void slin8_to_slin16_destroy(struct ast_trans_pvt *pvt)
{
struct slin8_to_slin16_pvt *resamp_pvt = pvt->pvt;
if (resamp_pvt->resampler)
resample_close(resamp_pvt->resampler);
}
static int resample_frame(struct ast_trans_pvt *pvt,
void *resampler, double resample_factor, struct ast_frame *f)
{
int total_in_buf_used = 0;
int total_out_buf_used = 0;
int16_t *in_buf = (int16_t *) f->data;
int16_t *out_buf = (int16_t *) pvt->outbuf + pvt->samples;
float in_buf_f[f->samples];
float out_buf_f[2048];
int res = 0;
int i;
for (i = 0; i < f->samples; i++)
in_buf_f[i] = in_buf[i] * (FLT_MAX / SHRT_MAX);
while (total_in_buf_used < f->samples) {
int in_buf_used, out_buf_used;
out_buf_used = resample_process(resampler, resample_factor,
&in_buf_f[total_in_buf_used], f->samples - total_in_buf_used,
0, &in_buf_used,
&out_buf_f[total_out_buf_used], ARRAY_LEN(out_buf_f) - total_out_buf_used);
if (out_buf_used < 0)
break;
total_out_buf_used += out_buf_used;
total_in_buf_used += in_buf_used;
if (total_out_buf_used == ARRAY_LEN(out_buf_f)) {
ast_log(LOG_ERROR, "Output buffer filled ... need to increase its size\n");
res = -1;
break;
}
}
for (i = 0; i < total_out_buf_used; i++)
out_buf[i] = out_buf_f[i] * (SHRT_MAX / FLT_MAX);
pvt->samples += total_out_buf_used;
pvt->datalen += (total_out_buf_used * sizeof(int16_t));
return res;
}
static int slin16_to_slin8_framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
{
struct slin16_to_slin8_pvt *resamp_pvt = pvt->pvt;
return resample_frame(pvt, resamp_pvt->resampler, resamp_pvt->resample_factor, f);
}
static int slin8_to_slin16_framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
{
struct slin8_to_slin16_pvt *resamp_pvt = pvt->pvt;
return resample_frame(pvt, resamp_pvt->resampler, resamp_pvt->resample_factor, f);
}
static struct ast_frame *slin16_to_slin8_sample(void)
{
static struct ast_frame f = {
.frametype = AST_FRAME_VOICE,
.subclass = AST_FORMAT_SLINEAR16,
.datalen = sizeof(slin16_slin8_ex),
.samples = sizeof(slin16_slin8_ex) / sizeof(slin16_slin8_ex[0]),
.src = __PRETTY_FUNCTION__,
.data = slin16_slin8_ex,
};
return &f;
}
static struct ast_frame *slin8_to_slin16_sample(void)
{
static struct ast_frame f = {
.frametype = AST_FRAME_VOICE,
.subclass = AST_FORMAT_SLINEAR,
.datalen = sizeof(slin8_slin16_ex),
.samples = sizeof(slin8_slin16_ex) / sizeof(slin8_slin16_ex[0]),
.src = __PRETTY_FUNCTION__,
.data = slin8_slin16_ex,
};
return &f;
}
static struct ast_translator slin16_to_slin8 = {
.name = "slin16_to_slin8",
.srcfmt = AST_FORMAT_SLINEAR16,
.dstfmt = AST_FORMAT_SLINEAR,
.newpvt = slin16_to_slin8_new,
.destroy = slin16_to_slin8_destroy,
.framein = slin16_to_slin8_framein,
.sample = slin16_to_slin8_sample,
.desc_size = sizeof(struct slin16_to_slin8_pvt),
.buffer_samples = (OUTBUF_SIZE / sizeof(int16_t)),
.buf_size = OUTBUF_SIZE,
};
static struct ast_translator slin8_to_slin16 = {
.name = "slin8_to_slin16",
.srcfmt = AST_FORMAT_SLINEAR,
.dstfmt = AST_FORMAT_SLINEAR16,
.newpvt = slin8_to_slin16_new,
.destroy = slin8_to_slin16_destroy,
.framein = slin8_to_slin16_framein,
.sample = slin8_to_slin16_sample,
.desc_size = sizeof(struct slin8_to_slin16_pvt),
.buffer_samples = OUTBUF_SIZE,
.buf_size = OUTBUF_SIZE,
};
static int unload_module(void)
{
int res = 0;
res |= ast_unregister_translator(&slin16_to_slin8);
res |= ast_unregister_translator(&slin8_to_slin16);
return res;
}
static int load_module(void)
{
int res = 0;
res |= ast_register_translator(&slin16_to_slin8);
res |= ast_register_translator(&slin8_to_slin16);
return AST_MODULE_LOAD_SUCCESS;
}
AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "SLIN Resampling Codec");

43
codecs/slin_resample_ex.h Normal file
View File

@ -0,0 +1,43 @@
/*! \file
* \brief slin_resample_ex.h --
*
* Copyright (C) 2007, Digium Inc.
*
* Distributed under the terms of the GNU General Public License
*/
static signed short slin16_slin8_ex[] = {
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
};
static signed short slin8_slin16_ex[] = {
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
};

View File

@ -111,6 +111,9 @@ editline/libedit.a: CHECK_SUBDIR
db1-ast/libdb1.a: CHECK_SUBDIR
CFLAGS="$(ASTCFLAGS)" LDFLAGS="$(ASTLDFLAGS)" $(MAKE) -C db1-ast libdb1.a
libresample/libresample.a: CHECK_SUBDIR
$(MAKE) -f Makefile.asterisk -C libresample libresample.a
ast_expr2.c ast_expr2.h:
bison -o $@ -d --name-prefix=ast_yy ast_expr2.y
@ -152,7 +155,7 @@ else
MAIN_TGT:=asterisk
endif
$(MAIN_TGT): $(OBJS) editline/libedit.a db1-ast/libdb1.a minimime/libmmime.a $(AST_EMBED_LDSCRIPTS)
$(MAIN_TGT): $(OBJS) editline/libedit.a db1-ast/libdb1.a minimime/libmmime.a $(AST_EMBED_LDSCRIPTS) libresample/libresample.a
@$(CC) -c -o buildinfo.o $(ASTCFLAGS) buildinfo.c
$(ECHO_PREFIX) echo " [LD] $^ -> $@"
ifneq ($(findstring chan_h323,$(MENUSELECT_CHANNELS)),)
@ -169,3 +172,4 @@ clean::
@$(MAKE) -C db1-ast clean
@$(MAKE) -C stdtime clean
@$(MAKE) -C minimime clean
@$(MAKE) -f Makefile.asterisk -C libresample clean

View File

@ -0,0 +1,463 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations
below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control
compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply, and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License
may add an explicit geographical distribution limitation excluding those
countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS

View File

@ -0,0 +1,11 @@
include $(ASTTOPDIR)/Makefile.moddir_rules
ASTCFLAGS+= -Isrc -Iinclude
libresample.a: src/resample.o src/resamplesubs.o src/filterkit.o
$(ECHO_PREFIX) echo " [AR] $^ -> $@"
$(CMD_PREFIX) $(AR) cr $@ $^
$(CMD_PREFIX) $(RANLIB) $@
clean::
rm -f src/*.o libresample.a

View File

@ -0,0 +1,52 @@
# Run configure to generate Makefile from Makefile.in on
# any system supported by GNU autoconf. For all other
# systems, use this file as a template to create a
# working Makefile.
CC = @CC@
CFLAGS = @CFLAGS@ -Wall
LIBS = @LIBS@ -lm
AR = @AR@
RANLIB = @RANLIB@
OBJS = \
src/resample.c.o \
src/resamplesubs.c.o \
src/filterkit.c.o
TARGETS = @TARGETS@
all: $(TARGETS)
libresample.a: $(OBJS) Makefile
$(AR) ruv libresample.a $(OBJS)
ranlib libresample.a
tests/testresample: libresample.a tests/testresample.c
$(CC) -o tests/testresample \
$(CFLAGS) tests/testresample.c \
libresample.a $(LIBS)
tests/compareresample: libresample.a tests/compareresample.c
$(CC) -o tests/compareresample \
$(CFLAGS) tests/compareresample.c \
libresample.a -lsamplerate $(LIBS)
tests/resample-sndfile: libresample.a tests/resample-sndfile.c
$(CC) -o tests/resample-sndfile \
$(CFLAGS) tests/resample-sndfile.c \
libresample.a -lsndfile $(LIBS)
clean:
rm -f $(TARGETS) $(OBJS)
distclean: clean
rm -f Makefile
rm -f config.status config.cache config.log src/config.h
rm -f *~ src/*~ tests/*~ include/*~
%.c.o: %.c Makefile include/libresample.h \
src/resample_defs.h src/filterkit.h src/config.h
$(CC) -c $(CFLAGS) $< -o $@

View File

@ -0,0 +1,84 @@
libresample
Real-time library interface by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
License: LGPL - see the file LICENSE.txt for more information
History:
This library is not the highest-quality resampling library
available, nor is it the most flexible, nor is it the
fastest. But it is pretty good in all of these regards, and
it is quite portable. The best resampling library I am aware
of is libsamplerate by Erik de Castro Lopo. It's small, fast,
and very high quality. However, it uses the GPL for its
license (with commercial options available) and I needed
a more free library. So I wrote this library, using
the LGPL resample-1.7 library by Julius Smith as a basis.
Resample-1.7 is a fixed-point resampler, and as a result
has only limited precision. I rewrote it to use single-precision
floating-point arithmetic instead and increased the number
of filter coefficients between time steps significantly.
On modern processors it can resample in real time even
with this extra overhead.
Resample-1.7 was designed to read and write from files, so
I removed all of that code and replaced it with an API that
lets you pass samples in small chunks. It should be easy
to link to resample-1.7 as a library.
Changes in version 0.1.3:
* Fixed two bugs that were causing subtle problems
on Intel x86 processors due to differences in roundoff errors.
* Prefixed most function names with lrs and changed header file
from resample.h to libresample.h, to avoid namespace
collisions with existing programs and libraries.
* Added resample_dup (thanks to Glenn Maynard)
* Argument to resample_get_filter_width takes a const void *
(thanks to Glenn Maynard)
* resample-sndfile clips output to -1...1 (thanks to Glenn Maynard)
Usage notes:
- If the output buffer you pass is too small, resample_process
may not use any input samples because its internal output
buffer is too full to process any more. So do not assume
that it is an error just because no input samples were
consumed. Just keep passing valid output buffers.
- Given a resampling factor f > 1, and a number of input
samples n, the number of output samples should be between
floor(n - f) and ceil(n + f). In other words, if you
resample 1000 samples at a factor of 8, the number of
output samples might be between 7992 and 8008. Do not
assume that it will be exactly 8000. If you need exactly
8000 outputs, pad the input with extra zeros as necessary.
License and warranty:
All of the files in this package are Copyright 2003 by Dominic
Mazzoni <dominic@minorninth.com>. This library was based heavily
on Resample-1.7, Copyright 1994-2002 by Julius O. Smith III
<jos@ccrma.stanford.edu>, all rights reserved.
Permission to use and copy is granted subject to the terms of the
"GNU Lesser General Public License" (LGPL) as published by the
Free Software Foundation; either version 2.1 of the License,
or any later version. In addition, Julius O. Smith III requests
that a copy of any modified files be sent by email to
jos@ccrma.stanford.edu so that he may incorporate them into the
CCRMA version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

1432
main/libresample/config.guess vendored Executable file

File diff suppressed because it is too large Load Diff

1537
main/libresample/config.sub vendored Executable file

File diff suppressed because it is too large Load Diff

4552
main/libresample/configure vendored Executable file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,68 @@
dnl
dnl libresample configure.in script
dnl
dnl Dominic Mazzoni
dnl
dnl Require autoconf >= 2.13
AC_PREREQ(2.13)
dnl Init autoconf and make sure configure is being called
dnl from the right directory
AC_INIT([src/resample.c])
dnl Checks for programs.
AC_PROG_CC
AC_PROG_RANLIB
AC_PATH_PROG(AR, ar, no)
if [[ $AR = "no" ]] ; then
AC_MSG_ERROR("Could not find ar - needed to create a library");
fi
AC_SUBST(TARGETS)
TARGETS="libresample.a tests/testresample"
AC_CHECK_LIB(sndfile, sf_open, have_libsndfile=yes, have_libsndfile=no)
AC_CHECK_HEADER(sndfile.h, , have_libsndfile=no)
if [[ $have_libsndfile = "yes" ]] ; then
TARGETS="$TARGETS tests/resample-sndfile"
fi
AC_CHECK_LIB(samplerate, src_simple, have_libsamplerate=yes, have_libsamplerate=no)
AC_CHECK_HEADER(samplerate.h, , have_libsamplerate=no)
if [[ $have_libsamplerate = "yes" ]] ; then
TARGETS="$TARGETS tests/compareresample"
fi
AC_CHECK_HEADERS(inttypes.h)
AC_CONFIG_HEADER(src/config.h:src/configtemplate.h)
AC_OUTPUT([Makefile])
echo ""
if [[ $have_libsamplerate = "yes" ]] ; then
echo "Configured to build tests/resample-sndfile using libsndfile"
echo ""
else
echo "Could not find libsndfile - needed if you want to"
echo "compile tests/resample-sndfile"
echo ""
fi
if [[ $have_libsamplerate = "yes" ]] ; then
echo "Configured to build tests/compareresample to compare against"
echo "Erik de Castro Lopo's libsamplerate library."
echo ""
else
echo "Could not find libsamplerate - only needed if you want to"
echo "compile tests/compareresample to compare their performance."
echo ""
fi
echo "Type 'configure --help' to see options."
echo ""
echo "Type 'make' to build libresample and tests."

View File

@ -0,0 +1,44 @@
/**********************************************************************
resample.h
Real-time library interface by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
License: LGPL - see the file LICENSE.txt for more information
**********************************************************************/
#ifndef LIBRESAMPLE_INCLUDED
#define LIBRESAMPLE_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
void *resample_open(int highQuality,
double minFactor,
double maxFactor);
void *resample_dup(const void *handle);
int resample_get_filter_width(const void *handle);
int resample_process(void *handle,
double factor,
float *inBuffer,
int inBufferLen,
int lastFlag,
int *inBufferUsed,
float *outBuffer,
int outBufferLen);
void resample_close(void *handle);
#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */
#endif /* LIBRESAMPLE_INCLUDED */

251
main/libresample/install-sh Executable file
View File

@ -0,0 +1,251 @@
#!/bin/sh
#
# install - install a program, script, or datafile
# This comes from X11R5 (mit/util/scripts/install.sh).
#
# Copyright 1991 by the Massachusetts Institute of Technology
#
# Permission to use, copy, modify, distribute, and sell this software and its
# documentation for any purpose is hereby granted without fee, provided that
# the above copyright notice appear in all copies and that both that
# copyright notice and this permission notice appear in supporting
# documentation, and that the name of M.I.T. not be used in advertising or
# publicity pertaining to distribution of the software without specific,
# written prior permission. M.I.T. makes no representations about the
# suitability of this software for any purpose. It is provided "as is"
# without express or implied warranty.
#
# Calling this script install-sh is preferred over install.sh, to prevent
# `make' implicit rules from creating a file called install from it
# when there is no Makefile.
#
# This script is compatible with the BSD install script, but was written
# from scratch. It can only install one file at a time, a restriction
# shared with many OS's install programs.
# set DOITPROG to echo to test this script
# Don't use :- since 4.3BSD and earlier shells don't like it.
doit="${DOITPROG-}"
# put in absolute paths if you don't have them in your path; or use env. vars.
mvprog="${MVPROG-mv}"
cpprog="${CPPROG-cp}"
chmodprog="${CHMODPROG-chmod}"
chownprog="${CHOWNPROG-chown}"
chgrpprog="${CHGRPPROG-chgrp}"
stripprog="${STRIPPROG-strip}"
rmprog="${RMPROG-rm}"
mkdirprog="${MKDIRPROG-mkdir}"
transformbasename=""
transform_arg=""
instcmd="$mvprog"
chmodcmd="$chmodprog 0755"
chowncmd=""
chgrpcmd=""
stripcmd=""
rmcmd="$rmprog -f"
mvcmd="$mvprog"
src=""
dst=""
dir_arg=""
while [ x"$1" != x ]; do
case $1 in
-c) instcmd="$cpprog"
shift
continue;;
-d) dir_arg=true
shift
continue;;
-m) chmodcmd="$chmodprog $2"
shift
shift
continue;;
-o) chowncmd="$chownprog $2"
shift
shift
continue;;
-g) chgrpcmd="$chgrpprog $2"
shift
shift
continue;;
-s) stripcmd="$stripprog"
shift
continue;;
-t=*) transformarg=`echo $1 | sed 's/-t=//'`
shift
continue;;
-b=*) transformbasename=`echo $1 | sed 's/-b=//'`
shift
continue;;
*) if [ x"$src" = x ]
then
src=$1
else
# this colon is to work around a 386BSD /bin/sh bug
:
dst=$1
fi
shift
continue;;
esac
done
if [ x"$src" = x ]
then
echo "install: no input file specified"
exit 1
else
true
fi
if [ x"$dir_arg" != x ]; then
dst=$src
src=""
if [ -d $dst ]; then
instcmd=:
chmodcmd=""
else
instcmd=mkdir
fi
else
# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
# might cause directories to be created, which would be especially bad
# if $src (and thus $dsttmp) contains '*'.
if [ -f $src -o -d $src ]
then
true
else
echo "install: $src does not exist"
exit 1
fi
if [ x"$dst" = x ]
then
echo "install: no destination specified"
exit 1
else
true
fi
# If destination is a directory, append the input filename; if your system
# does not like double slashes in filenames, you may need to add some logic
if [ -d $dst ]
then
dst="$dst"/`basename $src`
else
true
fi
fi
## this sed command emulates the dirname command
dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
# Make sure that the destination directory exists.
# this part is taken from Noah Friedman's mkinstalldirs script
# Skip lots of stat calls in the usual case.
if [ ! -d "$dstdir" ]; then
defaultIFS='
'
IFS="${IFS-${defaultIFS}}"
oIFS="${IFS}"
# Some sh's can't handle IFS=/ for some reason.
IFS='%'
set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
IFS="${oIFS}"
pathcomp=''
while [ $# -ne 0 ] ; do
pathcomp="${pathcomp}${1}"
shift
if [ ! -d "${pathcomp}" ] ;
then
$mkdirprog "${pathcomp}"
else
true
fi
pathcomp="${pathcomp}/"
done
fi
if [ x"$dir_arg" != x ]
then
$doit $instcmd $dst &&
if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
else
# If we're going to rename the final executable, determine the name now.
if [ x"$transformarg" = x ]
then
dstfile=`basename $dst`
else
dstfile=`basename $dst $transformbasename |
sed $transformarg`$transformbasename
fi
# don't allow the sed command to completely eliminate the filename
if [ x"$dstfile" = x ]
then
dstfile=`basename $dst`
else
true
fi
# Make a temp file name in the proper directory.
dsttmp=$dstdir/#inst.$$#
# Move or copy the file name to the temp name
$doit $instcmd $src $dsttmp &&
trap "rm -f ${dsttmp}" 0 &&
# and set any options; do chmod last to preserve setuid bits
# If any of these fail, we abort the whole thing. If we want to
# ignore errors from any of these, just make sure not to ignore
# errors from the above "$doit $instcmd $src $dsttmp" command.
if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
# Now rename the file to the real destination.
$doit $rmcmd -f $dstdir/$dstfile &&
$doit $mvcmd $dsttmp $dstdir/$dstfile
fi &&
exit 0

View File

@ -0,0 +1,7 @@
/* Run configure to generate config.h automatically on any
system supported by GNU autoconf. For all other systems,
use this file as a template to create config.h
*/
#undef HAVE_INTTYPES_H

View File

@ -0,0 +1,215 @@
/**********************************************************************
resamplesubs.c
Real-time library interface by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
License: LGPL - see the file LICENSE.txt for more information
This file provides Kaiser-windowed low-pass filter support,
including a function to create the filter coefficients, and
two functions to apply the filter at a particular point.
**********************************************************************/
/* Definitions */
#include "resample_defs.h"
#include "filterkit.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
/* LpFilter()
*
* reference: "Digital Filters, 2nd edition"
* R.W. Hamming, pp. 178-179
*
* Izero() computes the 0th order modified bessel function of the first kind.
* (Needed to compute Kaiser window).
*
* LpFilter() computes the coeffs of a Kaiser-windowed low pass filter with
* the following characteristics:
*
* c[] = array in which to store computed coeffs
* frq = roll-off frequency of filter
* N = Half the window length in number of coeffs
* Beta = parameter of Kaiser window
* Num = number of coeffs before 1/frq
*
* Beta trades the rejection of the lowpass filter against the transition
* width from passband to stopband. Larger Beta means a slower
* transition and greater stopband rejection. See Rabiner and Gold
* (Theory and Application of DSP) under Kaiser windows for more about
* Beta. The following table from Rabiner and Gold gives some feel
* for the effect of Beta:
*
* All ripples in dB, width of transition band = D*N where N = window length
*
* BETA D PB RIP SB RIP
* 2.120 1.50 +-0.27 -30
* 3.384 2.23 0.0864 -40
* 4.538 2.93 0.0274 -50
* 5.658 3.62 0.00868 -60
* 6.764 4.32 0.00275 -70
* 7.865 5.0 0.000868 -80
* 8.960 5.7 0.000275 -90
* 10.056 6.4 0.000087 -100
*/
#define IzeroEPSILON 1E-21 /* Max error acceptable in Izero */
static double Izero(double x)
{
double sum, u, halfx, temp;
int n;
sum = u = n = 1;
halfx = x/2.0;
do {
temp = halfx/(double)n;
n += 1;
temp *= temp;
u *= temp;
sum += u;
} while (u >= IzeroEPSILON*sum);
return(sum);
}
void lrsLpFilter(double c[], int N, double frq, double Beta, int Num)
{
double IBeta, temp, temp1, inm1;
int i;
/* Calculate ideal lowpass filter impulse response coefficients: */
c[0] = 2.0*frq;
for (i=1; i<N; i++) {
temp = PI*(double)i/(double)Num;
c[i] = sin(2.0*temp*frq)/temp; /* Analog sinc function, cutoff = frq */
}
/*
* Calculate and Apply Kaiser window to ideal lowpass filter.
* Note: last window value is IBeta which is NOT zero.
* You're supposed to really truncate the window here, not ramp
* it to zero. This helps reduce the first sidelobe.
*/
IBeta = 1.0/Izero(Beta);
inm1 = 1.0/((double)(N-1));
for (i=1; i<N; i++) {
temp = (double)i * inm1;
temp1 = 1.0 - temp*temp;
temp1 = (temp1<0? 0: temp1); /* make sure it's not negative since
we're taking the square root - this
happens on Pentium 4's due to tiny
roundoff errors */
c[i] *= Izero(Beta*sqrt(temp1)) * IBeta;
}
}
float lrsFilterUp(float Imp[], /* impulse response */
float ImpD[], /* impulse response deltas */
UWORD Nwing, /* len of one wing of filter */
BOOL Interp, /* Interpolate coefs using deltas? */
float *Xp, /* Current sample */
double Ph, /* Phase */
int Inc) /* increment (1 for right wing or -1 for left) */
{
float *Hp, *Hdp = NULL, *End;
double a = 0;
float v, t;
Ph *= Npc; /* Npc is number of values per 1/delta in impulse response */
v = 0.0; /* The output value */
Hp = &Imp[(int)Ph];
End = &Imp[Nwing];
if (Interp) {
Hdp = &ImpD[(int)Ph];
a = Ph - floor(Ph); /* fractional part of Phase */
}
if (Inc == 1) /* If doing right wing... */
{ /* ...drop extra coeff, so when Ph is */
End--; /* 0.5, we don't do too many mult's */
if (Ph == 0) /* If the phase is zero... */
{ /* ...then we've already skipped the */
Hp += Npc; /* first sample, so we must also */
Hdp += Npc; /* skip ahead in Imp[] and ImpD[] */
}
}
if (Interp)
while (Hp < End) {
t = *Hp; /* Get filter coeff */
t += (*Hdp)*a; /* t is now interp'd filter coeff */
Hdp += Npc; /* Filter coeff differences step */
t *= *Xp; /* Mult coeff by input sample */
v += t; /* The filter output */
Hp += Npc; /* Filter coeff step */
Xp += Inc; /* Input signal step. NO CHECK ON BOUNDS */
}
else
while (Hp < End) {
t = *Hp; /* Get filter coeff */
t *= *Xp; /* Mult coeff by input sample */
v += t; /* The filter output */
Hp += Npc; /* Filter coeff step */
Xp += Inc; /* Input signal step. NO CHECK ON BOUNDS */
}
return v;
}
float lrsFilterUD(float Imp[], /* impulse response */
float ImpD[], /* impulse response deltas */
UWORD Nwing, /* len of one wing of filter */
BOOL Interp, /* Interpolate coefs using deltas? */
float *Xp, /* Current sample */
double Ph, /* Phase */
int Inc, /* increment (1 for right wing or -1 for left) */
double dhb) /* filter sampling period */
{
float a;
float *Hp, *Hdp, *End;
float v, t;
double Ho;
v = 0.0; /* The output value */
Ho = Ph*dhb;
End = &Imp[Nwing];
if (Inc == 1) /* If doing right wing... */
{ /* ...drop extra coeff, so when Ph is */
End--; /* 0.5, we don't do too many mult's */
if (Ph == 0) /* If the phase is zero... */
Ho += dhb; /* ...then we've already skipped the */
} /* first sample, so we must also */
/* skip ahead in Imp[] and ImpD[] */
if (Interp)
while ((Hp = &Imp[(int)Ho]) < End) {
t = *Hp; /* Get IR sample */
Hdp = &ImpD[(int)Ho]; /* get interp bits from diff table*/
a = Ho - floor(Ho); /* a is logically between 0 and 1 */
t += (*Hdp)*a; /* t is now interp'd filter coeff */
t *= *Xp; /* Mult coeff by input sample */
v += t; /* The filter output */
Ho += dhb; /* IR step */
Xp += Inc; /* Input signal step. NO CHECK ON BOUNDS */
}
else
while ((Hp = &Imp[(int)Ho]) < End) {
t = *Hp; /* Get IR sample */
t *= *Xp; /* Mult coeff by input sample */
v += t; /* The filter output */
Ho += dhb; /* IR step */
Xp += Inc; /* Input signal step. NO CHECK ON BOUNDS */
}
return v;
}

View File

@ -0,0 +1,28 @@
/**********************************************************************
resamplesubs.c
Real-time library interface by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
License: LGPL - see the file LICENSE.txt for more information
**********************************************************************/
/* Definitions */
#include "resample_defs.h"
/*
* FilterUp() - Applies a filter to a given sample when up-converting.
* FilterUD() - Applies a filter to a given sample when up- or down-
*/
float lrsFilterUp(float Imp[], float ImpD[], UWORD Nwing, BOOL Interp,
float *Xp, double Ph, int Inc);
float lrsFilterUD(float Imp[], float ImpD[], UWORD Nwing, BOOL Interp,
float *Xp, double Ph, int Inc, double dhb);
void lrsLpFilter(double c[], int N, double frq, double Beta, int Num);

View File

@ -0,0 +1,347 @@
/**********************************************************************
resample.c
Real-time library interface by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
License: LGPL - see the file LICENSE.txt for more information
This is the main source file, implementing all of the API
functions and handling all of the buffering logic.
**********************************************************************/
/* External interface */
#include "../include/libresample.h"
/* Definitions */
#include "resample_defs.h"
#include "filterkit.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
typedef struct {
float *Imp;
float *ImpD;
float LpScl;
UWORD Nmult;
UWORD Nwing;
double minFactor;
double maxFactor;
UWORD XSize;
float *X;
UWORD Xp; /* Current "now"-sample pointer for input */
UWORD Xread; /* Position to put new samples */
UWORD Xoff;
UWORD YSize;
float *Y;
UWORD Yp;
double Time;
} rsdata;
void *resample_dup(const void * handle)
{
const rsdata *cpy = (const rsdata *)handle;
rsdata *hp = (rsdata *)malloc(sizeof(rsdata));
hp->minFactor = cpy->minFactor;
hp->maxFactor = cpy->maxFactor;
hp->Nmult = cpy->Nmult;
hp->LpScl = cpy->LpScl;
hp->Nwing = cpy->Nwing;
hp->Imp = (float *)malloc(hp->Nwing * sizeof(float));
memcpy(hp->Imp, cpy->Imp, hp->Nwing * sizeof(float));
hp->ImpD = (float *)malloc(hp->Nwing * sizeof(float));
memcpy(hp->ImpD, cpy->ImpD, hp->Nwing * sizeof(float));
hp->Xoff = cpy->Xoff;
hp->XSize = cpy->XSize;
hp->X = (float *)malloc((hp->XSize + hp->Xoff) * sizeof(float));
memcpy(hp->X, cpy->X, (hp->XSize + hp->Xoff) * sizeof(float));
hp->Xp = cpy->Xp;
hp->Xread = cpy->Xread;
hp->YSize = cpy->YSize;
hp->Y = (float *)malloc(hp->YSize * sizeof(float));
memcpy(hp->Y, cpy->Y, hp->YSize * sizeof(float));
hp->Yp = cpy->Yp;
hp->Time = cpy->Time;
return (void *)hp;
}
void *resample_open(int highQuality, double minFactor, double maxFactor)
{
double *Imp64;
double Rolloff, Beta;
rsdata *hp;
UWORD Xoff_min, Xoff_max;
int i;
/* Just exit if we get invalid factors */
if (minFactor <= 0.0 || maxFactor <= 0.0 || maxFactor < minFactor) {
#if DEBUG
fprintf(stderr,
"libresample: "
"minFactor and maxFactor must be positive real numbers,\n"
"and maxFactor should be larger than minFactor.\n");
#endif
return 0;
}
hp = (rsdata *)malloc(sizeof(rsdata));
hp->minFactor = minFactor;
hp->maxFactor = maxFactor;
if (highQuality)
hp->Nmult = 35;
else
hp->Nmult = 11;
hp->LpScl = 1.0;
hp->Nwing = Npc*(hp->Nmult-1)/2; /* # of filter coeffs in right wing */
Rolloff = 0.90;
Beta = 6;
Imp64 = (double *)malloc(hp->Nwing * sizeof(double));
lrsLpFilter(Imp64, hp->Nwing, 0.5*Rolloff, Beta, Npc);
hp->Imp = (float *)malloc(hp->Nwing * sizeof(float));
hp->ImpD = (float *)malloc(hp->Nwing * sizeof(float));
for(i=0; i<hp->Nwing; i++)
hp->Imp[i] = Imp64[i];
/* Storing deltas in ImpD makes linear interpolation
of the filter coefficients faster */
for (i=0; i<hp->Nwing-1; i++)
hp->ImpD[i] = hp->Imp[i+1] - hp->Imp[i];
/* Last coeff. not interpolated */
hp->ImpD[hp->Nwing-1] = - hp->Imp[hp->Nwing-1];
free(Imp64);
/* Calc reach of LP filter wing (plus some creeping room) */
Xoff_min = ((hp->Nmult+1)/2.0) * MAX(1.0, 1.0/minFactor) + 10;
Xoff_max = ((hp->Nmult+1)/2.0) * MAX(1.0, 1.0/maxFactor) + 10;
hp->Xoff = MAX(Xoff_min, Xoff_max);
/* Make the inBuffer size at least 4096, but larger if necessary
in order to store the minimum reach of the LP filter and then some.
Then allocate the buffer an extra Xoff larger so that
we can zero-pad up to Xoff zeros at the end when we reach the
end of the input samples. */
hp->XSize = MAX(2*hp->Xoff+10, 4096);
hp->X = (float *)malloc((hp->XSize + hp->Xoff) * sizeof(float));
hp->Xp = hp->Xoff;
hp->Xread = hp->Xoff;
/* Need Xoff zeros at begining of X buffer */
for(i=0; i<hp->Xoff; i++)
hp->X[i]=0;
/* Make the outBuffer long enough to hold the entire processed
output of one inBuffer */
hp->YSize = (int)(((double)hp->XSize)*maxFactor+2.0);
hp->Y = (float *)malloc(hp->YSize * sizeof(float));
hp->Yp = 0;
hp->Time = (double)hp->Xoff; /* Current-time pointer for converter */
return (void *)hp;
}
int resample_get_filter_width(const void *handle)
{
const rsdata *hp = (const rsdata *)handle;
return hp->Xoff;
}
int resample_process(void *handle,
double factor,
float *inBuffer,
int inBufferLen,
int lastFlag,
int *inBufferUsed, /* output param */
float *outBuffer,
int outBufferLen)
{
rsdata *hp = (rsdata *)handle;
float *Imp = hp->Imp;
float *ImpD = hp->ImpD;
float LpScl = hp->LpScl;
UWORD Nwing = hp->Nwing;
BOOL interpFilt = FALSE; /* TRUE means interpolate filter coeffs */
int outSampleCount;
UWORD Nout, Ncreep, Nreuse;
int Nx;
int i, len;
#if DEBUG
fprintf(stderr, "resample_process: in=%d, out=%d lastFlag=%d\n",
inBufferLen, outBufferLen, lastFlag);
#endif
/* Initialize inBufferUsed and outSampleCount to 0 */
*inBufferUsed = 0;
outSampleCount = 0;
if (factor < hp->minFactor || factor > hp->maxFactor) {
#if DEBUG
fprintf(stderr,
"libresample: factor %f is not between "
"minFactor=%f and maxFactor=%f",
factor, hp->minFactor, hp->maxFactor);
#endif
return -1;
}
/* Start by copying any samples still in the Y buffer to the output
buffer */
if (hp->Yp && (outBufferLen-outSampleCount)>0) {
len = MIN(outBufferLen-outSampleCount, hp->Yp);
for(i=0; i<len; i++)
outBuffer[outSampleCount+i] = hp->Y[i];
outSampleCount += len;
for(i=0; i<hp->Yp-len; i++)
hp->Y[i] = hp->Y[i+len];
hp->Yp -= len;
}
/* If there are still output samples left, return now - we need
the full output buffer available to us... */
if (hp->Yp)
return outSampleCount;
/* Account for increased filter gain when using factors less than 1 */
if (factor < 1)
LpScl = LpScl*factor;
for(;;) {
/* This is the maximum number of samples we can process
per loop iteration */
#ifdef DEBUG
printf("XSize: %d Xoff: %d Xread: %d Xp: %d lastFlag: %d\n",
hp->XSize, hp->Xoff, hp->Xread, hp->Xp, lastFlag);
#endif
/* Copy as many samples as we can from the input buffer into X */
len = hp->XSize - hp->Xread;
if (len >= (inBufferLen - (*inBufferUsed)))
len = (inBufferLen - (*inBufferUsed));
for(i=0; i<len; i++)
hp->X[hp->Xread + i] = inBuffer[(*inBufferUsed) + i];
*inBufferUsed += len;
hp->Xread += len;
if (lastFlag && (*inBufferUsed == inBufferLen)) {
/* If these are the last samples, zero-pad the
end of the input buffer and make sure we process
all the way to the end */
Nx = hp->Xread - hp->Xoff;
for(i=0; i<hp->Xoff; i++)
hp->X[hp->Xread + i] = 0;
}
else
Nx = hp->Xread - 2 * hp->Xoff;
#ifdef DEBUG
fprintf(stderr, "new len=%d Nx=%d\n", len, Nx);
#endif
if (Nx <= 0)
break;
/* Resample stuff in input buffer */
if (factor >= 1) { /* SrcUp() is faster if we can use it */
Nout = lrsSrcUp(hp->X, hp->Y, factor, &hp->Time, Nx,
Nwing, LpScl, Imp, ImpD, interpFilt);
}
else {
Nout = lrsSrcUD(hp->X, hp->Y, factor, &hp->Time, Nx,
Nwing, LpScl, Imp, ImpD, interpFilt);
}
#ifdef DEBUG
printf("Nout: %d\n", Nout);
#endif
hp->Time -= Nx; /* Move converter Nx samples back in time */
hp->Xp += Nx; /* Advance by number of samples processed */
/* Calc time accumulation in Time */
Ncreep = (int)(hp->Time) - hp->Xoff;
if (Ncreep) {
hp->Time -= Ncreep; /* Remove time accumulation */
hp->Xp += Ncreep; /* and add it to read pointer */
}
/* Copy part of input signal that must be re-used */
Nreuse = hp->Xread - (hp->Xp - hp->Xoff);
for (i=0; i<Nreuse; i++)
hp->X[i] = hp->X[i + (hp->Xp - hp->Xoff)];
#ifdef DEBUG
printf("New Xread=%d\n", Nreuse);
#endif
hp->Xread = Nreuse; /* Pos in input buff to read new data into */
hp->Xp = hp->Xoff;
/* Check to see if output buff overflowed (shouldn't happen!) */
if (Nout > hp->YSize) {
#ifdef DEBUG
printf("Nout: %d YSize: %d\n", Nout, hp->YSize);
#endif
fprintf(stderr, "libresample: Output array overflow!\n");
return -1;
}
hp->Yp = Nout;
/* Copy as many samples as possible to the output buffer */
if (hp->Yp && (outBufferLen-outSampleCount)>0) {
len = MIN(outBufferLen-outSampleCount, hp->Yp);
for(i=0; i<len; i++)
outBuffer[outSampleCount+i] = hp->Y[i];
outSampleCount += len;
for(i=0; i<hp->Yp-len; i++)
hp->Y[i] = hp->Y[i+len];
hp->Yp -= len;
}
/* If there are still output samples left, return now,
since we need the full output buffer available */
if (hp->Yp)
break;
}
return outSampleCount;
}
void resample_close(void *handle)
{
rsdata *hp = (rsdata *)handle;
free(hp->X);
free(hp->Y);
free(hp->Imp);
free(hp->ImpD);
free(hp);
}

View File

@ -0,0 +1,90 @@
/**********************************************************************
resample_defs.h
Real-time library interface by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
License: LGPL - see the file LICENSE.txt for more information
**********************************************************************/
#ifndef __RESAMPLE_DEFS__
#define __RESAMPLE_DEFS__
#if 0
#if !defined(WIN32) && !defined(__CYGWIN__)
#include "config.h"
#endif
#endif
#define DEBUG 0
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef PI
#define PI (3.14159265358979232846)
#endif
#ifndef PI2
#define PI2 (6.28318530717958465692)
#endif
#define D2R (0.01745329348) /* (2*pi)/360 */
#define R2D (57.29577951) /* 360/(2*pi) */
#ifndef MAX
#define MAX(x,y) ((x)>(y) ?(x):(y))
#endif
#ifndef MIN
#define MIN(x,y) ((x)<(y) ?(x):(y))
#endif
#ifndef ABS
#define ABS(x) ((x)<0 ?(-(x)):(x))
#endif
#ifndef SGN
#define SGN(x) ((x)<0 ?(-1):((x)==0?(0):(1)))
#endif
#if HAVE_INTTYPES_H
#include <inttypes.h>
typedef char BOOL;
typedef int32_t WORD;
typedef uint32_t UWORD;
#else
typedef char BOOL;
typedef int WORD;
typedef unsigned int UWORD;
#endif
#ifdef DEBUG
#define INLINE
#else
#define INLINE inline
#endif
/* Accuracy */
#define Npc 4096
/* Function prototypes */
int lrsSrcUp(float X[], float Y[], double factor, double *Time,
UWORD Nx, UWORD Nwing, float LpScl,
float Imp[], float ImpD[], BOOL Interp);
int lrsSrcUD(float X[], float Y[], double factor, double *Time,
UWORD Nx, UWORD Nwing, float LpScl,
float Imp[], float ImpD[], BOOL Interp);
#endif

View File

@ -0,0 +1,123 @@
/**********************************************************************
resamplesubs.c
Real-time library interface by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
License: LGPL - see the file LICENSE.txt for more information
This file provides the routines that do sample-rate conversion
on small arrays, calling routines from filterkit.
**********************************************************************/
/* Definitions */
#include "resample_defs.h"
#include "filterkit.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
/* Sampling rate up-conversion only subroutine;
* Slightly faster than down-conversion;
*/
int lrsSrcUp(float X[],
float Y[],
double factor,
double *TimePtr,
UWORD Nx,
UWORD Nwing,
float LpScl,
float Imp[],
float ImpD[],
BOOL Interp)
{
float *Xp, *Ystart;
float v;
double CurrentTime = *TimePtr;
double dt; /* Step through input signal */
double endTime; /* When Time reaches EndTime, return to user */
dt = 1.0/factor; /* Output sampling period */
Ystart = Y;
endTime = CurrentTime + Nx;
while (CurrentTime < endTime)
{
double LeftPhase = CurrentTime-floor(CurrentTime);
double RightPhase = 1.0 - LeftPhase;
Xp = &X[(int)CurrentTime]; /* Ptr to current input sample */
/* Perform left-wing inner product */
v = lrsFilterUp(Imp, ImpD, Nwing, Interp, Xp,
LeftPhase, -1);
/* Perform right-wing inner product */
v += lrsFilterUp(Imp, ImpD, Nwing, Interp, Xp+1,
RightPhase, 1);
v *= LpScl; /* Normalize for unity filter gain */
*Y++ = v; /* Deposit output */
CurrentTime += dt; /* Move to next sample by time increment */
}
*TimePtr = CurrentTime;
return (Y - Ystart); /* Return the number of output samples */
}
/* Sampling rate conversion subroutine */
int lrsSrcUD(float X[],
float Y[],
double factor,
double *TimePtr,
UWORD Nx,
UWORD Nwing,
float LpScl,
float Imp[],
float ImpD[],
BOOL Interp)
{
float *Xp, *Ystart;
float v;
double CurrentTime = (*TimePtr);
double dh; /* Step through filter impulse response */
double dt; /* Step through input signal */
double endTime; /* When Time reaches EndTime, return to user */
dt = 1.0/factor; /* Output sampling period */
dh = MIN(Npc, factor*Npc); /* Filter sampling period */
Ystart = Y;
endTime = CurrentTime + Nx;
while (CurrentTime < endTime)
{
double LeftPhase = CurrentTime-floor(CurrentTime);
double RightPhase = 1.0 - LeftPhase;
Xp = &X[(int)CurrentTime]; /* Ptr to current input sample */
/* Perform left-wing inner product */
v = lrsFilterUD(Imp, ImpD, Nwing, Interp, Xp,
LeftPhase, -1, dh);
/* Perform right-wing inner product */
v += lrsFilterUD(Imp, ImpD, Nwing, Interp, Xp+1,
RightPhase, 1, dh);
v *= LpScl; /* Normalize for unity filter gain */
*Y++ = v; /* Deposit output */
CurrentTime += dt; /* Move to next sample by time increment */
}
*TimePtr = CurrentTime;
return (Y - Ystart); /* Return the number of output samples */
}

View File

@ -0,0 +1,183 @@
/**********************************************************************
compareresample.c
Real-time library interface by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
License: LGPL - see the file LICENSE.txt for more information
**********************************************************************/
#include "../include/libresample.h"
#include <samplerate.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#define MIN(A, B) (A) < (B)? (A) : (B)
void dostat(char *name, float *d1, float *d2, int len)
{
int i;
double sum, sumsq, err, rmserr;
sum = 0.0;
sumsq = 0.0;
for(i=0; i<len; i++) {
double diff = d1[i] - d2[i];
sum += fabs(diff);
sumsq += diff * diff;
}
err = sum / len;
rmserr = sqrt(sumsq / len);
printf(" %s: Avg err: %f RMS err: %f\n", name, err, rmserr);
}
void runtest(float *src, int srclen,
float *ans, int anslen,
double factor)
{
struct timeval tv0, tv1;
int dstlen = (int)(srclen * factor);
float *dst_rs = (float *)malloc((dstlen+100) * sizeof(float));
float *dst_rabbit = (float *)malloc((dstlen+100) * sizeof(float));
void *handle;
SRC_DATA rabbit;
double deltat;
int srcblocksize = srclen;
int dstblocksize = dstlen;
int i, out, out_rabbit, o, srcused;
int statlen, srcpos;
/* do resample */
for(i=0; i<dstlen+100; i++)
dst_rs[i] = -99.0;
gettimeofday(&tv0, NULL);
handle = resample_open(1, factor, factor);
out = 0;
srcpos = 0;
for(;;) {
int srcBlock = MIN(srclen-srcpos, srcblocksize);
int lastFlag = (srcBlock == srclen-srcpos);
o = resample_process(handle, factor,
&src[srcpos], srcBlock,
lastFlag, &srcused,
&dst_rs[out], MIN(dstlen-out, dstblocksize));
srcpos += srcused;
if (o >= 0)
out += o;
if (o < 0 || (o == 0 && srcpos == srclen))
break;
}
resample_close(handle);
gettimeofday(&tv1, NULL);
deltat =
(tv1.tv_sec + tv1.tv_usec * 0.000001) -
(tv0.tv_sec + tv0.tv_usec * 0.000001);
if (o < 0) {
printf("Error: resample_process returned an error: %d\n", o);
}
if (out <= 0) {
printf("Error: resample_process returned %d samples\n", out);
free(dst_rs);
return;
}
printf(" resample: %.3f seconds, %d outputs\n", deltat, out);
/* do rabbit (Erik's libsamplerate) */
for(i=0; i<dstlen+100; i++)
dst_rabbit[i] = -99.0;
rabbit.data_in = src;
rabbit.data_out = dst_rabbit;
rabbit.input_frames = srclen;
rabbit.output_frames = dstlen;
rabbit.input_frames_used = 0;
rabbit.output_frames_gen = 0;
rabbit.end_of_input = 1;
rabbit.src_ratio = factor;
gettimeofday(&tv0, NULL);
/* src_simple(&rabbit, SRC_SINC_BEST_QUALITY, 1); */
src_simple(&rabbit, SRC_SINC_FASTEST, 1);
/* src_simple(&rabbit, SRC_LINEAR, 1); */
gettimeofday(&tv1, NULL);
deltat =
(tv1.tv_sec + tv1.tv_usec * 0.000001) -
(tv0.tv_sec + tv0.tv_usec * 0.000001);
out_rabbit = rabbit.output_frames_gen;
printf(" rabbit : %.3f seconds, %d outputs\n",
deltat, out_rabbit);
statlen = MIN(out, out_rabbit);
if (anslen > 0)
statlen = MIN(statlen, anslen);
if (ans) {
dostat("resample ", dst_rs, ans, statlen);
dostat("rabbit ", dst_rabbit, ans, statlen);
}
dostat( "RS vs rabbit", dst_rs, dst_rabbit, statlen);
free(dst_rs);
free(dst_rabbit);
}
int main(int argc, char **argv)
{
int i, srclen;
float *src, *ans;
printf("\n*** sin wave, factor = 1.0 *** \n\n");
srclen = 100000;
src = malloc(srclen * sizeof(float));
for(i=0; i<srclen; i++)
src[i] = sin(i/100.0);
runtest(src, srclen, src, srclen, 1.0);
printf("\n*** sin wave, factor = 0.25 *** \n\n");
srclen = 100000;
for(i=0; i<srclen; i++)
src[i] = sin(i/100.0);
ans = malloc((srclen/4) * sizeof(float));
for(i=0; i<srclen/4; i++)
ans[i] = sin(i/25.0);
runtest(src, srclen, ans, srclen/4, 0.25);
free(ans);
printf("\n*** sin wave, factor = 4.0 *** \n\n");
srclen = 20000;
for(i=0; i<srclen; i++)
src[i] = sin(i/100.0);
ans = malloc((srclen*4) * sizeof(float));
for(i=0; i<srclen*4; i++)
ans[i] = sin(i/400.0);
runtest(src, srclen, ans, srclen*4, 4.0);
free(ans);
free(src);
return 0;
}

View File

@ -0,0 +1,213 @@
/**********************************************************************
resample-sndfile.c
Written by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
License: LGPL - see the file LICENSE.txt for more information
**********************************************************************/
#include "../include/libresample.h"
#include <sndfile.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <sys/time.h>
#define MIN(A, B) (A) < (B)? (A) : (B)
void usage(char *progname)
{
fprintf(stderr, "Usage: %s -by <ratio> <input> <output>\n", progname);
fprintf(stderr, " %s -to <rate> <input> <output>\n", progname);
fprintf(stderr, "\n");
exit(-1);
}
int main(int argc, char **argv)
{
SNDFILE *srcfile, *dstfile;
SF_INFO srcinfo, dstinfo;
SF_FORMAT_INFO formatinfo;
char *extension;
void **handle;
int channels;
int srclen, dstlen;
float *src, *srci;
float *dst, *dsti;
double ratio = 0.0;
double srcrate;
double dstrate = 0.0;
struct timeval tv0, tv1;
double deltat;
int numformats;
int pos, bufferpos, outcount;
int i, c;
if (argc != 5)
usage(argv[0]);
if (!strcmp(argv[1], "-by")) {
ratio = atof(argv[2]);
if (ratio <= 0.0) {
fprintf(stderr, "Ratio of %f is illegal\n", ratio);
usage(argv[0]);
}
}
else if (!strcmp(argv[1], "-to")) {
dstrate = atof(argv[2]);
if (dstrate < 10.0 || dstrate > 100000.0) {
fprintf(stderr, "Sample rate of %f is illegal\n", dstrate);
usage(argv[0]);
}
}
else
usage(argv[0]);
memset(&srcinfo, 0, sizeof(srcinfo));
memset(&dstinfo, 0, sizeof(dstinfo));
srcfile = sf_open(argv[3], SFM_READ, &srcinfo);
if (!srcfile) {
fprintf(stderr, "%s", sf_strerror(NULL));
exit(-1);
}
srcrate = srcinfo.samplerate;
if (dstrate == 0.0)
dstrate = srcrate * ratio;
else
ratio = dstrate / srcrate;
channels = srcinfo.channels;
/* figure out format of destination file */
extension = strstr(argv[4], ".");
if (extension) {
extension++;
sf_command(NULL, SFC_GET_FORMAT_MAJOR_COUNT,
&numformats, sizeof(numformats));
for(i=0; i<numformats; i++) {
memset(&formatinfo, 0, sizeof(formatinfo));
formatinfo.format = i;
sf_command(NULL, SFC_GET_FORMAT_MAJOR,
&formatinfo, sizeof(formatinfo));
if (!strcmp(formatinfo.extension, extension)) {
printf("Using %s for output format.\n", formatinfo.name);
dstinfo.format = formatinfo.format |
(srcinfo.format & SF_FORMAT_SUBMASK);
break;
}
}
}
if (!dstinfo.format) {
if (extension)
printf("Warning: output format (%s) not recognized, "
"using same as input format.\n",
extension);
dstinfo.format = srcinfo.format;
}
dstinfo.samplerate = (int)(dstrate + 0.5);
dstinfo.channels = channels;
dstfile = sf_open(argv[4], SFM_WRITE, &dstinfo);
if (!dstfile) {
fprintf(stderr, "%s", sf_strerror(NULL));
exit(-1);
}
printf("Source: %s (%d frames, %.2f Hz)\n",
argv[3], (int)srcinfo.frames, srcrate);
printf("Destination: %s (%.2f Hz, ratio=%.5f)\n", argv[4],
dstrate, ratio);
srclen = 4096;
dstlen = (srclen * ratio + 1000);
srci = (float *)malloc(srclen * channels * sizeof(float));
dsti = (float *)malloc(dstlen * channels * sizeof(float));
src = (float *)malloc(srclen * sizeof(float));
dst = (float *)malloc(dstlen * sizeof(float));
handle = (void **)malloc(channels * sizeof(void *));
for(c=0; c<channels; c++)
handle[c] = resample_open(1, ratio, ratio);
gettimeofday(&tv0, NULL);
pos = 0;
bufferpos = 0;
outcount = 0;
while(pos < srcinfo.frames) {
int block = MIN(srclen-bufferpos, srcinfo.frames-pos);
int lastFlag = (pos+block == srcinfo.frames);
int inUsed, inUsed2=0, out=0, out2=0;
sf_readf_float(srcfile, &srci[bufferpos*channels], block);
block += bufferpos;
for(c=0; c<channels; c++) {
for(i=0; i<block; i++)
src[i] = srci[i*channels+c];
inUsed = 0;
out = resample_process(handle[c], ratio, src, block, lastFlag,
&inUsed, dst, dstlen);
if (c==0) {
inUsed2 = inUsed;
out2 = out;
}
else {
if (inUsed2 != inUsed || out2 != out) {
fprintf(stderr, "Fatal error: channels out of sync!\n");
exit(-1);
}
}
for(i=0; i<out; i++)
{
if(dst[i] <= -1)
dsti[i*channels+c] = -1;
else if(dst[i] >= 1)
dsti[i*channels+c] = 1;
else
dsti[i*channels+c] = dst[i];
}
}
sf_writef_float(dstfile, dsti, out);
bufferpos = block - inUsed;
for(i=0; i<bufferpos*channels; i++)
srci[i] = srci[i+(inUsed*channels)];
pos += inUsed;
outcount += out;
}
sf_close(srcfile);
sf_close(dstfile);
gettimeofday(&tv1, NULL);
deltat =
(tv1.tv_sec + tv1.tv_usec * 0.000001) -
(tv0.tv_sec + tv0.tv_usec * 0.000001);
printf("Elapsed time: %.3f seconds\n", deltat);
printf("%d frames written to output file\n", outcount);
free(src);
free(srci);
free(dst);
free(dsti);
exit(0);
}

View File

@ -0,0 +1,182 @@
/**********************************************************************
testresample.c
Real-time library interface by Dominic Mazzoni
Based on resample-1.7:
http://www-ccrma.stanford.edu/~jos/resample/
License: LGPL - see the file LICENSE.txt for more information
**********************************************************************/
#include "../include/libresample.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MIN(A, B) (A) < (B)? (A) : (B)
void runtest(int srclen, double freq, double factor,
int srcblocksize, int dstblocksize)
{
int expectedlen = (int)(srclen * factor);
int dstlen = expectedlen + 1000;
float *src = (float *)malloc((srclen+100) * sizeof(float));
float *dst = (float *)malloc((dstlen+100) * sizeof(float));
void *handle;
double sum, sumsq, err, rmserr;
int i, out, o, srcused, errcount, rangecount;
int statlen, srcpos, lendiff;
int fwidth;
printf("-- srclen: %d sin freq: %.1f factor: %.3f srcblk: %d dstblk: %d\n",
srclen, freq, factor, srcblocksize, dstblocksize);
for(i=0; i<srclen; i++)
src[i] = sin(i/freq);
for(i=srclen; i<srclen+100; i++)
src[i] = -99.0;
for(i=0; i<dstlen+100; i++)
dst[i] = -99.0;
handle = resample_open(1, factor, factor);
fwidth = resample_get_filter_width(handle);
out = 0;
srcpos = 0;
for(;;) {
int srcBlock = MIN(srclen-srcpos, srcblocksize);
int lastFlag = (srcBlock == srclen-srcpos);
o = resample_process(handle, factor,
&src[srcpos], srcBlock,
lastFlag, &srcused,
&dst[out], MIN(dstlen-out, dstblocksize));
srcpos += srcused;
if (o >= 0)
out += o;
if (o < 0 || (o == 0 && srcpos == srclen))
break;
}
resample_close(handle);
if (o < 0) {
printf("Error: resample_process returned an error: %d\n", o);
}
if (out <= 0) {
printf("Error: resample_process returned %d samples\n", out);
free(src);
free(dst);
return;
}
lendiff = abs(out - expectedlen);
if (lendiff > (int)(2*factor + 1.0)) {
printf(" Expected ~%d, got %d samples out\n",
expectedlen, out);
}
sum = 0.0;
sumsq = 0.0;
errcount = 0.0;
/* Don't compute statistics on all output values; the last few
are guaranteed to be off because it's based on far less
interpolation. */
statlen = out - fwidth;
for(i=0; i<statlen; i++) {
double diff = sin((i/freq)/factor) - dst[i];
if (fabs(diff) > 0.05) {
if (errcount == 0)
printf(" First error at i=%d: expected %.3f, got %.3f\n",
i, sin((i/freq)/factor), dst[i]);
errcount++;
}
sum += fabs(diff);
sumsq += diff * diff;
}
rangecount = 0;
for(i=0; i<statlen; i++) {
if (dst[i] < -1.01 || dst[i] > 1.01) {
if (rangecount == 0)
printf(" Error at i=%d: value is %.3f\n", i, dst[i]);
rangecount++;
}
}
if (rangecount > 1)
printf(" At least %d samples were out of range\n", rangecount);
if (errcount > 0) {
i = out - 1;
printf(" i=%d: expected %.3f, got %.3f\n",
i, sin((i/freq)/factor), dst[i]);
printf(" At least %d samples had significant error.\n", errcount);
}
err = sum / statlen;
rmserr = sqrt(sumsq / statlen);
printf(" Out: %d samples Avg err: %f RMS err: %f\n", out, err, rmserr);
free(src);
free(dst);
}
int main(int argc, char **argv)
{
int i, srclen, dstlen, ifreq;
double factor;
printf("\n*** Vary source block size*** \n\n");
srclen = 10000;
ifreq = 100;
for(i=0; i<20; i++) {
factor = ((rand() % 16) + 1) / 4.0;
dstlen = (int)(srclen * factor + 10);
runtest(srclen, (double)ifreq, factor, 64, dstlen);
runtest(srclen, (double)ifreq, factor, 32, dstlen);
runtest(srclen, (double)ifreq, factor, 8, dstlen);
runtest(srclen, (double)ifreq, factor, 2, dstlen);
runtest(srclen, (double)ifreq, factor, srclen, dstlen);
}
printf("\n*** Vary dest block size ***\n\n");
srclen = 10000;
ifreq = 100;
for(i=0; i<20; i++) {
factor = ((rand() % 16) + 1) / 4.0;
runtest(srclen, (double)ifreq, factor, srclen, 32);
dstlen = (int)(srclen * factor + 10);
runtest(srclen, (double)ifreq, factor, srclen, dstlen);
}
printf("\n*** Resample factor 1.0, testing different srclen ***\n\n");
ifreq = 40;
for(i=0; i<100; i++) {
srclen = (rand() % 30000) + 10;
dstlen = (int)(srclen + 10);
runtest(srclen, (double)ifreq, 1.0, srclen, dstlen);
}
printf("\n*** Resample factor 1.0, testing different sin freq ***\n\n");
srclen = 10000;
for(i=0; i<100; i++) {
ifreq = ((int)rand() % 10000) + 1;
dstlen = (int)(srclen * 10);
runtest(srclen, (double)ifreq, 1.0, srclen, dstlen);
}
printf("\n*** Resample with different factors ***\n\n");
srclen = 10000;
ifreq = 100;
for(i=0; i<100; i++) {
factor = ((rand() % 64) + 1) / 4.0;
dstlen = (int)(srclen * factor + 10);
runtest(srclen, (double)ifreq, factor, srclen, dstlen);
}
return 0;
}

View File

@ -0,0 +1,116 @@
# Microsoft Developer Studio Project File - Name="libresample" - Package Owner=<4>
# Microsoft Developer Studio Generated Build File, Format Version 6.00
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Static Library" 0x0104
CFG=libresample - Win32 Debug
!MESSAGE This is not a valid makefile. To build this project using NMAKE,
!MESSAGE use the Export Makefile command and run
!MESSAGE
!MESSAGE NMAKE /f "libresample.mak".
!MESSAGE
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "libresample.mak" CFG="libresample - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "libresample - Win32 Release" (based on "Win32 (x86) Static Library")
!MESSAGE "libresample - Win32 Debug" (based on "Win32 (x86) Static Library")
!MESSAGE
# Begin Project
# PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName ""
# PROP Scc_LocalPath ""
CPP=cl.exe
RSC=rc.exe
!IF "$(CFG)" == "libresample - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
# ADD CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo /out:"libresample.lib"
!ELSEIF "$(CFG)" == "libresample - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
LIB32=link.exe -lib
# ADD BASE LIB32 /nologo
# ADD LIB32 /nologo /out:"libresampled.lib"
!ENDIF
# Begin Target
# Name "libresample - Win32 Release"
# Name "libresample - Win32 Debug"
# Begin Group "Source Files"
# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
# Begin Source File
SOURCE=..\src\filterkit.c
# End Source File
# Begin Source File
SOURCE=..\src\resample.c
# End Source File
# Begin Source File
SOURCE=..\src\resamplesubs.c
# End Source File
# End Group
# Begin Group "Header Files"
# PROP Default_Filter "h;hpp;hxx;hm;inl"
# Begin Source File
SOURCE=..\src\filterkit.h
# End Source File
# Begin Source File
SOURCE=..\include\libresample.h
# End Source File
# Begin Source File
SOURCE=..\src\resample_defs.h
# End Source File
# End Group
# End Target
# End Project

View File

@ -0,0 +1,192 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="libresample"
SccProjectName=""
SccLocalPath="">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory=".\Debug"
IntermediateDirectory=".\Debug"
ConfigurationType="4"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_LIB"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="2"
PrecompiledHeaderFile=".\Debug/libresample.pch"
AssemblerListingLocation=".\Debug/"
ObjectFile=".\Debug/"
ProgramDataBaseFileName=".\Debug/"
WarningLevel="3"
SuppressStartupBanner="TRUE"
DebugInformationFormat="4"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="libresampled.lib"
SuppressStartupBanner="TRUE"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="_DEBUG"
Culture="1033"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory=".\Release"
IntermediateDirectory=".\Release"
ConfigurationType="4"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
AdditionalOptions="/O2"
Optimization="2"
InlineFunctionExpansion="1"
OptimizeForProcessor="3"
PreprocessorDefinitions="WIN32;NDEBUG;_LIB"
StringPooling="TRUE"
RuntimeLibrary="0"
EnableFunctionLevelLinking="TRUE"
UsePrecompiledHeader="2"
PrecompiledHeaderFile=".\Release/libresample.pch"
AssemblerListingLocation=".\Release/"
ObjectFile=".\Release/"
ProgramDataBaseFileName=".\Release/"
WarningLevel="3"
SuppressStartupBanner="TRUE"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="libresample.lib"
SuppressStartupBanner="TRUE"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
<Tool
Name="VCResourceCompilerTool"
PreprocessorDefinitions="NDEBUG"
Culture="1033"/>
<Tool
Name="VCWebServiceProxyGeneratorTool"/>
<Tool
Name="VCXMLDataGeneratorTool"/>
<Tool
Name="VCManagedWrapperGeneratorTool"/>
<Tool
Name="VCAuxiliaryManagedWrapperGeneratorTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
<File
RelativePath="..\src\filterkit.c">
<FileConfiguration
Name="Debug|Win32">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions=""
BasicRuntimeChecks="3"/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32">
<Tool
Name="VCCLCompilerTool"
Optimization="2"
PreprocessorDefinitions=""/>
</FileConfiguration>
</File>
<File
RelativePath="..\src\resample.c">
<FileConfiguration
Name="Debug|Win32">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions=""
BasicRuntimeChecks="3"/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32">
<Tool
Name="VCCLCompilerTool"
Optimization="2"
PreprocessorDefinitions=""/>
</FileConfiguration>
</File>
<File
RelativePath="..\src\resamplesubs.c">
<FileConfiguration
Name="Debug|Win32">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions=""
BasicRuntimeChecks="3"/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32">
<Tool
Name="VCCLCompilerTool"
Optimization="2"
PreprocessorDefinitions=""/>
</FileConfiguration>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl">
<File
RelativePath="..\src\filterkit.h">
</File>
<File
RelativePath="..\include\libresample.h">
</File>
<File
RelativePath="..\src\resample_defs.h">
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>