├── .gitignore
├── .gitmodules
├── CMakeLists.txt
├── LICENSE
├── README.md
├── doc
├── BBD_Filters.png
├── HP_compare.png
├── Lanczos_compare.png
├── hpresampler.png
├── lanczosresampler.png
├── libsamplerate.png
├── speed_chart.png
└── writeup.md
├── src
├── BaseSRC.h
├── HPResampler.h
├── LanczosSRC.h
├── LibSamplerRateSRC.h
├── src_sndfile.cpp
├── src_test.cpp
├── src_utils
│ ├── FastMath.h
│ ├── HPFilters.h
│ ├── LanczosResampler.h
│ └── SSEComplex.h
└── utils.h
├── tests.py
└── third_party
└── matplotlibcpp.h
/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | /.vscode
3 | .DS_Store
4 | *.wav
5 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "third_party/libsamplerate"]
2 | path = third_party/libsamplerate
3 | url = https://github.com/libsndfile/libsamplerate
4 | [submodule "third_party/libsndfile"]
5 | path = third_party/libsndfile
6 | url = https://github.com/libsndfile/libsndfile
7 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.1)
2 | project(NonIntegerSRC)
3 | set(CMAKE_CXX_STANDARD 17)
4 |
5 | add_executable(src_test src/src_test.cpp)
6 | add_executable(src_sndfile src/src_sndfile.cpp)
7 |
8 | # Link to libsamplerate
9 | set(BUILD_TESTING OFF CACHE BOOL "Don't build CMake tests!")
10 | add_subdirectory(third_party/libsamplerate)
11 |
12 | target_include_directories(src_test PRIVATE third_party/libsamplerate/include)
13 | target_link_libraries(src_test PUBLIC samplerate)
14 |
15 | target_include_directories(src_sndfile PRIVATE third_party/libsamplerate/include)
16 | target_link_libraries(src_sndfile PUBLIC samplerate)
17 |
18 | # Link to libsndfile
19 | set(BUILD_PROGRAMS OFF CACHE BOOL "Don't build libsndfile programs!")
20 | set(BUILD_EXAMPLES OFF CACHE BOOL "Don't build libsndfile examples!")
21 | set(BUILD_REGTEST OFF CACHE BOOL "Don't build libsndfile regtest!")
22 | add_subdirectory(third_party/libsndfile)
23 |
24 | target_include_directories(src_sndfile PRIVATE third_party/libsndfile/include)
25 | target_link_libraries(src_sndfile PUBLIC sndfile)
26 |
27 | # use matplotlibcpp (if needed)
28 | set(USEMATPLOTLIB OFF)
29 | if(USEMATPLOTLIB)
30 | find_package(Python3 COMPONENTS Development NumPy)
31 |
32 | target_include_directories(src_test PRIVATE
33 | ${Python3_INCLUDE_DIRS}
34 | ${Python3_NumPy_INCLUDE_DIRS}
35 | third_party
36 | )
37 |
38 | target_link_libraries(src_test PUBLIC
39 | Python3::Python
40 | Python3::NumPy
41 | )
42 |
43 | target_compile_definitions(src_test PUBLIC MAKE_PLOTS=1)
44 | endif()
45 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) 2018 {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C) 2021 Jatin Chowdhury
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Non-Integer Sample Rate Conversion
2 |
3 | This repository contains a comparison of sample-rate
4 | conversion (SRC) algorithms, with an emphasis on performance
5 | for non-integer SRC factors. Currently two oversampling
6 | algorithms are implemented:
7 |
8 | - libsamplerate (Sinc interpolation, using `SRC_SINC_FASTEST` mode)
9 | - Holters-Parker Resampler (using 4th-order Butterworth filters)
10 | - Lanczos Resampler (borrowed from the [Surge Synthesizer](https://github.com/surge-synthesizer/surge) project)
11 |
12 | ## Results:
13 | On my Linux machine, the HP resampler is faster than libsamplerate
14 | by the following amounts:
15 |
16 | 
17 |
18 | ## Building
19 | ```bash
20 | $ cmake -Bbuild
21 | $ cmake --build build --config Release
22 | ```
23 | Then to run the testing tool, run
24 | `./build/src_test`.
25 |
26 | ## Credits
27 |
28 | - [libsamplerate](https://github.com/libsndfile/libsamplerate)
29 | - The Holters-Parker Resampler is based on the filters derived in their [2018 DAFx paper](https://www.dafx.de/paper-archive/2018/papers/DAFx2018_paper_12.pdf)
30 | - [matplotlibcpp](https://github.com/lava/matplotlib-cpp)
31 | - The HP-Resampler, and Lanczos Resampler use a ton of code borrowed from the [Surge Synthesizer project](https://github.com/surge-synthesizer/surge) (in particular, the `SSEComplex` and `LanczosResampler` classes written by Paul Walker)
32 |
33 | ## License
34 |
35 | The code in this repository is licensed under the GPLv3. Enjoy!
36 |
--------------------------------------------------------------------------------
/doc/BBD_Filters.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jatinchowdhury18/NonIntegerSRC/a2034141116f67917ed6a8f1b306ab22e34b6318/doc/BBD_Filters.png
--------------------------------------------------------------------------------
/doc/HP_compare.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jatinchowdhury18/NonIntegerSRC/a2034141116f67917ed6a8f1b306ab22e34b6318/doc/HP_compare.png
--------------------------------------------------------------------------------
/doc/Lanczos_compare.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jatinchowdhury18/NonIntegerSRC/a2034141116f67917ed6a8f1b306ab22e34b6318/doc/Lanczos_compare.png
--------------------------------------------------------------------------------
/doc/hpresampler.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jatinchowdhury18/NonIntegerSRC/a2034141116f67917ed6a8f1b306ab22e34b6318/doc/hpresampler.png
--------------------------------------------------------------------------------
/doc/lanczosresampler.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jatinchowdhury18/NonIntegerSRC/a2034141116f67917ed6a8f1b306ab22e34b6318/doc/lanczosresampler.png
--------------------------------------------------------------------------------
/doc/libsamplerate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jatinchowdhury18/NonIntegerSRC/a2034141116f67917ed6a8f1b306ab22e34b6318/doc/libsamplerate.png
--------------------------------------------------------------------------------
/doc/speed_chart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jatinchowdhury18/NonIntegerSRC/a2034141116f67917ed6a8f1b306ab22e34b6318/doc/speed_chart.png
--------------------------------------------------------------------------------
/doc/writeup.md:
--------------------------------------------------------------------------------
1 | # Faster Non-Integer Sample Rate Conversion
2 |
3 | A couple months ago, I was doing some research into emulating
4 | [bucket-brigade devices](https://en.wikipedia.org/wiki/Bucket-brigade_device) for creating analog-style
5 | delay-lines, when I ran into a rather interesting paper,
6 | written by [Martin Holters and Julian Parker](http://dafx2018.web.ua.pt/papers/DAFx2018_paper_12.pdf).
7 |
8 | Although bucket-brigade devices (BBDs) are made up of analog
9 | circuits, in concept they behave like a fixed-length digital
10 | delay-line with a variable sample rate which determines the
11 | length of the delay created by the device. One of the primary
12 | challenges of emulating BBDs is performing fast sample rate
13 | conversion (SRC) to match the effective sample rate of the BBD.
14 |
15 | 
16 |
17 | Holters and Parker found a rather brilliant solution to this
18 | problem. They noted that BBDs typically use filters at their
19 | input and output, to reduce imaging and aliasing artifacts,
20 | and figured out how to implement these filters in the digital
21 | domain as "multi-rate" filters, so that the filter can use the
22 | audio sample rate on one side of the filter, and the BBD sample
23 | rate on the other side.
24 |
25 | While I was eventually able to implement a BBD emulation using
26 | Holters and Parker's method, I came to realize that their
27 | algorithm can be used much more generally for any task that
28 | requires sample rate conversion. (If anyone is interested in
29 | the results of the BBD emulation, it is now impemented in
30 | the [Surge Synthesizer](https://surge-synthesizer.github.io)
31 | as part of their "Ensemble" effect.)
32 |
33 | ## Non-Integer Sample Rate Conversion
34 |
35 | There are two fundamental kinds of sample rate conversions:
36 | Integer Sample Rate Conversion and Non-Integer Sample Rate
37 | Conversion.
38 |
39 | With Integer SRC, the sample rate is being changed by an integer
40 | factor. In this case, the block of audio can simply be truncated
41 | or padded with zeros, and then filtered, again to avoid any
42 | imaging or aliasing artifacts in the reconstructed signal.
43 |
44 | It is possible to use two stages of Integer SRC to perform
45 | Non-Integer SRC. For example, to upsample a signal by a factor
46 | of 1.5, one option would be to upsample by a factor of 3,
47 | and then downsample by a factor of 2. However, this approach
48 | can become very costly in cases where a very large upsampling
49 | factor is required.
50 |
51 | 
52 |
53 | A better option that works well for a broad range of SRC
54 | factors is to use interpolation, for example
55 | [Sinc interpolation](https://ccrma.stanford.edu/~jos/Interpolation/Ideal_Bandlimited_Sinc_Interpolation.html), or
56 | [Lanczos interpolation](https://en.wikipedia.org/wiki/Lanczos_resampling).
57 | One of the most commonly used sample rate conversion libraries,
58 | [`libsamplerate`](https://github.com/libsndfile/libsamplerate)
59 | (AKA "Secret Rabbit Code") uses Sinc interpolation, with a couple
60 | different options, to trade off quality for performance.
61 |
62 | Non-Integer sample rate conversion is a very common issue
63 | in audio signal processing. For example, two commonly used
64 | audio sample rates are 44.1 kHz and 48 kHz, which differ by
65 | a factor 0f 1.088. If an algorithm is designed to run at one
66 | sample rate, but a user wants to use the algorithm at a different
67 | sample rate, then real-time non-integer SRC is often required.
68 | In these cases, we want to be able to do the SRC as quickly as
69 | possible, so that the majority of the time spent in our
70 | processing code can be spent actually doing the signal
71 | processing that we're interested in, rather than getting
72 | to and from our target sample rate.
73 |
74 | ## Holters-Parker Resampling
75 |
76 | Here I'd like to introduce Holters-Parker resampling as a
77 | potential alternative to interpolation-based resampling.
78 | Holters and Parker start with a filter in the analog domain,
79 | to be used for anti-aliasing or anti-imaging similar to the
80 | filters used in integer sample rate conversion. Next, Holters
81 | and Parker mention the "impulse invariance" method for
82 | discretizing analog filters. The idea behind impulse invariance
83 | is to derive an expression for the impulse response of the
84 | analog system, and then essentially "sample" the impulse
85 | response at the sample rate of the digital system.
86 |
87 | However, Holters and Parker instead use what they refer to
88 | as a "modified impulse-invariant transform", so that the
89 | input and output signals for the transformed filters may be
90 | at different sample rates. When seen in the context of
91 | sample rate conversion, this is a pretty neat insight:
92 | rather than resampling and then filtering, the filtering and
93 | resampling happen in the same process!
94 |
95 | 
96 |
97 | I won't delve too deeply into the implementation of the
98 | Holters-Parker resampler here, except to note that while
99 | it can be used with any choice of filters, I would
100 | recommend choosing a filter order that is a multiple
101 | of four. The reason for this is that my implementation
102 | uses SIMD registers for computing the filter stages in
103 | parallel. For CPUs with the SSE instruction set (most CPUs
104 | these days), a single SIMD register can contain 4 32-bit
105 | floating point numbers, enabling us to compute a fourth-order
106 | filter for the same computational cost as a first-order
107 | filter. In my implementation, I use a fourth-order Butterworth
108 | filter, but it should be possible to produce a higher-quality
109 | output using a filter with a steeper rolloff, or with a
110 | higher-order filter.
111 |
112 | ## Results
113 | Finally, let's see how the Holters-Parker resampler compares
114 | to the commonly used Sinc interpolation algorithm in
115 | `libsamplerate`. Since I'm primarily interested in
116 | speed rather than quality, I've set `libsamplerate` to
117 | use the `SRC_SINC_FASTEST` option. As it turns out, the
118 | results are not even close! On my Linux system running an
119 | Intel i7 CPU, the Holters-Parker resampler measures 10-40x
120 | faster than `libsamplerate` depending on the sample rate
121 | conversion factor! On a Mac machine, I found comparable
122 | results, while on my Windows machine, the improvements
123 | were even more significant, nearing 40x in almost every
124 | test case. Further, I don't think my implementation of
125 | the Holters-Parker resampler is fully optimal just yet.
126 | With a couple more rounds of optimisations, I bet
127 | I could have it running even faster!
128 |
129 | 
130 |
131 | So does this mean that you should immediately abandon
132 | `libsamplerate` and interpolation-based resampling
133 | altogether? Certainly not! Sinc interpolation is
134 | still the most ideal sample rate conversion scheme
135 | in most cases, and `libsamplerate` has a thoroughly
136 | tested implementation, with well understood trade-offs
137 | between quality and speed. Further, there are other
138 | interpolation-based methods that give decent quality
139 | output and can also out-perform `libsamplerate`.
140 |
141 | My goal here is simply to introduce the Holters-Parker
142 | resampler as a potential option that may be useful for
143 | some cases. Eventually, I'll need to see how my implementation
144 | stacks up in both speed and quality to `libsamplerate`
145 | and other interpolation-based SRC implementations. In
146 | particular, I think choosing the right filter design
147 | for the Holters-Parker resampler will be an important
148 | part of getting the highest quality results.
149 |
150 | ## Conclusion
151 | I hope this discussion of non-integer sample rate conversion
152 | and Holters-Parker resampling has been interesting and useful!
153 | If you'd like to take a look at the source code for my
154 | implementation of the resampler, the code can be found on
155 | [GitHub](https://github.com/jatinchowdhury18/NonIntegerSRC). I would greatly appreciate
156 | any suggestions on how to improve the quality or performance
157 | of the implementation!
158 |
159 | Thanks to the Surge Synthesizer Team for piquing my interest
160 | about all this stuff in the first place, and especially to
161 | Paul Walker for showing me how to use SIMD to vectorize the
162 | filter computations!
163 |
--------------------------------------------------------------------------------
/src/BaseSRC.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | class BaseSRC
4 | {
5 | public:
6 | BaseSRC() = default;
7 | virtual ~BaseSRC() = default;
8 |
9 | virtual void prepare (double sample_rate, int block_size, double src_ratio) = 0;
10 | virtual int process (const float* input, float* output, int num_samples) = 0;
11 | };
12 |
--------------------------------------------------------------------------------
/src/HPResampler.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "BaseSRC.h"
4 | #include "src_utils/HPFilters.h"
5 |
6 | class HPResampler : public BaseSRC
7 | {
8 | public:
9 | HPResampler() = default;
10 |
11 | void prepare (double sample_rate, int block_size, double src_ratio) override
12 | {
13 | ratio = (float) src_ratio;
14 | Ts = 1.0f / ((float) sample_rate);
15 | Ts_in = 1.0f / ((float) sample_rate * ratio);
16 | Ts_out = 1.0f / ((float) sample_rate / ratio);
17 | y_old = 0.0f;
18 |
19 | inFilter = std::make_unique (Ts);
20 | inFilter->set_freq ((float) sample_rate * 0.5f);
21 | inFilter->set_delta (Ts_in);
22 |
23 | outFilter = std::make_unique (Ts_in);
24 | outFilter->set_freq ((float) sample_rate * 0.5f);
25 | outFilter->set_delta (Ts_out);
26 |
27 | middle.resize (int (block_size * ratio) + 1, 0.0f);
28 | }
29 |
30 | #if 0 // use input filter (Dirac)
31 | int process (const float* input, float* output, int num_samples) override
32 | {
33 | inFilter->set_time (tn);
34 | int count = 0;
35 | for (int i = 0; i < num_samples; ++i)
36 | {
37 | while (tn < Ts)
38 | {
39 | inFilter->calcG();
40 | auto sum = FastMath::vSum(SSEComplexMulReal(inFilter->Gcalc, inFilter->x));
41 | output[count++] = -0.95097f * sum;
42 |
43 | tn += Ts_in;
44 | }
45 | tn -= Ts;
46 |
47 | inFilter->process(input[i]);
48 | }
49 |
50 | return count;
51 | }
52 | #else // use output filter (rectangular)
53 | int process (const float* input, float* output, int num_samples) override
54 | {
55 | outFilter->set_time (tn);
56 | int count = 0;
57 | for (int i = 0; i < num_samples; )
58 | {
59 | SSEComplex xOutAccum;
60 | while (tn < Ts)
61 | {
62 | auto y = input[i++];
63 | auto delta = (y - y_old);
64 | y_old = y;
65 |
66 | outFilter->calcG();
67 | xOutAccum += outFilter->Gcalc * delta;
68 | tn += Ts_out;
69 | }
70 | tn -= Ts;
71 |
72 | outFilter->process(xOutAccum);
73 | float sum = FastMath::vSum(xOutAccum._r);
74 | output[count++] = y_old + sum;
75 | }
76 |
77 | return count;
78 | }
79 | #endif
80 |
81 | private:
82 | std::unique_ptr inFilter;
83 | std::unique_ptr outFilter;
84 |
85 | float Ts = 1.0f;
86 | float Ts_in = 1.0f;
87 | float Ts_out = 1.0f;
88 | float tn = 0.0;
89 |
90 | float y_old = 0.0f;
91 | float ratio = 1.0f;
92 |
93 | std::vector middle;
94 | };
95 |
--------------------------------------------------------------------------------
/src/LanczosSRC.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "BaseSRC.h"
4 | #include "src_utils/LanczosResampler.h"
5 | #include
6 |
7 | class LanczosSRC : public BaseSRC
8 | {
9 | public:
10 | LanczosSRC() = default;
11 |
12 | void prepare (double sample_rate, int block_size, double src_ratio) override
13 | {
14 | ratio = src_ratio;
15 | lanczos = std::make_unique ((float) sample_rate, float (sample_rate * ratio));
16 | }
17 |
18 | int process (const float* input, float* output, int num_samples) override
19 | {
20 | lanczos->renormalizePhases();
21 |
22 | for (int i = 0; i < num_samples; ++i)
23 | lanczos->push(input[i]);
24 |
25 | return lanczos->populateNext (output, int (num_samples * ratio + 1));
26 | }
27 |
28 | private:
29 | std::unique_ptr lanczos;
30 | double ratio = 1.0;
31 | };
32 |
--------------------------------------------------------------------------------
/src/LibSamplerRateSRC.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "BaseSRC.h"
4 | #include
5 | #include
6 | #include
7 |
8 | class LibSampleRateSRC : public BaseSRC
9 | {
10 | public:
11 | LibSampleRateSRC() = default;
12 |
13 | void prepare (double /*sample_rate*/, int block_size, double src_ratio) override
14 | {
15 | int error;
16 | src_state.reset (src_new (SRC_SINC_FASTEST, 1, &error));
17 | src_set_ratio (src_state.get(), src_ratio);
18 |
19 | ratio = src_ratio;
20 | // output_data.resize (block_size * src_ratio + 1, 0.0f); // allocate an extra sample for rounding error
21 | }
22 |
23 | int process (const float* input, float* output, int num_samples) override
24 | {
25 | SRC_DATA src_data {
26 | input,
27 | output,
28 | num_samples,
29 | int (num_samples * ratio + 1),
30 | 0,
31 | 0,
32 | 0,
33 | ratio
34 | };
35 |
36 | src_process (src_state.get(), &src_data);
37 |
38 | return (int) src_data.output_frames_gen;
39 | }
40 |
41 | private:
42 | double ratio = 1.0;
43 | std::unique_ptr src_state {nullptr, &src_delete};
44 | };
45 |
--------------------------------------------------------------------------------
/src/src_sndfile.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 |
7 | #include "LibSamplerRateSRC.h"
8 | #include "HPResampler.h"
9 | #include "LanczosSRC.h"
10 |
11 | void usage()
12 | {
13 | std::cout << "USAGE: src_sndfile in_file out_file target_sample_rate mode" << std::endl;
14 | }
15 |
16 | using Vec2d = std::vector>;
17 |
18 | std::pair load_file (char* file, SF_INFO& sf_info)
19 | {
20 | std::cout << "Loading file: " << file << std::endl;
21 |
22 | auto wavFile = sf_open(file, SFM_READ, &sf_info);
23 |
24 | if (sf_info.frames == 0)
25 | {
26 | std::cout << "File could not be opened!" << std::endl;
27 | exit (1);
28 | }
29 |
30 | const double fs = (double) sf_info.samplerate;
31 | std::cout << "Original sample rate: " << fs << std::endl;
32 |
33 | std::vector readInterleaved(sf_info.channels * sf_info.frames, 0.0);
34 | sf_readf_float(wavFile, readInterleaved.data(), sf_info.frames);
35 | sf_close(wavFile);
36 |
37 | Vec2d audio (sf_info.channels, std::vector (sf_info.frames, 0.0));
38 |
39 | // de-interleave channels
40 | for (int i = 0; i < sf_info.frames; ++i)
41 | {
42 | int interleavedPtr = i * sf_info.channels;
43 | for(size_t ch = 0; ch < sf_info.channels; ++ch)
44 | audio[ch][i] = readInterleaved[interleavedPtr + ch];
45 | }
46 |
47 | return std::make_pair(audio, fs);
48 | }
49 |
50 | void write_file (char* file, const Vec2d& audio, double fs, SF_INFO& sf_info)
51 | {
52 | std::cout << "Writing to file: " << file << std::endl;
53 |
54 | const auto channels = (int) audio.size();
55 | const auto frames = (sf_count_t) audio[0].size();
56 | sf_info.frames = frames;
57 | sf_info.samplerate = (int) fs;
58 |
59 | auto wavFile = sf_open(file, SFM_WRITE, &sf_info);
60 | std::vector writeInterleaved(channels * frames, 0.0);
61 |
62 | // de-interleave channels
63 | for (int i = 0; i < frames; ++i)
64 | {
65 | int interleavedPtr = i * channels;
66 | for(int ch = 0; ch < channels; ++ch)
67 | writeInterleaved[interleavedPtr + ch] = audio[ch][i];
68 | }
69 |
70 | sf_writef_float(wavFile, writeInterleaved.data(), frames);
71 | sf_close(wavFile);
72 | }
73 |
74 | std::unique_ptr getSRC (int mode)
75 | {
76 | if (mode == 0)
77 | {
78 | std::cout << "Using mode: libsamplerate" << std::endl;
79 | return std::make_unique();
80 | }
81 |
82 | if (mode == 1)
83 | {
84 | std::cout << "Using mode: HPResampler" << std::endl;
85 | return std::make_unique();
86 | }
87 |
88 | if (mode == 2)
89 | {
90 | std::cout << "Using mode: LanczosResampler" << std::endl;
91 | return std::make_unique();
92 | }
93 |
94 | std::cout << "Mode argument not recogized!" << std::endl;
95 | return std::make_unique();
96 | }
97 |
98 | Vec2d process_data (const Vec2d& input, double ratio, BaseSRC* src, float fs)
99 | {
100 | constexpr int block_size = 2048;
101 |
102 | using clock_t = std::chrono::high_resolution_clock;
103 | using second_t = std::chrono::duration;
104 |
105 | auto start = clock_t::now();
106 |
107 | Vec2d output;
108 | int ch = 0;
109 | for (auto& data : input)
110 | {
111 | std::cout << "Processing channel " << ch++ << "..." << std::endl;
112 |
113 | src->prepare ((double) fs, (int) input.size(), ratio);
114 | std::vector out (int (data.size() * ratio + 1), 0.0f);
115 |
116 | int out_ptr = 0;
117 | for (int i = 0; i + block_size < (int) data.size(); i += block_size)
118 | out_ptr += src->process (&data[i], &out[out_ptr], block_size);
119 |
120 | output.push_back(std::vector (out.begin(), out.begin() + out_ptr));
121 | }
122 |
123 | auto dur = std::chrono::duration_cast(clock_t::now() - start).count();
124 | std::cout << "Finished processing in " << dur << " seconds" << std::endl;
125 |
126 | return output;
127 | }
128 |
129 | int main (int argc, char* argv[])
130 | {
131 | if (argc != 5)
132 | {
133 | usage();
134 | return 0;
135 | }
136 |
137 | SF_INFO sf_info;
138 | auto [audio, fs] = load_file (argv[1], sf_info);
139 |
140 | const auto target_fs = std::atof (argv[3]);
141 | const auto ratio = target_fs / fs;
142 |
143 | auto src = getSRC (std::atoi (argv[4]));
144 | auto audio_out = process_data (audio, ratio, src.get(), (float) fs);
145 |
146 | write_file (argv[2], audio_out, target_fs, sf_info);
147 |
148 | return 0;
149 | }
150 |
--------------------------------------------------------------------------------
/src/src_test.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "LibSamplerRateSRC.h"
6 | #include "HPResampler.h"
7 | #include "LanczosSRC.h"
8 | #include "utils.h"
9 |
10 | #if MAKE_PLOTS
11 | #include
12 | namespace plt = matplotlibcpp;
13 | #endif
14 |
15 | namespace
16 | {
17 | constexpr int n_samples = 1000000;
18 | constexpr float freq = 100.0f;
19 | }
20 |
21 | double process_data (const std::vector& data, std::vector& output, double ratio, BaseSRC* src, float fs)
22 | {
23 | constexpr int block_size = 2048;
24 | src->prepare ((double) fs, block_size, ratio);
25 |
26 | std::vector out (int ((data.size() + block_size) * ratio + 1), 0.0f);
27 |
28 | using clock_t = std::chrono::high_resolution_clock;
29 | using second_t = std::chrono::duration;
30 |
31 | auto start = clock_t::now();
32 |
33 | int out_ptr = 0;
34 | for (int i = 0; i + block_size < (int) data.size(); i += block_size)
35 | out_ptr += src->process (&data[i], &out[out_ptr], block_size);
36 |
37 | auto dur = std::chrono::duration_cast(clock_t::now() - start).count();
38 |
39 | output.resize (out_ptr, 0.0f);
40 | std::copy (out.begin(), out.begin() + out_ptr, output.begin());
41 |
42 | return dur;
43 | }
44 |
45 | void test_libsamplerate (const std::vector& data, double ratio, float fs)
46 | {
47 | LibSampleRateSRC src;
48 | std::vector output;
49 | auto time = process_data (data, output, ratio, &src, fs);
50 | auto [latency, err] = calc_stats (freq, (float) ratio * fs, output);
51 |
52 | // std::cout << " Ratio: " << ratio << std::endl;
53 | std::cout << " libsamplerate Duration: " << time << std::endl;
54 | // std::cout << " Latency: " << latency << std::endl;
55 | // std::cout << " Error: " << err << std::endl;
56 |
57 | #if MAKE_PLOTS
58 | plt::figure();
59 | plt::plot(gen_time (fs, (int) data.size()), data);
60 | plt::plot(gen_time (fs * (float) ratio, (int) output.size()), output);
61 | plt::xlim(0.0, 0.01);
62 | plt::save("./doc/libsamplerate.png");
63 | #endif
64 | }
65 |
66 | void test_hpresampler (const std::vector& data, double ratio, float fs)
67 | {
68 | HPResampler src;
69 | std::vector output;
70 | auto time = process_data (data, output, ratio, &src, fs);
71 | auto [latency, err] = calc_stats (freq, (float) ratio * fs, output);
72 |
73 | // auto max_val = *std::max_element (output.begin(), output.end());
74 | // std::cout << max_val << std::endl;
75 | // std::cout << 1.0f / max_val << std::endl;
76 |
77 | // std::cout << " Ratio: " << ratio << std::endl;
78 | std::cout << " HPResampler Duration: " << time << std::endl;
79 | // std::cout << " Latency: " << latency << std::endl;
80 | // std::cout << " Error: " << err << std::endl;
81 |
82 | #if MAKE_PLOTS
83 | plt::figure();
84 | plt::plot(gen_time (fs, (int) data.size()), data);
85 | plt::plot(gen_time (fs * (float) ratio, (int) output.size()), output);
86 | plt::xlim(0.0, 0.01);
87 | plt::save("./doc/hpresampler.png");
88 | #endif
89 | }
90 |
91 | void test_lanczos (const std::vector& data, double ratio, float fs)
92 | {
93 | LanczosSRC src;
94 | std::vector output;
95 | auto time = process_data (data, output, ratio, &src, fs);
96 | auto [latency, err] = calc_stats (freq, (float) ratio * fs, output);
97 |
98 | // auto max_val = *std::max_element (output.begin(), output.end());
99 | // std::cout << max_val << std::endl;
100 | // std::cout << 1.0f / max_val << std::endl;
101 |
102 | // std::cout << " Ratio: " << ratio << std::endl;
103 | std::cout << " Lanczos Duration: " << time << std::endl;
104 | // std::cout << " Latency: " << latency << std::endl;
105 | // std::cout << " Error: " << err << std::endl;
106 |
107 | #if MAKE_PLOTS
108 | plt::figure();
109 | plt::plot(gen_time (fs, (int) data.size()), data);
110 | plt::plot(gen_time (fs * (float) ratio, (int) output.size()), output);
111 | plt::xlim(0.0, 0.01);
112 | plt::save("./doc/lanczosresampler.png");
113 | #endif
114 | }
115 |
116 | int main()
117 | {
118 | std::cout << "Generating input data..." << std::endl;
119 | auto sine_48 = gen_sine (freq, 48000.0f, n_samples);
120 | auto sine_96 = gen_sine (freq, 96000.0f, n_samples);
121 | auto sine_441 = gen_sine (freq, 44100.0f, n_samples);
122 |
123 | std::cout << "Testing 48k -> 96k..." << std::endl;
124 | test_libsamplerate (sine_48, 2.0, 48000.0f);
125 | test_hpresampler (sine_48, 2.0, 48000.0f);
126 | test_lanczos (sine_48, 2.0, 48000.0f);
127 |
128 | std::cout << "Testing 96k -> 48k..." << std::endl;
129 | test_libsamplerate (sine_96, 0.5, 96000.0f);
130 | test_hpresampler (sine_96, 0.5, 96000.0f);
131 | test_lanczos (sine_96, 0.5, 96000.0f);
132 |
133 | std::cout << "Testing 44.1k -> 48k..." << std::endl;
134 | test_libsamplerate (sine_441, 1.088, 44100.0f);
135 | test_hpresampler (sine_441, 1.088, 44100.0f);
136 | test_lanczos (sine_441, 1.088, 44100.0f);
137 |
138 | std::cout << "Testing 48k -> 44.1k..." << std::endl;
139 | test_libsamplerate (sine_48, 0.919, 48000.0f);
140 | test_hpresampler (sine_48, 0.919, 48000.0f);
141 | test_lanczos (sine_48, 0.919, 48000.0f);
142 |
143 | return 0;
144 | }
145 |
--------------------------------------------------------------------------------
/src/src_utils/FastMath.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #define _USE_MATH_DEFINES
4 | #include
5 | #include
6 |
7 | // Some SSE code borrowed from Surge
8 | namespace FastMath
9 | {
10 |
11 | inline float vSum(__m128 x)
12 | {
13 | __m128 a = _mm_add_ps(x, _mm_movehl_ps(x, x));
14 | a = _mm_add_ss(a, _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 1)));
15 | float f;
16 | _mm_store_ss(&f, a);
17 |
18 | return f;
19 | }
20 |
21 | inline __m128 fastsinSSE(__m128 x) noexcept
22 | {
23 | #define M(a, b) _mm_mul_ps(a, b)
24 | #define A(a, b) _mm_add_ps(a, b)
25 | #define S(a, b) _mm_sub_ps(a, b)
26 | #define F(a) _mm_set_ps1(a)
27 | #define C(x) __m128 m##x = F((float)x)
28 |
29 | /*
30 | auto numerator = -x * (-(float)11511339840 +
31 | x2 * ((float)1640635920 + x2 * (-(float)52785432 + x2 * (float)479249)));
32 | auto denominator =
33 | (float)11511339840 + x2 * ((float)277920720 + x2 * ((float)3177720 + x2 * (float)18361));
34 | */
35 | C(11511339840);
36 | C(1640635920);
37 | C(52785432);
38 | C(479249);
39 | C(277920720);
40 | C(3177720);
41 | C(18361);
42 | auto mnegone = F(-1);
43 |
44 | auto x2 = M(x, x);
45 |
46 | auto num = M(mnegone,
47 | M(x, S(M(x2, A(m1640635920, M(x2, S(M(x2, m479249), m52785432)))), m11511339840)));
48 | auto den = A(m11511339840, M(x2, A(m277920720, M(x2, A(m3177720, M(x2, m18361))))));
49 |
50 | #undef C
51 | #undef M
52 | #undef A
53 | #undef S
54 | #undef F
55 | return _mm_div_ps(num, den);
56 | }
57 |
58 | inline __m128 fastcosSSE(__m128 x) noexcept
59 | {
60 | #define M(a, b) _mm_mul_ps(a, b)
61 | #define A(a, b) _mm_add_ps(a, b)
62 | #define S(a, b) _mm_sub_ps(a, b)
63 | #define F(a) _mm_set_ps1(a)
64 | #define C(x) __m128 m##x = F((float)x)
65 |
66 | // auto x2 = x * x;
67 | auto x2 = M(x, x);
68 |
69 | C(39251520);
70 | C(18471600);
71 | C(1075032);
72 | C(14615);
73 | C(1154160);
74 | C(16632);
75 | C(127);
76 |
77 | // auto numerator = -(-(float)39251520 + x2 * ((float)18471600 + x2 * (-1075032 + 14615 * x2)));
78 | auto num = S(m39251520, M(x2, A(m18471600, M(x2, S(M(m14615, x2), m1075032)))));
79 |
80 | // auto denominator = (float)39251520 + x2 * (1154160 + x2 * (16632 + x2 * 127));
81 | auto den = A(m39251520, M(x2, A(m1154160, M(x2, A(m16632, M(x2, m127))))));
82 | #undef C
83 | #undef M
84 | #undef A
85 | #undef S
86 | #undef F
87 | return _mm_div_ps(num, den);
88 | }
89 |
90 | inline __m128 clampToPiRangeSSE(__m128 x)
91 | {
92 | const auto mpi = _mm_set1_ps(M_PI);
93 | const auto m2pi = _mm_set1_ps(2.0 * M_PI);
94 | const auto oo2p = _mm_set1_ps(1.0 / (2.0 * M_PI));
95 | const auto mz = _mm_setzero_ps();
96 |
97 | auto y = _mm_add_ps(x, mpi);
98 | auto yip = _mm_cvtepi32_ps(_mm_cvttps_epi32(_mm_mul_ps(y, oo2p)));
99 | auto p = _mm_sub_ps(y, _mm_mul_ps(m2pi, yip));
100 | auto off = _mm_and_ps(_mm_cmplt_ps(p, mz), m2pi);
101 | p = _mm_add_ps(p, off);
102 |
103 | return _mm_sub_ps(p, mpi);
104 | }
105 |
106 | } // namespace FastMath
107 |
--------------------------------------------------------------------------------
/src/src_utils/HPFilters.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "SSEComplex.h"
4 |
5 | /**
6 | * Bucket-Bridage Device filters, as derived by
7 | * Martin Holters and Julian Parker:
8 | * http://dafx2018.web.ua.pt/papers/DAFx2018_paper_12.pdf
9 | */
10 |
11 | /**
12 | * Anti-aliasing/reconstruction filters used by JUNO-60 chorus.
13 | * Root/Pole analysis borrowed from the above paper.
14 | */
15 | namespace FilterSpec
16 | {
17 | constexpr size_t N_filt = 4;
18 |
19 | constexpr std::complex iFiltRoot[] = {{-10329.2715f, -329.848f},
20 | {-10329.2715f, +329.848f},
21 | {366.990557f, -1811.4318f},
22 | {366.990557f, +1811.4318f}};
23 | constexpr std::complex iFiltPole[] = {
24 | {-55482.0f, -25082.0f}, {-55482.0f, +25082.0f}, {-26292.0f, -59437.0f}, {-26292.0f, +59437.0f}};
25 |
26 | constexpr std::complex oFiltRoot[] = {
27 | {-11256.0f, -99566.0f}, {-11256.0f, +99566.0f}, {-13802.0f, -24606.0f}, {-13802.0f, +24606.0f}};
28 | constexpr std::complex oFiltPole[] = {
29 | {-51468.0f, -21437.0f}, {-51468.0f, +21437.0f}, {-26276.0f, -59699.0f}, {-26276.0f, +59699.0f}};
30 | } // namespace FilterSpec
31 |
32 | inline SSEComplex fast_complex_pow(__m128 angle, float b)
33 | {
34 | const __m128 scalar = _mm_set1_ps(b);
35 | auto angle_pow = _mm_mul_ps(angle, scalar);
36 | return SSEComplex::fastExp(angle_pow);
37 | }
38 |
39 | struct InputFilterBank
40 | {
41 | public:
42 | InputFilterBank(float sampleTime) : Ts(sampleTime)
43 | {
44 | float root_real alignas(16)[4];
45 | float root_imag alignas(16)[4];
46 | float pole_real alignas(16)[4];
47 | float pole_imag alignas(16)[4];
48 | for (size_t i = 0; i < FilterSpec::N_filt; ++i)
49 | {
50 | root_real[i] = FilterSpec::iFiltRoot[i].real();
51 | root_imag[i] = FilterSpec::iFiltRoot[i].imag();
52 |
53 | pole_real[i] = FilterSpec::iFiltPole[i].real();
54 | pole_imag[i] = FilterSpec::iFiltPole[i].imag();
55 | }
56 | roots = SSEComplex(root_real, root_imag);
57 | poles = SSEComplex(pole_real, pole_imag);
58 | }
59 |
60 | inline void set_freq(float freq)
61 | {
62 | constexpr float originalCutoff = 9900.0f;
63 | const float freqFactor = freq / originalCutoff;
64 | root_corr = roots * freqFactor;
65 | pole_corr = poles.map([&freqFactor, this](const std::complex &f) {
66 | return std::exp(f * freqFactor * Ts);
67 | });
68 |
69 | pole_corr_angle =
70 | pole_corr.map_float([](const std::complex &f) { return std::arg(f); });
71 |
72 | gCoef = root_corr * Ts;
73 | }
74 |
75 | inline void set_time(float tn)
76 | {
77 | Gcalc =
78 | gCoef * pole_corr.map([&tn](const std::complex &f) { return std::pow(f, tn); });
79 | }
80 |
81 | inline void set_delta(float delta) { Aplus = fast_complex_pow(pole_corr_angle, delta); }
82 |
83 | inline void calcG() noexcept { Gcalc = Aplus * Gcalc; }
84 |
85 | inline void process(float u)
86 | {
87 | x = pole_corr * x + SSEComplex(_mm_set1_ps(u), _mm_set1_ps(0.0f));
88 | }
89 |
90 | SSEComplex x;
91 | SSEComplex Gcalc{{1.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 0.0f, 0.0f}};
92 |
93 | private:
94 | SSEComplex roots;
95 | SSEComplex poles;
96 | SSEComplex root_corr;
97 | SSEComplex pole_corr;
98 | __m128 pole_corr_angle;
99 |
100 | SSEComplex Aplus;
101 |
102 | const float Ts;
103 | SSEComplex gCoef;
104 | };
105 |
106 | struct OutputFilterBank
107 | {
108 | public:
109 | OutputFilterBank(float sampleTime) : Ts(sampleTime)
110 | {
111 | float gcoefs_real alignas(16)[4];
112 | float gcoefs_imag alignas(16)[4];
113 | float pole_real alignas(16)[4];
114 | float pole_imag alignas(16)[4];
115 | for (size_t i = 0; i < FilterSpec::N_filt; ++i)
116 | {
117 | auto gVal = FilterSpec::oFiltRoot[i] / FilterSpec::oFiltPole[i];
118 | gcoefs_real[i] = gVal.real();
119 | gcoefs_imag[i] = gVal.imag();
120 |
121 | pole_real[i] = FilterSpec::oFiltPole[i].real();
122 | pole_imag[i] = FilterSpec::oFiltPole[i].imag();
123 | }
124 | gCoef = SSEComplex(gcoefs_real, gcoefs_imag);
125 | poles = SSEComplex(pole_real, pole_imag);
126 | }
127 |
128 | inline float calcH0() const { return -1.0f * FastMath::vSum(gCoef.real()); }
129 |
130 | inline void set_freq(float freq)
131 | {
132 | constexpr float originalCutoff = 9500.0f;
133 | const float freqFactor = freq / originalCutoff;
134 | pole_corr = poles.map([&freqFactor, this](const std::complex &f) {
135 | return std::exp(f * freqFactor * Ts);
136 | });
137 |
138 | pole_corr_angle =
139 | pole_corr.map_float([](const std::complex &f) { return std::arg(f); });
140 |
141 | Amult = gCoef * pole_corr;
142 | }
143 |
144 | inline void set_time(float tn)
145 | {
146 | Gcalc = Amult * pole_corr.map(
147 | [&tn](const std::complex &f) { return std::pow(f, 1.0f - tn); });
148 | }
149 |
150 | inline void set_delta(float delta) { Aplus = fast_complex_pow(pole_corr_angle, -delta); }
151 |
152 | inline void calcG() noexcept { Gcalc = Aplus * Gcalc; }
153 |
154 | inline void process(SSEComplex u) { x = pole_corr * x + u; }
155 |
156 | SSEComplex x;
157 | SSEComplex Gcalc{{1.0f, 1.0f, 1.0f, 1.0f}, {0.0f, 0.0f, 0.0f, 0.0f}};
158 |
159 | private:
160 | SSEComplex gCoef;
161 | SSEComplex poles;
162 | SSEComplex root_corr;
163 | SSEComplex pole_corr;
164 | __m128 pole_corr_angle;
165 |
166 | SSEComplex Aplus;
167 |
168 | const float Ts;
169 | SSEComplex Amult;
170 | };
171 |
--------------------------------------------------------------------------------
/src/src_utils/LanczosResampler.h:
--------------------------------------------------------------------------------
1 | /*
2 | ** Surge Synthesizer is Free and Open Source Software
3 | **
4 | ** Surge is made available under the Gnu General Public License, v3.0
5 | ** https://www.gnu.org/licenses/gpl-3.0.en.html
6 | **
7 | ** Copyright 2004-2021 by various individuals as described by the Git transaction log
8 | **
9 | ** All source at: https://github.com/surge-synthesizer/surge.git
10 | **
11 | ** Surge was a commercial product from 2004-2018, with Copyright and ownership
12 | ** in that period held by Claes Johanson at Vember Audio. Claes made Surge
13 | ** open source in September 2018.
14 | */
15 |
16 | #ifndef SURGE_LANCZOSRESAMPLER_H
17 | #define SURGE_LANCZOSRESAMPLER_H
18 |
19 | #include "FastMath.h"
20 | #include
21 | #include
22 |
23 | /*
24 | * See https://en.wikipedia.org/wiki/Lanczos_resampling
25 | */
26 |
27 | struct LanczosResampler
28 | {
29 | static constexpr size_t A = 4;
30 | static constexpr size_t BUFFER_SZ = 4096;
31 | static constexpr size_t filterWidth = A * 2;
32 | static constexpr size_t tableObs = 8192;
33 | static constexpr double dx = 1.0 / (tableObs);
34 |
35 | // Fixme: Make this static and shared
36 | static float lanczosTable alignas(16)[tableObs][filterWidth], lanczosTableDX
37 | alignas(16)[tableObs][filterWidth];
38 | static bool tablesInitialized;
39 |
40 | float input[BUFFER_SZ * 2];
41 | int wp = 0;
42 | float sri, sro;
43 | double phaseI, phaseO, dPhaseI, dPhaseO;
44 |
45 | inline double kernel(double x)
46 | {
47 | if (fabs(x) < 1e-7)
48 | return 1;
49 | return A * std::sin(M_PI * x) * std::sin(M_PI * x / A) / (M_PI * M_PI * x * x);
50 | }
51 |
52 | LanczosResampler(float inputRate, float outputRate) : sri(inputRate), sro(outputRate)
53 | {
54 | phaseI = 0;
55 | phaseO = 0;
56 |
57 | dPhaseI = 1.0;
58 | dPhaseO = sri / sro;
59 |
60 | memset(input, 0, 2 * BUFFER_SZ * sizeof(float));
61 | if (!tablesInitialized)
62 | {
63 | for (int t = 0; t < tableObs; ++t)
64 | {
65 | double x0 = dx * t;
66 | for (int i = 0; i < filterWidth; ++i)
67 | {
68 | double x = x0 + i - A;
69 | lanczosTable[t][i] = kernel(x);
70 | }
71 | }
72 | for (int t = 0; t < tableObs; ++t)
73 | {
74 | for (int i = 0; i < filterWidth; ++i)
75 | {
76 | lanczosTableDX[t][i] =
77 | lanczosTable[(t + 1) & (tableObs - 1)][i] - lanczosTable[t][i];
78 | }
79 | }
80 | tablesInitialized = true;
81 | }
82 | }
83 |
84 | inline void push(float f)
85 | {
86 | input[wp] = f;
87 | input[wp + BUFFER_SZ] = f; // this way we can always wrap
88 | wp = (wp + 1) & (BUFFER_SZ - 1);
89 | phaseI += dPhaseI;
90 | }
91 |
92 | inline float readZOH(double xBack) const
93 | {
94 | double p0 = wp - xBack;
95 | int idx0 = (int)p0;
96 | idx0 = (idx0 + BUFFER_SZ) & (BUFFER_SZ - 1);
97 | if (idx0 <= A)
98 | idx0 += BUFFER_SZ;
99 |
100 | return input[idx0];
101 | }
102 |
103 | inline float readLin(double xBack) const
104 | {
105 | double p0 = wp - xBack;
106 | int idx0 = (int)p0;
107 | float frac = p0 - idx0;
108 | idx0 = (idx0 + BUFFER_SZ) & (BUFFER_SZ - 1);
109 | if (idx0 <= A)
110 | idx0 += BUFFER_SZ;
111 |
112 | return (1.0 - frac) * input[idx0] + frac * input[idx0 + 1];
113 | }
114 |
115 | inline float read(double xBack) const
116 | {
117 | double p0 = wp - xBack;
118 | int idx0 = floor(p0);
119 | double off0 = 1.0 - (p0 - idx0);
120 |
121 | idx0 = (idx0 + BUFFER_SZ) & (BUFFER_SZ - 1);
122 | idx0 += (idx0 <= A) * BUFFER_SZ;
123 |
124 | double off0byto = off0 * tableObs;
125 | int tidx = (int)(off0byto);
126 | double fidx = (off0byto - tidx);
127 |
128 | auto fl = _mm_set1_ps((float)fidx);
129 | auto f0 = _mm_load_ps(&lanczosTable[tidx][0]);
130 | auto df0 = _mm_load_ps(&lanczosTableDX[tidx][0]);
131 |
132 | f0 = _mm_add_ps(f0, _mm_mul_ps(df0, fl));
133 |
134 | auto f1 = _mm_load_ps(&lanczosTable[tidx][4]);
135 | auto df1 = _mm_load_ps(&lanczosTableDX[tidx][4]);
136 | f1 = _mm_add_ps(f1, _mm_mul_ps(df1, fl));
137 |
138 | auto d0 = _mm_loadu_ps(&input[idx0 - A]);
139 | auto d1 = _mm_loadu_ps(&input[idx0]);
140 | auto rv = _mm_add_ps(_mm_mul_ps(f0, d0), _mm_mul_ps(f1, d1));
141 | return FastMath::vSum(rv);
142 | }
143 |
144 | inline size_t inputsRequiredToGenerateOutputs(size_t desiredOutputs) const
145 | {
146 | /*
147 | * So (phaseI + dPhaseI * res - phaseO - dPhaseO * desiredOutputs) * sri > A + 1
148 | *
149 | * Use the fact that dPhaseI = sri and find
150 | * res > (A+1) - (phaseI - phaseO + dPhaseO * desiredOutputs) * sri
151 | */
152 | double res = A + 1 - (phaseI - phaseO - dPhaseO * desiredOutputs);
153 |
154 | return (size_t)std::max(res + 1, 0.0); // Check this calculation
155 | }
156 |
157 | size_t populateNext(float *f, size_t max);
158 |
159 | // /*
160 | // * This is a dangerous but efficient function which more quickly
161 | // * populates BLOCK_SIZE_OS worth of items, but assumes you have
162 | // * checked the range.
163 | // */
164 | // void populateNextBlockSizeOS(float *f);
165 |
166 | inline void advanceReadPointer(size_t n) { phaseO += n * dPhaseO; }
167 | inline void snapOutToIn()
168 | {
169 | phaseO = 0;
170 | phaseI = 0;
171 | }
172 |
173 | inline void renormalizePhases()
174 | {
175 | phaseI -= phaseO;
176 | phaseO = 0;
177 | }
178 | };
179 |
180 | float LanczosResampler::lanczosTable alignas(
181 | 16)[LanczosResampler::tableObs][LanczosResampler::filterWidth];
182 | float LanczosResampler::lanczosTableDX alignas(
183 | 16)[LanczosResampler::tableObs][LanczosResampler::filterWidth];
184 |
185 | bool LanczosResampler::tablesInitialized = false;
186 |
187 | size_t LanczosResampler::populateNext(float *f, size_t max)
188 | {
189 | int populated = 0;
190 | while (populated < max && (phaseI - phaseO) > A + 1)
191 | {
192 | f[populated] = read(phaseI - phaseO);
193 | phaseO += dPhaseO;
194 | populated++;
195 | }
196 | return populated;
197 | }
198 |
199 | #endif // SURGE_LANCZOSRESAMPLER_H
200 |
--------------------------------------------------------------------------------
/src/src_utils/SSEComplex.h:
--------------------------------------------------------------------------------
1 | /*
2 | ** Surge Synthesizer is Free and Open Source Software
3 | **
4 | ** Surge is made available under the Gnu General Public License, v3.0
5 | ** https://www.gnu.org/licenses/gpl-3.0.en.html
6 | **
7 | ** Copyright 2004-2021 by various individuals as described by the Git transaction log
8 | **
9 | ** All source at: https://github.com/surge-synthesizer/surge.git
10 | **
11 | ** Surge was a commercial product from 2004-2018, with Copyright and ownership
12 | ** in that period held by Claes Johanson at Vember Audio. Claes made Surge
13 | ** open source in September 2018.
14 | */
15 |
16 | /*
17 | * You would hope you could specialize std::complex for SSE, but alas, you cannot
18 | * because it assumes (in the spec) that you only do float double or longdouble and
19 | * that shows up in how it is coded. So instead write a little SSEComplex class
20 | * with limited capabilities
21 | */
22 |
23 | #ifndef SURGE_SSECOMPLEX_H
24 | #define SURGE_SSECOMPLEX_H
25 |
26 | #include "FastMath.h"
27 | #include
28 | #include
29 |
30 | struct SSEComplex
31 | {
32 | typedef __m128 T;
33 | T _r, _i;
34 | constexpr SSEComplex(const T &r = _mm_setzero_ps(), const T &i = _mm_setzero_ps())
35 | : _r(r), _i(i)
36 | {
37 | }
38 |
39 | SSEComplex(float r[4], float i[4])
40 | {
41 | _r = _mm_loadu_ps(r);
42 | _i = _mm_loadu_ps(i);
43 | }
44 |
45 | inline __m128 real() const { return _r; }
46 | inline __m128 imag() const { return _i; }
47 |
48 | SSEComplex(std::initializer_list r, std::initializer_list i)
49 | {
50 | if (r.size() != 4 && i.size() != 4)
51 | {
52 | throw std::invalid_argument("Initialize lists must be of size 4");
53 | }
54 | float rfl alignas(16)[4], ifl alignas(16)[4];
55 | for (int q = 0; q < 4; ++q)
56 | {
57 | rfl[q] = *(r.begin() + q);
58 | ifl[q] = *(i.begin() + q);
59 | }
60 |
61 | _r = _mm_load_ps(rfl);
62 | _i = _mm_load_ps(ifl);
63 | }
64 | inline SSEComplex &operator+=(const SSEComplex &o)
65 | {
66 | _r = _mm_add_ps(_r, o._r);
67 | _i = _mm_add_ps(_i, o._i);
68 | return *this;
69 | }
70 |
71 | std::complex atIndex(int i) const
72 | {
73 | float rfl alignas(16)[4], ifl alignas(16)[4];
74 | _mm_store_ps(rfl, _r);
75 | _mm_store_ps(ifl, _i);
76 | return std::complex{rfl[i], ifl[i]};
77 | }
78 |
79 | inline static SSEComplex fastExp(__m128 angle)
80 | {
81 | angle = FastMath::clampToPiRangeSSE(angle);
82 | return {FastMath::fastcosSSE(angle), FastMath::fastsinSSE(angle)};
83 | }
84 |
85 | inline SSEComplex map(std::function(const std::complex &)> f)
86 | {
87 | float rfl alignas(16)[4], ifl alignas(16)[4];
88 | _mm_store_ps(rfl, _r);
89 | _mm_store_ps(ifl, _i);
90 |
91 | float rflR alignas(16)[4], iflR alignas(16)[4];
92 | for (int i = 0; i < 4; ++i)
93 | {
94 | auto a = std::complex{rfl[i], ifl[i]};
95 | auto b = f(a);
96 | rflR[i] = b.real();
97 | iflR[i] = b.imag();
98 | }
99 | return {_mm_load_ps(rflR), _mm_load_ps(iflR)};
100 | }
101 |
102 | inline __m128 map_float(std::function &)> f)
103 | {
104 | float rfl alignas(16)[4], ifl alignas(16)[4];
105 | _mm_store_ps(rfl, _r);
106 | _mm_store_ps(ifl, _i);
107 |
108 | float out alignas(16)[4];
109 | for (int i = 0; i < 4; ++i)
110 | {
111 | auto a = std::complex{rfl[i], ifl[i]};
112 | out[i] = f(a);
113 | }
114 | return _mm_load_ps(out);
115 | }
116 | };
117 |
118 | inline SSEComplex operator+(const SSEComplex &a, const SSEComplex &b)
119 | {
120 | return {_mm_add_ps(a._r, b._r), _mm_add_ps(a._i, b._i)};
121 | }
122 |
123 | inline __m128 SSEComplexMulReal(const SSEComplex &a, const SSEComplex &b)
124 | {
125 | return _mm_sub_ps(_mm_mul_ps(a._r, b._r), _mm_mul_ps(a._i, b._i));
126 | }
127 |
128 | inline __m128 SSEComplexMulImag(const SSEComplex &a, const SSEComplex &b)
129 | {
130 | return _mm_add_ps(_mm_mul_ps(a._r, b._i), _mm_mul_ps(a._i, b._r));
131 | }
132 |
133 | inline SSEComplex operator*(const SSEComplex &a, const SSEComplex &b)
134 | {
135 | return {SSEComplexMulReal(a, b), SSEComplexMulImag(a, b)};
136 | }
137 |
138 | inline SSEComplex operator*(const SSEComplex &a, const float &b)
139 | {
140 | const __m128 scalar = _mm_set1_ps(b);
141 | return {_mm_mul_ps(a._r, scalar), _mm_mul_ps(a._i, scalar)};
142 | }
143 |
144 | #endif // SURGE_SSECOMPLEX_H
145 |
--------------------------------------------------------------------------------
/src/utils.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | std::vector gen_time (float fs, int num_samples)
6 | {
7 | std::vector time (num_samples);
8 | std::generate (time.begin(), time.end(), [=, n = 0.0f] () mutable { return n++ / fs; });
9 |
10 | return std::move (time);
11 | }
12 |
13 | std::vector gen_sine (float freq, float fs, int num_samples)
14 | {
15 | std::vector data (num_samples);
16 | std::generate (data.begin(), data.end(), [=, n = 0.0f] () mutable { return std::sin (2.0f * M_PI * n++ * freq / fs); });
17 |
18 | return std::move (data);
19 | }
20 |
21 | int calc_latency (const std::vector& data, const std::vector& ref_data)
22 | {
23 | auto find_first_point5 = [] (const std::vector& x) -> int {
24 | for (int i = 0; i < (int) x.size(); ++i)
25 | {
26 | if (x[i] >= 0.5f)
27 | return i;
28 | }
29 | return 0;
30 | };
31 |
32 | auto ref_one = find_first_point5 (ref_data);
33 | auto actual_one = find_first_point5 (data);
34 |
35 | return actual_one - ref_one;
36 | }
37 |
38 | std::pair calc_stats (float freq, float fs, const std::vector& data)
39 | {
40 | const int num_samples = (int) data.size();
41 | auto compare_data = gen_sine (freq, fs, num_samples);
42 | auto latency_samp = calc_latency (data, compare_data);
43 |
44 | float error_sum = 0.0f;
45 | for (int i = 0; i < num_samples - latency_samp; ++i)
46 | error_sum += std::abs (compare_data[i] - data[i + latency_samp]);
47 |
48 | // for (int i = 0; i < 50; i += 5)
49 | // std::cout << compare_data[i] << ", " << data[i] << std::endl;
50 |
51 | auto avg_error = error_sum / (float) num_samples;
52 | return std::make_pair (latency_samp, avg_error);
53 | }
54 |
--------------------------------------------------------------------------------
/tests.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from scipy.io import wavfile
3 | import matplotlib.pyplot as plt
4 | import os
5 |
6 | FS = 44100
7 | N = int(FS)
8 | freq = 100.0
9 | x = np.sin(2 * np.pi * np.arange(N) * freq / FS)
10 | wavfile.write('audio/sine_441.wav', FS, x)
11 |
12 | def plot_fft(x, fs, *args, **kwargs):
13 | freqs = np.fft.rfftfreq(len(x), 1.0 / fs)
14 | X = np.fft.rfft(x) / len(x)
15 | plt.semilogx(freqs, 20 * np.log10(np.abs(X)), *args, **kwargs)
16 |
17 | # plot_fft(x, FS)
18 |
19 | target_fs = 96 # kHz
20 |
21 | os.system(f'./build/src_sndfile audio/sine_441.wav audio/sine_{target_fs}_SRC.wav {1000 * target_fs} 0')
22 | os.system(f'./build/src_sndfile audio/sine_441.wav audio/sine_{target_fs}_HPR.wav {1000 * target_fs} 1')
23 | os.system(f'./build/src_sndfile audio/sine_441.wav audio/sine_{target_fs}_LCZ.wav {1000 * target_fs} 2')
24 |
25 | fs, x1 = wavfile.read('audio/sine_96_SRC.wav')
26 | plot_fft(x1, fs, label='SRC')
27 |
28 | # fs, x2 = wavfile.read('audio/sine_96_HPR.wav')
29 | # plot_fft(x2, fs, '--', label='HP')
30 |
31 | fs, x3 = wavfile.read('audio/sine_96_LCZ.wav')
32 | plot_fft(x3, fs, '--', label='Lanczos')
33 |
34 | plt.grid()
35 | plt.ylim(-150)
36 | plt.legend()
37 |
38 | plt.title('SRC Comparison')
39 | plt.xlabel('Frequency [Hz]')
40 | plt.ylabel('Amplitude [dB]')
41 |
42 | plt.show()
43 |
--------------------------------------------------------------------------------
/third_party/matplotlibcpp.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | // Python headers must be included before any system headers, since
4 | // they define _POSIX_C_SOURCE
5 | #include
6 |
7 | #include
8 | #include