Add pre-packaged dependency libraries (ESP32-audioI2S and PNGdec)

This commit is contained in:
drjones
2026-07-01 19:18:01 -07:00
parent e207c9a5b7
commit 7606b9d5df
146 changed files with 106590 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
name: Close inactive issues
on:
schedule:
- cron: "30 1 * * *"
jobs:
stale:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v9
with:
days-before-issue-stale: 30
days-before-issue-close: 14
stale-issue-label: "stale"
stale-issue-message: "This issue is stale because it has been open for 30 days with no activity."
close-issue-message: "This issue was closed because it has been inactive for 14 days since being marked as stale."
days-before-pr-stale: 45
days-before-pr-close: 10
stale-pr-message: 'This PR is stale because it has been open 45 days with no activity. Remove stale label or comment or this will be closed in 10 days.'
close-pr-message: 'This PR was closed because it has been stalled for 10 days with no activity.'

View File

@@ -0,0 +1,9 @@
get_filename_component(dir ${CMAKE_CURRENT_LIST_FILE} PATH)
FILE(GLOB_RECURSE app_sources ${dir}/src/*.cpp)
idf_component_register(SRCS ${app_sources}
REQUIRES "ESP32-audioI2S"
INCLUDE_DIRS "src"
REQUIRES wear_levelling Arduino
)

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, 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
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -0,0 +1,97 @@
# ESP32-audioI2S
:warning: **This library only works on multi-core chips like ESP32, ESP32-S3 and ESP32-P4. Your board must have PSRAM! It does not work on the ESP32-S2, ESP32-C3 etc** :warning:
Plays mp3, m4a and wav files from SD card via I2S with external hardware.
HELIX-mp3 and faad2-aac decoder is included. There is also an OPUS decoder for Fullband, an VORBIS decoder and a FLAC decoder.
Works with MAX98357A (3 Watt amplifier with DAC), connected three lines (DOUT, BLCK, LRC) to I2S. The I2S output frequency is always 48kHz, regardless of the input source, so Bluetooth devices can also be connected without any problems.
For stereo are two MAX98357A necessary. AudioI2S works with UDA1334A (Adafruit I2S Stereo Decoder Breakout Board), PCM5102A and CS4344.
Other HW may work but not tested. Plays also icy-streams, GoogleTTS and OpenAIspeech. Can be compiled with Arduino IDE. [WIKI](https://github.com/schreibfaul1/ESP32-audioI2S/wiki)
```` c++
#include "Arduino.h"
#include "WiFi.h"
#include "Audio.h"
// Digital I/O used
#define I2S_DOUT 25
#define I2S_BCLK 27
#define I2S_LRC 26
String ssid = "*******";
String password = "*******";
Audio audio;
// callbacks
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info; // optional
Serial.begin(115200);
WiFi.begin(ssid.c_str(), password.c_str());
while (WiFi.status() != WL_CONNECTED) delay(1500);
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(21); // default 0...21
audio.connecttohost("http://stream.antennethueringen.de/live/aac-64/stream.antennethueringen.de/");
}
void loop(){
audio.loop();
vTaskDelay(1);
}
````
You can find more examples here: https://github.com/schreibfaul1/ESP32-audioI2S/tree/master/examples
````c++
// detailed cb output
void my_audio_info(Audio::msg_t m) {
switch(m.e){
case Audio::evt_info: Serial.printf("info: ....... %s\n", m.msg); break;
case Audio::evt_eof: Serial.printf("end of file: %s\n", m.msg); break;
case Audio::evt_bitrate: Serial.printf("bitrate: .... %s\n", m.msg); break; // icy-bitrate or bitrate from metadata
case Audio::evt_icyurl: Serial.printf("icy URL: .... %s\n", m.msg); break;
case Audio::evt_id3data: Serial.printf("ID3 data: ... %s\n", m.msg); break; // id3-data or metadata
case Audio::evt_lasthost: Serial.printf("last URL: ... %s\n", m.msg); break;
case Audio::evt_name: Serial.printf("station name: %s\n", m.msg); break; // station name or icy-name
case Audio::evt_streamtitle: Serial.printf("stream title: %s\n", m.msg); break;
case Audio::evt_icylogo: Serial.printf("icy logo: ... %s\n", m.msg); break;
case Audio::evt_icydescription: Serial.printf("icy descr: .. %s\n", m.msg); break;
case Audio::evt_image: for(int i = 0; i < m.vec.size(); i += 2){
Serial.printf("cover image: segment %02i, pos %07lu, len %05lu\n", i / 2, m.vec[i], m.vec[i + 1]);} break; // APIC
case Audio::evt_lyrics: Serial.printf("sync lyrics: %s\n", m.msg); break;
case Audio::evt_log : Serial.printf("audio_logs: %s\n", m.msg); break;
default: Serial.printf("message:..... %s\n", m.msg); break;
}
}
````
<br>
|Codec | ESP32 |ESP32-S3 or ESP32-P4 | |
|------------|-------------|-----------------------------|--------------------------|
| mp3 | y | y | |
| aac | y | y | |
| aacp | y (mono) | y (+SBR, +Parametric Stereo)| |
| wav | y | y | |
| flac | y | y |blocksize max 24576 bytes |
| vorbis | y | y | <=196Kbit/s |
| m4a | y | y | |
| opus | y | y | |
<br>
***
Wiring
![schematic](https://github.com/user-attachments/assets/77ce30d2-acb1-4b5d-a9d6-4f1e3d56e385)
***
Impulse diagram
![Impulse diagram](https://github.com/schreibfaul1/ESP32-audioI2S/blob/master/additional_info/Impulsdiagramm.jpg)
***
Yellobyte has developed an all-in-one board. It includes an ESP32-S3 N8R2, 2x MAX98357 and an SD card adapter.
Documentation, circuit diagrams and examples can be found here: https://github.com/yellobyte/ESP32-DevBoards-Getting-Started
![image](https://github.com/user-attachments/assets/4002d09e-8e76-4e08-9265-188fed7628d3)

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 309 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 337 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 381 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

View File

@@ -0,0 +1,5 @@
#EXTM3U
#EXTINF:18,Bjarne Liller - Olsen Banden (Titelmusik der Olsenbande) - Olsen-Banden.mp3
https://raw.githubusercontent.com/schreibfaul1/ESP32-audioI2S/master/additional_info/Testfiles/Olsen-Banden.mp3
#EXTINF:10,Santiano-Wellermann - Santiano-Wellerman.flac
https://raw.githubusercontent.com/schreibfaul1/ESP32-audioI2S/master/additional_info/Testfiles/Santiano-Wellerman.flac

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,589 @@
// based on helix aac decoder
#pragma once
//#pragma GCC optimize ("O3")
//#pragma GCC diagnostic ignored "-Wnarrowing"
#include "Arduino.h"
#define AAC_ENABLE_MPEG4
#if (defined CONFIG_IDF_TARGET_ESP32S3 && defined BOARD_HAS_PSRAM)
#define AAC_ENABLE_SBR // needs additional 60KB DRAM,
#endif
#define ASSERT(x) /* do nothing */
#ifndef MAX
#define MAX(a,b) std::max(a,b)
#endif
#ifndef MIN
#define MIN(a,b) std::min(a,b)
#endif
/* AAC file format */
enum {
AAC_FF_Unknown = 0, /* should be 0 on init */
AAC_FF_ADTS = 1,
AAC_FF_ADIF = 2,
AAC_FF_RAW = 3
};
/* syntactic element type */
enum {
AAC_ID_INVALID = -1,
AAC_ID_SCE = 0,
AAC_ID_CPE = 1,
AAC_ID_CCE = 2,
AAC_ID_LFE = 3,
AAC_ID_DSE = 4,
AAC_ID_PCE = 5,
AAC_ID_FIL = 6,
AAC_ID_END = 7
};
enum {
ERR_AAC_NONE = 0,
ERR_AAC_INDATA_UNDERFLOW = -1,
ERR_AAC_NULL_POINTER = -2,
ERR_AAC_INVALID_ADTS_HEADER = -3,
ERR_AAC_INVALID_ADIF_HEADER = -4,
ERR_AAC_INVALID_FRAME = -5,
ERR_AAC_MPEG4_UNSUPPORTED = -6,
ERR_AAC_CHANNEL_MAP = -7,
ERR_AAC_SYNTAX_ELEMENT = -8,
ERR_AAC_DEQUANT = -9,
ERR_AAC_STEREO_PROCESS = -10,
ERR_AAC_PNS = -11,
ERR_AAC_SHORT_BLOCK_DEINT = -12,
ERR_AAC_TNS = -13,
ERR_AAC_IMDCT = -14,
ERR_AAC_NCHANS_TOO_HIGH = -15,
ERR_AAC_SBR_INIT = -16,
ERR_AAC_SBR_BITSTREAM = -17,
ERR_AAC_SBR_DATA = -18,
ERR_AAC_SBR_PCM_FORMAT = -19,
ERR_AAC_SBR_NCHANS_TOO_HIGH = -20,
ERR_AAC_SBR_SINGLERATE_UNSUPPORTED = -21,
ERR_AAC_RAWBLOCK_PARAMS = -22,
ERR_AAC_UNKNOWN = -9999
};
enum {
SBR_GRID_FIXFIX = 0,
SBR_GRID_FIXVAR = 1,
SBR_GRID_VARFIX = 2,
SBR_GRID_VARVAR = 3
};
enum {
HuffTabSBR_tEnv15 = 0,
HuffTabSBR_fEnv15 = 1,
HuffTabSBR_tEnv15b = 2,
HuffTabSBR_fEnv15b = 3,
HuffTabSBR_tEnv30 = 4,
HuffTabSBR_fEnv30 = 5,
HuffTabSBR_tEnv30b = 6,
HuffTabSBR_fEnv30b = 7,
HuffTabSBR_tNoise30 = 8,
HuffTabSBR_fNoise30 = 5,
HuffTabSBR_tNoise30b = 9,
HuffTabSBR_fNoise30b = 7
};
typedef struct _AACDecInfo_t {
/* raw decoded data, before rounding to 16-bit PCM (for postprocessing such as SBR) */
void *rawSampleBuf[2];
int32_t rawSampleBytes;
int32_t rawSampleFBits;
/* fill data (can be used for processing SBR or other extensions) */
uint8_t *fillBuf;
int32_t fillCount;
int32_t fillExtType;
int32_t prevBlockID; /* block information */
int32_t currBlockID;
int32_t currInstTag;
int32_t sbDeinterleaveReqd[2]; // [MAX_NCHANS_ELEM]
int32_t adtsBlocksLeft;
int32_t bitRate; /* user-accessible info */
int32_t nChans;
int32_t sampRate;
float compressionRatio;
int32_t id; /* 0: MPEG-4, 1: MPEG2 */
int32_t profile; /* 0: Main profile, 1: LowComplexity (LC), 2: ScalableSamplingRate (SSR), 3: reserved */
int32_t format;
int32_t sbrEnabled;
int32_t tnsUsed;
int32_t pnsUsed;
int32_t frameCount;
} AACDecInfo_t;
typedef struct _aac_BitStreamInfo_t {
uint8_t *bytePtr;
uint32_t iCache;
int32_t cachedBits;
int32_t nBytes;
} aac_BitStreamInfo_t;
typedef union _U64 {
int64_t w64;
struct {
uint32_t lo32;
int32_t hi32;
} r;
} U64;
typedef struct _AACFrameInfo_t {
int32_t bitRate;
int32_t nChans;
int32_t sampRateCore;
int32_t sampRateOut;
int32_t bitsPerSample;
int32_t outputSamps;
int32_t profile;
int32_t tnsUsed;
int32_t pnsUsed;
} AACFrameInfo_t;
typedef struct _HuffInfo_t {
int32_t maxBits; /* number of bits in longest codeword */
uint8_t count[20]; /* count[MAX_HUFF_BITS] = number of codes with length i+1 bits */
int32_t offset; /* offset into symbol table */
} HuffInfo_t;
typedef struct _PulseInfo_t {
uint8_t pulseDataPresent;
uint8_t numPulse;
uint8_t startSFB;
uint8_t offset[4]; // [MAX_PULSES]
uint8_t amp[4]; // [MAX_PULSES]
} PulseInfo_t;
typedef struct _TNSInfo_t {
uint8_t tnsDataPresent;
uint8_t numFilt[8]; // [MAX_TNS_FILTERS] max 1 filter each for 8 short windows, or 3 filters for 1 long window
uint8_t coefRes[8]; // [MAX_TNS_FILTERS]
uint8_t length[8]; // [MAX_TNS_FILTERS]
uint8_t order[8]; // [MAX_TNS_FILTERS]
uint8_t dir[8]; // [MAX_TNS_FILTERS]
int8_t coef[60]; // [MAX_TNS_COEFS] max 3 filters * 20 coefs for 1 long window,
// or 1 filter * 7 coefs for each of 8 short windows
} TNSInfo_t;
typedef struct _GainControlInfo_t {
uint8_t gainControlDataPresent;
uint8_t maxBand;
uint8_t adjNum[3][8]; // [MAX_GAIN_BANDS][MAX_GAIN_WIN]
uint8_t alevCode[3][8][7]; // [MAX_GAIN_BANDS][MAX_GAIN_WIN][MAX_GAIN_ADJUST]
uint8_t alocCode[3][8][7]; // [MAX_GAIN_BANDS][MAX_GAIN_WIN][MAX_GAIN_ADJUST]
} GainControlInfo_t;
typedef struct _ICSInfo_t {
uint8_t icsResBit;
uint8_t winSequence;
uint8_t winShape;
uint8_t maxSFB;
uint8_t sfGroup;
uint8_t predictorDataPresent;
uint8_t predictorReset;
uint8_t predictorResetGroupNum;
uint8_t predictionUsed[41]; // [MAX_PRED_SFB]
uint8_t numWinGroup;
uint8_t winGroupLen[8]; // [MAX_WIN_GROUPS]
} ICSInfo_t;
typedef struct _ADTSHeader_t {
/* fixed */
uint8_t id; /* MPEG bit - should be 1 */
uint8_t layer; /* MPEG layer - should be 0 */
uint8_t protectBit; /* 0 = CRC word follows, 1 = no CRC word */
uint8_t profile; /* 0 = main, 1 = LC, 2 = SSR, 3 = reserved */
uint8_t sampRateIdx; /* sample rate index range = [0, 11] */
uint8_t privateBit; /* ignore */
uint8_t channelConfig; /* 0 = implicit, >0 = use default table */
uint8_t origCopy; /* 0 = copy, 1 = original */
uint8_t home; /* ignore */
/* variable */
uint8_t copyBit; /* 1 bit of the 72-bit copyright ID (transmitted as 1 bit per frame) */
uint8_t copyStart; /* 1 = this bit starts the 72-bit ID, 0 = it does not */
int32_t frameLength; /* length of frame */
int32_t bufferFull; /* number of 32-bit words left in enc buffer, 0x7FF = VBR */
uint8_t numRawDataBlocks; /* number of raw data blocks in frame */
/* CRC */
int32_t crcCheckWord; /* 16-bit CRC check word (present if protectBit == 0) */
} ADTSHeader_t;
typedef struct _ADIFHeader_t {
uint8_t copyBit; /* 0 = no copyright ID, 1 = 72-bit copyright ID follows immediately */
uint8_t origCopy; /* 0 = copy, 1 = original */
uint8_t home; /* ignore */
uint8_t bsType; /* bitstream type: 0 = CBR, 1 = VBR */
int32_t bitRate; /* bitRate: CBR = bits/sec, VBR = peak bits/frame, 0 = unknown */
uint8_t numPCE; /* number of program config elements (max = 16) */
int32_t bufferFull; /* bits left in bit reservoir */
uint8_t copyID[9]; /* [ADIF_COPYID_SIZE] optional 72-bit copyright ID */
} ADIFHeader_t;
/* sizeof(ProgConfigElement_t) = 82 bytes (if KEEP_PCE_COMMENTS not defined) */
typedef struct _ProgConfigElement_t {
uint8_t elemInstTag; /* element instance tag */
uint8_t profile; /* 0 = main, 1 = LC, 2 = SSR, 3 = reserved */
uint8_t sampRateIdx; /* sample rate index range = [0, 11] */
uint8_t numFCE; /* number of front channel elements (max = 15) */
uint8_t numSCE; /* number of side channel elements (max = 15) */
uint8_t numBCE; /* number of back channel elements (max = 15) */
uint8_t numLCE; /* number of LFE channel elements (max = 3) */
uint8_t numADE; /* number of associated data elements (max = 7) */
uint8_t numCCE; /* number of valid channel coupling elements (max = 15) */
uint8_t monoMixdown; /* mono mixdown: bit 4 = present flag, bits 3-0 = element number */
uint8_t stereoMixdown; /* stereo mixdown: bit 4 = present flag, bits 3-0 = element number */
uint8_t matrixMixdown; /* bit 4 = present flag, bit 3 = unused,bits 2-1 = index, bit 0 = pseudo-surround enable */
uint8_t fce[15]; /* [MAX_NUM_FCE] front element channel pair: bit 4 = SCE/CPE flag, bits 3-0 = inst tag */
uint8_t sce[15]; /* [MAX_NUM_SCE] side element channel pair: bit 4 = SCE/CPE flag, bits 3-0 = inst tag */
uint8_t bce[15]; /* [MAX_NUM_BCE] back element channel pair: bit 4 = SCE/CPE flag, bits 3-0 = inst tag */
uint8_t lce[3]; /* [MAX_NUM_LCE] instance tag for LFE elements */
uint8_t ade[7]; /* [MAX_NUM_ADE] instance tag for ADE elements */
uint8_t cce[15]; /* [MAX_NUM_BCE] channel coupling elements: bit 4 = switching flag, bits 3-0 = inst tag */
} ProgConfigElement_t;
typedef struct _SBRHeader {
int32_t count;
uint8_t ampRes;
uint8_t startFreq;
uint8_t stopFreq;
uint8_t crossOverBand;
uint8_t resBitsHdr;
uint8_t hdrExtra1;
uint8_t hdrExtra2;
uint8_t freqScale;
uint8_t alterScale;
uint8_t noiseBands;
uint8_t limiterBands;
uint8_t limiterGains;
uint8_t interpFreq;
uint8_t smoothMode;
} SBRHeader;
/* need one SBRGrid per channel, updated every frame */
typedef struct _SBRGrid {
uint8_t frameClass;
uint8_t ampResFrame;
uint8_t pointer;
uint8_t numEnv; /* L_E */
uint8_t envTimeBorder[5 + 1]; // [MAX_NUM_ENV+1] /* t_E */
uint8_t freqRes[5]; // [MAX_NUM_ENV]/* r */
uint8_t numNoiseFloors; /* L_Q */
uint8_t noiseTimeBorder[2 + 1]; // [MAX_NUM_NOISE_FLOORS+1] /* t_Q */
uint8_t numEnvPrev;
uint8_t numNoiseFloorsPrev;
uint8_t freqResPrev;
} SBRGrid;
/* need one SBRFreq per element (SCE/CPE/LFE), updated only on header reset */
typedef struct _SBRFreq {
int32_t kStart; /* k_x */
int32_t nMaster;
int32_t nHigh;
int32_t nLow;
int32_t nLimiter; /* N_l */
int32_t numQMFBands; /* M */
int32_t numNoiseFloorBands; /* Nq */
int32_t kStartPrev;
int32_t numQMFBandsPrev;
uint8_t freqMaster[48 + 1]; // [MAX_QMF_BANDS + 1] /* not necessary to save this after derived tables are generated */
uint8_t freqHigh[48 + 1]; // [MAX_QMF_BANDS + 1]
uint8_t freqLow[48 / 2 + 1]; // [MAX_QMF_BANDS / 2 + 1] /* nLow = nHigh - (nHigh >> 1) */
uint8_t freqNoise[5 + 1]; // [MAX_NUM_NOISE_FLOOR_BANDS+1]
uint8_t freqLimiter[48 / 2 + 5];// [MAX_QMF_BANDS / 2 + MAX_NUM_PATCHES] /* max (intermediate) size = nLow + numPatches - 1 */
uint8_t numPatches;
uint8_t patchNumSubbands[5 + 1]; // [MAX_NUM_PATCHES + 1]
uint8_t patchStartSubband[5 + 1]; // [MAX_NUM_PATCHES + 1]
} SBRFreq;
typedef struct _SBRChan {
int32_t reset;
uint8_t deltaFlagEnv[5]; // [MAX_NUM_ENV]
uint8_t deltaFlagNoise[2]; // [MAX_NUM_NOISE_FLOORS]
int8_t envDataQuant[5][48]; // [MAX_NUM_ENV][MAX_QMF_BANDS] /* range = [0, 127] */
int8_t noiseDataQuant[2][5]; // [MAX_NUM_NOISE_FLOORS][MAX_NUM_NOISE_FLOOR_BANDS]
uint8_t invfMode[2][5]; // [2][MAX_NUM_NOISE_FLOOR_BANDS] /* invfMode[0/1][band] = prev/curr */
int32_t chirpFact[5]; // [MAX_NUM_NOISE_FLOOR_BANDS] /* bwArray */
uint8_t addHarmonicFlag[2]; /* addHarmonicFlag[0/1] = prev/curr */
uint8_t addHarmonic[2][64]; /* addHarmonic[0/1][band] = prev/curr */
int32_t gbMask[2]; /* gbMask[0/1] = XBuf[0-31]/XBuf[32-39] */
int8_t laPrev;
int32_t noiseTabIndex;
int32_t sinIndex;
int32_t gainNoiseIndex;
int32_t gTemp[5][48]; // [MAX_NUM_SMOOTH_COEFS][MAX_QMF_BANDS]
int32_t qTemp[5][48]; // [MAX_NUM_SMOOTH_COEFS][MAX_QMF_BANDS]
} SBRChan;
/* state info struct for baseline (MPEG-4 LC) decoding */
typedef struct _PSInfoBase_t {
int32_t dataCount;
uint8_t dataBuf[510]; // [DATA_BUF_SIZE]
int32_t fillCount;
uint8_t fillBuf[269]; //[FILL_BUF_SIZE]
/* state information which is the same throughout whole frame */
int32_t nChans;
int32_t useImpChanMap;
int32_t sampRateIdx;
/* state information which can be overwritten by subsequent elements within frame */
ICSInfo_t icsInfo[2]; // [MAX_NCHANS_ELEM]
int32_t commonWin;
int16_t scaleFactors[2][15*8]; // [MAX_NCHANS_ELEM][MAX_SF_BANDS]
uint8_t sfbCodeBook[2][15*8]; // [MAX_NCHANS_ELEM][MAX_SF_BANDS]
int32_t msMaskPresent;
uint8_t msMaskBits[(15 * 8 + 7) >> 3]; // [MAX_MS_MASK_BYTES]
int32_t pnsUsed[2]; // [MAX_NCHANS_ELEM]
int32_t pnsLastVal;
int32_t intensityUsed[2]; // [MAX_NCHANS_ELEM]
// PulseInfo_t pulseInfo[2]; // [MAX_NCHANS_ELEM]
TNSInfo_t tnsInfo[2]; // [MAX_NCHANS_ELEM]
int32_t tnsLPCBuf[20]; // [MAX_TNS_ORDER]
int32_t tnsWorkBuf[20]; //[MAX_TNS_ORDER]
GainControlInfo_t gainControlInfo[2]; // [MAX_NCHANS_ELEM]
int32_t gbCurrent[2]; // [MAX_NCHANS_ELEM]
int32_t coef[2][1024]; // [MAX_NCHANS_ELEM][AAC_MAX_NSAMPS]
#ifdef AAC_ENABLE_SBR
int32_t sbrWorkBuf[2][1024]; // [MAX_NCHANS_ELEM][AAC_MAX_NSAMPS];
#endif
/* state information which must be saved for each element and used in next frame */
int32_t overlap[2][1024]; // [AAC_MAX_NCHANS][AAC_MAX_NSAMPS]
int32_t prevWinShape[2]; // [AAC_MAX_NCHANS]
} PSInfoBase_t;
typedef struct _PSInfoSBR {
/* save for entire file */
int32_t frameCount;
int32_t sampRateIdx;
/* state info that must be saved for each channel */
SBRHeader sbrHdr[2];
SBRGrid sbrGrid[2];
SBRFreq sbrFreq[2];
SBRChan sbrChan[2];
/* temp variables, no need to save between blocks */
uint8_t dataExtra;
uint8_t resBitsData;
uint8_t extendedDataPresent;
int32_t extendedDataSize;
int8_t envDataDequantScale[2][5]; // [MAX_NCHANS_ELEM][MAX_NUM_ENV
int32_t envDataDequant[2][5][48]; // [MAX_NCHANS_ELEM][MAX_NUM_ENV][MAX_QMF_BANDS
int32_t noiseDataDequant[2][2][5]; // [MAX_NCHANS_ELEM][MAX_NUM_NOISE_FLOORS][MAX_NUM_NOISE_FLOOR_BANDS]
int32_t eCurr[48]; // [MAX_QMF_BANDS]
uint8_t eCurrExp[48]; // [MAX_QMF_BANDS]
uint8_t eCurrExpMax;
int8_t la;
int32_t crcCheckWord;
int32_t couplingFlag;
int32_t envBand;
int32_t eOMGainMax;
int32_t gainMax;
int32_t gainMaxFBits;
int32_t noiseFloorBand;
int32_t qp1Inv;
int32_t qqp1Inv;
int32_t sMapped;
int32_t sBand;
int32_t highBand;
int32_t sumEOrigMapped;
int32_t sumECurrGLim;
int32_t sumSM;
int32_t sumQM;
int32_t gLimBoost[48];
int32_t qmLimBoost[48];
int32_t smBoost[48];
int32_t smBuf[48];
int32_t qmLimBuf[48];
int32_t gLimBuf[48];
int32_t gLimFbits[48];
int32_t gFiltLast[48];
int32_t qFiltLast[48];
/* large buffers */
int32_t delayIdxQMFA[2]; // [AAC_MAX_NCHANS]
int32_t delayQMFA[2][10 * 32]; // [AAC_MAX_NCHANS][DELAY_SAMPS_QMFA]
int32_t delayIdxQMFS[2]; // [AAC_MAX_NCHANS]
int32_t delayQMFS[2][10 * 128]; // [AAC_MAX_NCHANS][DELAY_SAMPS_QMFS]
int32_t XBufDelay[2][8][64][2]; // [AAC_MAX_NCHANS][HF_GEN][64][2]
int32_t XBuf[32+8][64][2];
} PSInfoSBR_t;
bool AACDecoder_AllocateBuffers(void);
int32_t AACFlushCodec();
void AACDecoder_FreeBuffers(void);
bool AACDecoder_IsInit(void);
int32_t AACFindSyncWord(uint8_t *buf, int32_t nBytes);
int32_t AACSetRawBlockParams(int32_t nChans, int32_t sampRateCore, int32_t profile, int32_t copyLast = 0);
int32_t AACDecode(uint8_t *inbuf, int32_t *bytesLeft, int16_t *outbuf);
int32_t AACGetSampRate();
int32_t AACGetChannels();
int32_t AACGetID(); // 0-MPEG4, 1-MPEG2
uint8_t AACGetProfile(); // 0-Main, 1-LC, 2-SSR, 3-reserved
uint8_t AACGetFormat(); // 0-unknown 1-ADTS 2-ADIF, 3-RAW
int32_t AACGetBitsPerSample();
int32_t AACGetBitrate();
int32_t AACGetOutputSamps();
int32_t AACGetBitrate();
void DecodeLPCCoefs(int32_t order, int32_t res, int8_t *filtCoef, int32_t *a, int32_t *b);
int32_t FilterRegion(int32_t size, int32_t dir, int32_t order, int32_t *audioCoef, int32_t *a, int32_t *hist);
int32_t TNSFilter(int32_t ch);
int32_t DecodeSingleChannelElement();
int32_t DecodeChannelPairElement();
int32_t DecodeLFEChannelElement();
int32_t DecodeDataStreamElement();
int32_t DecodeProgramConfigElement(uint8_t idx);
int32_t DecodeFillElement();
int32_t DecodeNextElement(uint8_t **buf, int32_t *bitOffset, int32_t *bitsAvail);
void PreMultiply(int32_t tabidx, int32_t *zbuf1);
void PostMultiply(int32_t tabidx, int32_t *fft1);
void PreMultiplyRescale(int32_t tabidx, int32_t *zbuf1, int32_t es);
void PostMultiplyRescale(int32_t tabidx, int32_t *fft1, int32_t es);
void DCT4(int32_t tabidx, int32_t *coef, int32_t gb);
void BitReverse(int32_t *inout, int32_t tabidx);
void R4FirstPass(int32_t *x, int32_t bg);
void R8FirstPass(int32_t *x, int32_t bg);
void R4Core(int32_t *x, int32_t bg, int32_t gp, int32_t *wtab);
void R4FFT(int32_t tabidx, int32_t *x);
void UnpackZeros(int32_t nVals, int32_t *coef);
void UnpackQuads(int32_t cb, int32_t nVals, int32_t *coef);
void UnpackPairsNoEsc(int32_t cb, int32_t nVals, int32_t *coef);
void UnpackPairsEsc(int32_t cb, int32_t nVals, int32_t *coef);
void DecodeSpectrumLong(int32_t ch);
void DecodeSpectrumShort(int32_t ch);
void DecWindowOverlap(int32_t *buf0, int32_t *over0, int16_t *pcm0, int32_t nChans, int32_t winTypeCurr, int32_t winTypePrev);
void DecWindowOverlapLongStart(int32_t *buf0, int32_t *over0, int16_t *pcm0, int32_t nChans, int32_t winTypeCurr, int32_t winTypePrev);
void DecWindowOverlapLongStop(int32_t *buf0, int32_t *over0, int16_t *pcm0, int32_t nChans, int32_t winTypeCurr, int32_t winTypePrev);
void DecWindowOverlapShort(int32_t *buf0, int32_t *over0, int16_t *pcm0, int32_t nChans, int32_t winTypeCurr, int32_t winTypePrev);
int32_t IMDCT(int32_t ch, int32_t chOut, int16_t *outbuf);
void DecodeICSInfo(ICSInfo_t *icsInfo, int32_t sampRateIdx);
void DecodeSectionData(int32_t winSequence, int32_t numWinGrp, int32_t maxSFB, uint8_t *sfbCodeBook);
int32_t DecodeOneScaleFactor();
void DecodeScaleFactors(int32_t numWinGrp, int32_t maxSFB, int32_t globalGain, uint8_t *sfbCodeBook, int16_t *scaleFactors);
void DecodePulseInfo(uint8_t ch);
void DecodeTNSInfo(int32_t winSequence, TNSInfo_t *ti, int8_t *tnsCoef);
void DecodeGainControlInfo(int32_t winSequence, GainControlInfo_t *gi);
void DecodeICS(int32_t ch);
int32_t DecodeNoiselessData(uint8_t **buf, int32_t *bitOffset, int32_t *bitsAvail, int32_t ch);
int32_t UnpackADTSHeader(uint8_t **buf, int32_t *bitOffset, int32_t *bitsAvail);
int32_t GetADTSChannelMapping(uint8_t *buf, int32_t bitOffset, int32_t bitsAvail);
int32_t GetNumChannelsADIF(int32_t nPCE);
int32_t GetSampleRateIdxADIF(int32_t nPCE);
int32_t UnpackADIFHeader(uint8_t **buf, int32_t *bitOffset, int32_t *bitsAvail);
int32_t SetRawBlockParams(int32_t copyLast, int32_t nChans, int32_t sampRate, int32_t profile);
int32_t PrepareRawBlock();
int32_t DequantBlock(int32_t *inbuf, int32_t nSamps, int32_t scale);
int32_t AACDequantize(int32_t ch);
int32_t DeinterleaveShortBlocks(int32_t ch);
uint32_t Get32BitVal(uint32_t *last);
int32_t InvRootR(int32_t r);
int32_t ScaleNoiseVector(int32_t *coef, int32_t nVals, int32_t sf);
void GenerateNoiseVector(int32_t *coef, int32_t *last, int32_t nVals);
void CopyNoiseVector(int32_t *coefL, int32_t *coefR, int32_t nVals);
int32_t PNS(int32_t ch);
int32_t GetSampRateIdx(int32_t sampRate);
void StereoProcessGroup(int32_t *coefL, int32_t *coefR, const uint16_t *sfbTab, int32_t msMaskPres, uint8_t *msMaskPtr,
int32_t msMaskOffset, int32_t maxSFB, uint8_t *cbRight, int16_t *sfRight, int32_t *gbCurrent);
int32_t StereoProcess();
int32_t RatioPowInv(int32_t a, int32_t b, int32_t c);
int32_t SqrtFix(int32_t q, int32_t fBitsIn, int32_t *fBitsOut);
int32_t InvRNormalized(int32_t r);
void BitReverse32(int32_t *inout);
void R8FirstPass32(int32_t *r0);
void R4Core32(int32_t *r0);
void FFT32C(int32_t *x);
void CVKernel1(int32_t *XBuf, int32_t *accBuf);
void CVKernel2(int32_t *XBuf, int32_t *accBuf);
void SetBitstreamPointer(int32_t nBytes, uint8_t *buf);
inline void RefillBitstreamCache();
uint32_t GetBits(int32_t nBits);
uint32_t GetBitsNoAdvance(int32_t nBits);
void AdvanceBitstream(int32_t nBits);
int32_t CalcBitsUsed(uint8_t *startBuf, int32_t startOffset);
void ByteAlignBitstream();
// SBR
void InitSBRState();
int32_t DecodeSBRBitstream(int32_t chBase);
int32_t DecodeSBRData(int32_t chBase, int16_t *outbuf);
int32_t FlushCodecSBR();
void BubbleSort(uint8_t *v, int32_t nItems);
uint8_t VMin(uint8_t *v, int32_t nItems);
uint8_t VMax(uint8_t *v, int32_t nItems);
int32_t CalcFreqMasterScaleZero(uint8_t *freqMaster, int32_t alterScale, int32_t k0, int32_t k2);
int32_t CalcFreqMaster(uint8_t *freqMaster, int32_t freqScale, int32_t alterScale, int32_t k0, int32_t k2);
int32_t CalcFreqHigh(uint8_t *freqHigh, uint8_t *freqMaster, int32_t nMaster, int32_t crossOverBand);
int32_t CalcFreqLow(uint8_t *freqLow, uint8_t *freqHigh, int32_t nHigh);
int32_t CalcFreqNoise(uint8_t *freqNoise, uint8_t *freqLow, int32_t nLow, int32_t kStart, int32_t k2, int32_t noiseBands);
int32_t BuildPatches(uint8_t *patchNumSubbands, uint8_t *patchStartSubband, uint8_t *freqMaster, int32_t nMaster, int32_t k0,
int32_t kStart, int32_t numQMFBands, int32_t sampRateIdx);
int32_t FindFreq(uint8_t *freq, int32_t nFreq, uint8_t val);
void RemoveFreq(uint8_t *freq, int32_t nFreq, int32_t removeIdx);
int32_t CalcFreqLimiter(uint8_t *freqLimiter, uint8_t *patchNumSubbands, uint8_t *freqLow, int32_t nLow, int32_t kStart,
int32_t limiterBands, int32_t numPatches);
int32_t CalcFreqTables(SBRHeader *sbrHdr, SBRFreq *sbrFreq, int32_t sampRateIdx);
void EstimateEnvelope(SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, int32_t env);
int32_t GetSMapped(SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int32_t env, int32_t band, int32_t la);
void CalcMaxGain(SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, int32_t ch, int32_t env, int32_t lim, int32_t fbitsDQ);
void CalcNoiseDivFactors(int32_t q, int32_t *qp1Inv, int32_t *qqp1Inv);
void CalcComponentGains(SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int32_t ch, int32_t env, int32_t lim, int32_t fbitsDQ);
void ApplyBoost(SBRFreq *sbrFreq, int32_t lim, int32_t fbitsDQ);
void CalcGain(SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int32_t ch, int32_t env);
void MapHF(SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int32_t env, int32_t hfReset);
void AdjustHighFreq(SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int32_t ch);
int32_t CalcCovariance1(int32_t *XBuf, int32_t *p01reN, int32_t *p01imN, int32_t *p12reN, int32_t *p12imN, int32_t *p11reN, int32_t *p22reN);
int32_t CalcCovariance2(int32_t *XBuf, int32_t *p02reN, int32_t *p02imN);
void CalcLPCoefs(int32_t *XBuf, int32_t *a0re, int32_t *a0im, int32_t *a1re, int32_t *a1im, int32_t gb);
void GenerateHighFreq(SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int32_t ch);
int32_t DecodeHuffmanScalar(const int16_t *huffTab, const HuffInfo_t *huffTabInfo, uint32_t bitBuf, int32_t *val);
int32_t DecodeOneSymbol(int32_t huffTabIndex);
int32_t DequantizeEnvelope(int32_t nBands, int32_t ampRes, int8_t *envQuant, int32_t *envDequant);
void DequantizeNoise(int32_t nBands, int8_t *noiseQuant, int32_t *noiseDequant);
void DecodeSBREnvelope(SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int32_t ch);
void DecodeSBRNoise(SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int32_t ch);
void UncoupleSBREnvelope(SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChanR);
void UncoupleSBRNoise(SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChanR);
void DecWindowOverlapNoClip(int32_t *buf0, int32_t *over0, int32_t *out0, int32_t winTypeCurr, int32_t winTypePrev);
void DecWindowOverlapLongStartNoClip(int32_t *buf0, int32_t *over0, int32_t *out0, int32_t winTypeCurr, int32_t winTypePrev);
void DecWindowOverlapLongStopNoClip(int32_t *buf0, int32_t *over0, int32_t *out0, int32_t winTypeCurr, int32_t winTypePrev);
void DecWindowOverlapShortNoClip(int32_t *buf0, int32_t *over0, int32_t *out0, int32_t winTypeCurr, int32_t winTypePrev);
void PreMultiply64(int32_t *zbuf1);
void PostMultiply64(int32_t *fft1, int32_t nSampsOut);
void QMFAnalysisConv(int32_t *cTab, int32_t *delay, int32_t dIdx, int32_t *uBuf);
int32_t QMFAnalysis(int32_t *inbuf, int32_t *delay, int32_t *XBuf, int32_t fBitsIn, int32_t *delayIdx, int32_t qmfaBands);
void QMFSynthesisConv(int32_t *cPtr, int32_t *delay, int32_t dIdx, int16_t *outbuf, int32_t nChans);
void QMFSynthesis(int32_t *inbuf, int32_t *delay, int32_t *delayIdx, int32_t qmfsBands, int16_t *outbuf, int32_t nChans);
int32_t UnpackSBRHeader(SBRHeader *sbrHdr);
void UnpackSBRGrid(SBRHeader *sbrHdr, SBRGrid *sbrGrid);
void UnpackDeltaTimeFreq(int32_t numEnv, uint8_t *deltaFlagEnv, int32_t numNoiseFloors, uint8_t *deltaFlagNoise);
void UnpackInverseFilterMode(int32_t numNoiseFloorBands, uint8_t *mode);
void UnpackSinusoids(int32_t nHigh, int32_t addHarmonicFlag, uint8_t *addHarmonic);
void CopyCouplingGrid(SBRGrid *sbrGridLeft, SBRGrid *sbrGridRight);
void CopyCouplingInverseFilterMode(int32_t numNoiseFloorBands, uint8_t *modeLeft, uint8_t *modeRight);
void UnpackSBRSingleChannel(int32_t chBase);
void UnpackSBRChannelPair(int32_t chBase);
inline uint8_t AACGetSBR(){return 0;}
inline uint8_t AACGetParametricStereo(){return 0;}
const char* AACGetErrorMessage(uint8_t errorCode);

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,606 @@
// based om helix mp3 decoder
#pragma once
#include "Arduino.h"
#include "../psram_unique_ptr.hpp"
#include "assert.h"
extern __attribute__((weak)) void audio_info(const char*);
static const uint8_t m_HUFF_PAIRTABS =32;
static const uint8_t m_BLOCK_SIZE =18;
static const uint8_t m_NBANDS =32;
static const uint8_t m_MAX_REORDER_SAMPS =(192-126)*3; // largest critical band for short blocks (see sfBandTable)
static const uint16_t m_VBUF_LENGTH =17*2* m_NBANDS; // for double-sized vbuf FIFO
static const uint8_t m_MAX_SCFBD =4; // max scalefactor bands per channel
static const uint16_t m_MAINBUF_SIZE =1940;
static const uint8_t m_MAX_NGRAN =2; // max granules
static const uint8_t m_MAX_NCHAN =2; // max channels
static const uint16_t m_MAX_NSAMP =576; // max samples per channel, per granule
enum {
MP3_NONE = 0,
MP3_ERR = -1,
MP3_STOP = -100,
};
typedef struct MP3FrameInfo {
int32_t bitrate;
int32_t nChans;
int32_t samprate;
int32_t bitsPerSample;
int32_t outputSamps;
int32_t layer;
int32_t version;
} MP3FrameInfo_t;
typedef struct SFBandTable {
int32_t l[23];
int32_t s[14];
} SFBandTable_t;
typedef struct BitStreamInfo {
uint8_t *bytePtr;
uint32_t iCache;
int32_t cachedBits;
int32_t nBytes;
} BitStreamInfo_t;
typedef enum { /* map these to the corresponding 2-bit values in the frame header */
Stereo = 0x00, /* two independent channels, but L and R frames might have different # of bits */
Joint = 0x01, /* coupled channels - layer III: mix of M-S and intensity, Layers I/II: intensity and direct coding only */
Dual = 0x02, /* two independent channels, L and R always have exactly 1/2 the total bitrate */
Mono = 0x03 /* one channel */
} StereoMode_t;
typedef enum { /* map to 0,1,2 to make table indexing easier */
MPEG1 = 0,
MPEG2 = 1,
MPEG25 = 2
} MPEGVersion_t;
typedef struct FrameHeader {
int32_t layer; /* layer index (1, 2, or 3) */
int32_t crc; /* CRC flag: 0 = disabled, 1 = enabled */
int32_t brIdx; /* bitrate index (0 - 15) */
int32_t srIdx; /* sample rate index (0 - 2) */
int32_t paddingBit; /* padding flag: 0 = no padding, 1 = single pad byte */
int32_t privateBit; /* unused */
int32_t modeExt; /* used to decipher joint stereo mode */
int32_t copyFlag; /* copyright flag: 0 = no, 1 = yes */
int32_t origFlag; /* original flag: 0 = copy, 1 = original */
int32_t emphasis; /* deemphasis mode */
int32_t CRCWord; /* CRC word (16 bits, 0 if crc not enabled) */
} FrameHeader_t;
typedef struct SideInfoSub {
int32_t part23Length; /* number of bits in main data */
int32_t nBigvals; /* 2x this = first set of Huffman cw's (maximum amplitude can be > 1) */
int32_t globalGain; /* overall gain for dequantizer */
int32_t sfCompress; /* unpacked to figure out number of bits in scale factors */
int32_t winSwitchFlag; /* window switching flag */
int32_t blockType; /* block type */
int32_t mixedBlock; /* 0 = regular block (all short or long), 1 = mixed block */
int32_t tableSelect[3]; /* index of Huffman tables for the big values regions */
int32_t subBlockGain[3]; /* subblock gain offset, relative to global gain */
int32_t region0Count; /* 1+region0Count = num scale factor bands in first region of bigvals */
int32_t region1Count; /* 1+region1Count = num scale factor bands in second region of bigvals */
int32_t preFlag; /* for optional high frequency boost */
int32_t sfactScale; /* scaling of the scalefactors */
int32_t count1TableSelect; /* index of Huffman table for quad codewords */
} SideInfoSub_t;
typedef struct SideInfo {
int32_t mainDataBegin;
int32_t privateBits;
int32_t scfsi[m_MAX_NCHAN][m_MAX_SCFBD]; /* 4 scalefactor bands per channel */
} SideInfo_t;
typedef struct {
int32_t cbType; /* pure long = 0, pure short = 1, mixed = 2 */
int32_t cbEndS[3]; /* number nonzero short cb's, per subbblock */
int32_t cbEndSMax; /* max of cbEndS[] */
int32_t cbEndL; /* number nonzero long cb's */
} CriticalBandInfo_t;
typedef struct DequantInfo {
int32_t workBuf[m_MAX_REORDER_SAMPS]; /* workbuf for reordering short blocks */
} DequantInfo_t;
typedef struct HuffmanInfo {
int32_t huffDecBuf[m_MAX_NCHAN][m_MAX_NSAMP]; /* used both for decoded Huffman values and dequantized coefficients */
int32_t nonZeroBound[m_MAX_NCHAN]; /* number of coeffs in huffDecBuf[ch] which can be > 0 */
int32_t gb[m_MAX_NCHAN]; /* minimum number of guard bits in huffDecBuf[ch] */
} HuffmanInfo_t;
typedef enum HuffTabType {
noBits,
oneShot,
loopNoLinbits,
loopLinbits,
quadA,
quadB,
invalidTab
} HuffTabType_t;
typedef struct HuffTabLookup {
int32_t linBits;
int32_t tabType; /*HuffTabType*/
} HuffTabLookup_t;
typedef struct IMDCTInfo {
int32_t outBuf[m_MAX_NCHAN][m_BLOCK_SIZE][m_NBANDS]; /* output of IMDCT */
int32_t overBuf[m_MAX_NCHAN][m_MAX_NSAMP / 2]; /* overlap-add buffer (by symmetry, only need 1/2 size) */
int32_t numPrevIMDCT[m_MAX_NCHAN]; /* how many IMDCT's calculated in this channel on prev. granule */
int32_t prevType[m_MAX_NCHAN];
int32_t prevWinSwitch[m_MAX_NCHAN];
int32_t gb[m_MAX_NCHAN];
} IMDCTInfo_t;
typedef struct BlockCount {
int32_t nBlocksLong;
int32_t nBlocksTotal;
int32_t nBlocksPrev;
int32_t prevType;
int32_t prevWinSwitch;
int32_t currWinSwitch;
int32_t gbIn;
int32_t gbOut;
} BlockCount_t;
typedef struct ScaleFactorInfoSub { /* max bits in scalefactors = 5, so use char's to save space */
char l[23]; /* [band] */
char s[13][3]; /* [band][window] */
} ScaleFactorInfoSub_t;
typedef struct ScaleFactorJS { /* used in MPEG 2, 2.5 intensity (joint) stereo only */
int32_t intensityScale;
int32_t slen[4];
int32_t nr[4];
} ScaleFactorJS_t;
/* NOTE - could get by with smaller vbuf if memory is more important than speed
* (in Subband, instead of replicating each block in FDCT32 you would do a memmove on the
* last 15 blocks to shift them down one, a hardware style FIFO)
*/
typedef struct SubbandInfo {
int32_t vbuf[m_MAX_NCHAN * m_VBUF_LENGTH]; /* vbuf for fast DCT-based synthesis PQMF - double size for speed (no modulo indexing) */
int32_t vindex; /* internal index for tracking position in vbuf */
} SubbandInfo_t;
typedef struct MP3DecInfo {
/* buffer which must be large enough to hold largest possible main_data section */
uint8_t mainBuf[m_MAINBUF_SIZE];
/* special info for "free" bitrate files */
int32_t freeBitrateFlag;
int32_t freeBitrateSlots;
/* user-accessible info */
int32_t bitrate;
int32_t nChans;
int32_t samprate;
int32_t nGrans; /* granules per frame */
int32_t nGranSamps; /* samples per granule */
int32_t nSlots;
int32_t layer;
int32_t mainDataBegin;
int32_t mainDataBytes;
int32_t part23Length[m_MAX_NGRAN][m_MAX_NCHAN];
} MP3DecInfo_t;
const uint16_t mpeg1_layer3_bitrates[16] = { // Bitraten-Lookup tables (example for MPEG1 Layer III)
0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0 // Attention: These tables must be complete and correct!
}; // Index 0 is invalid, index 15 is invalid.
// SamplingFrequenz-Lookup tables(Beispiel für MPEG1, MPEG2, MPEG2.5)
const uint16_t sampling_rates[3][4] = {
{44100, 48000, 32000, 0}, // MPEG1
{22050, 24000, 16000, 0}, // MPEG2
{11025, 12000, 8000, 0} // MPEG2.5
};
typedef struct {
uint8_t mpeg_version; // 0=MPEG2.5, 1=reserved, 2=MPEG2, 3=MPEG1
uint8_t layer; // 0=reserved, 1=Layer III, 2=Layer II, 3=Layer I
bool crc_protected;
uint8_t bitrate_idx;
uint8_t sample_rate_idx;
bool padding;
uint8_t channel_mode;
uint32_t frame_length; // In Bytes
} Mp3FrameHeader;
/* format = Q31
* #define M_PI 3.14159265358979323846
* double u = 2.0 * M_PI / 9.0;
* float c0 = sqrt(3.0) / 2.0;
* float c1 = cos(u);
* float c2 = cos(2*u);
* float c3 = sin(u);
* float c4 = sin(2*u);
*/
const int32_t c9_0 = 0x6ed9eba1;
const int32_t c9_1 = 0x620dbe8b;
const int32_t c9_2 = 0x163a1a7e;
const int32_t c9_3 = 0x5246dd49;
const int32_t c9_4 = 0x7e0e2e32;
const int32_t c3_0 = 0x6ed9eba1; /* format = Q31, cos(pi/6) */
const int32_t c6[3] = { 0x7ba3751d, 0x5a82799a, 0x2120fb83 }; /* format = Q31, cos(((0:2) + 0.5) * (pi/6)) */
/* format = Q31
* cos(((0:8) + 0.5) * (pi/18))
*/
const uint32_t c18[9] = { 0x7f834ed0, 0x7ba3751d, 0x7401e4c1, 0x68d9f964, 0x5a82799a, 0x496af3e2, 0x36185aee, 0x2120fb83, 0x0b27eb5c};
/* scale factor lengths (num bits) */
const char m_SFLenTab[16][2] = { {0, 0}, {0, 1}, {0, 2}, {0, 3}, {3, 0}, {1, 1}, {1, 2}, {1, 3},
{2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}, {4, 2}, {4, 3}};
/* NRTab[size + 3*is_right][block type][partition]
* block type index: 0 = (bt0,bt1,bt3), 1 = bt2 non-mixed, 2 = bt2 mixed
* partition: scale factor groups (sfb1 through sfb4)
* for block type = 2 (mixed or non-mixed) / by 3 is rolled into this table
* (for 3 short blocks per long block)
* see 2.4.3.2 in MPEG 2 (low sample rate) spec
* stuff rolled into this table:
* NRTab[x][1][y] --> (NRTab[x][1][y]) / 3
* NRTab[x][2][>=1] --> (NRTab[x][2][>=1]) / 3 (first partition is long block)
*/
const char NRTab[6][3][4] = {
{{ 6, 5, 5, 5}, {3, 3, 3, 3}, {6, 3, 3, 3}},
{{ 6, 5, 7, 3}, {3, 3, 4, 2}, {6, 3, 4, 2}},
{{11, 10, 0, 0}, {6, 6, 0, 0}, {6, 3, 6, 0}},
{{ 7, 7, 7, 0}, {4, 4, 4, 0}, {6, 5, 4, 0}},
{{ 6, 6, 6, 3}, {4, 3, 3, 2}, {6, 4, 3, 2}},
{{ 8, 8, 5, 0}, {5, 4, 3, 0}, {6, 6, 3, 0}}
};
/* optional pre-emphasis for high-frequency scale factor bands */
const char preTab[22] = { 0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,3,3,3,2,0 };
/* pow(2,-i/4) for i=0..3, Q31 format */
const int32_t pow14[4] PROGMEM = {
0x7fffffff, 0x6ba27e65, 0x5a82799a, 0x4c1bf829
};
/*
* Minimax polynomial approximation to pow(x, 4/3), over the range
* poly43lo: x = [0.5, 0.7071]
* poly43hi: x = [0.7071, 1.0]
*
* Relative error < 1E-7
* Coefs are scaled by 4, 2, 1, 0.5, 0.25
*/
const uint32_t poly43lo[5] PROGMEM = { 0x29a0bda9, 0xb02e4828, 0x5957aa1b, 0x236c498d, 0xff581859 };
const uint32_t poly43hi[5] PROGMEM = { 0x10852163, 0xd333f6a4, 0x46e9408b, 0x27c2cef0, 0xfef577b4 };
/* pow(2, i*4/3) as exp and frac */
const int32_t pow2exp[8] PROGMEM = { 14, 13, 11, 10, 9, 7, 6, 5 };
const int32_t pow2frac[8] PROGMEM = {
0x6597fa94, 0x50a28be6, 0x7fffffff, 0x6597fa94,
0x50a28be6, 0x7fffffff, 0x6597fa94, 0x50a28be6
};
const uint16_t m_HUFF_OFFSET_01= 0;
const uint16_t m_HUFF_OFFSET_02= 9 + m_HUFF_OFFSET_01;
const uint16_t m_HUFF_OFFSET_03= 65 + m_HUFF_OFFSET_02;
const uint16_t m_HUFF_OFFSET_05= 65 + m_HUFF_OFFSET_03;
const uint16_t m_HUFF_OFFSET_06=257 + m_HUFF_OFFSET_05;
const uint16_t m_HUFF_OFFSET_07=129 + m_HUFF_OFFSET_06;
const uint16_t m_HUFF_OFFSET_08=110 + m_HUFF_OFFSET_07;
const uint16_t m_HUFF_OFFSET_09=280 + m_HUFF_OFFSET_08;
const uint16_t m_HUFF_OFFSET_10= 93 + m_HUFF_OFFSET_09;
const uint16_t m_HUFF_OFFSET_11=320 + m_HUFF_OFFSET_10;
const uint16_t m_HUFF_OFFSET_12=296 + m_HUFF_OFFSET_11;
const uint16_t m_HUFF_OFFSET_13=185 + m_HUFF_OFFSET_12;
const uint16_t m_HUFF_OFFSET_15=497 + m_HUFF_OFFSET_13;
const uint16_t m_HUFF_OFFSET_16=580 + m_HUFF_OFFSET_15;
const uint16_t m_HUFF_OFFSET_24=651 + m_HUFF_OFFSET_16;
const int32_t huffTabOffset[m_HUFF_PAIRTABS] PROGMEM = {
0, m_HUFF_OFFSET_01, m_HUFF_OFFSET_02, m_HUFF_OFFSET_03,
0, m_HUFF_OFFSET_05, m_HUFF_OFFSET_06, m_HUFF_OFFSET_07,
m_HUFF_OFFSET_08, m_HUFF_OFFSET_09, m_HUFF_OFFSET_10, m_HUFF_OFFSET_11,
m_HUFF_OFFSET_12, m_HUFF_OFFSET_13, 0, m_HUFF_OFFSET_15,
m_HUFF_OFFSET_16, m_HUFF_OFFSET_16, m_HUFF_OFFSET_16, m_HUFF_OFFSET_16,
m_HUFF_OFFSET_16, m_HUFF_OFFSET_16, m_HUFF_OFFSET_16, m_HUFF_OFFSET_16,
m_HUFF_OFFSET_24, m_HUFF_OFFSET_24, m_HUFF_OFFSET_24, m_HUFF_OFFSET_24,
m_HUFF_OFFSET_24, m_HUFF_OFFSET_24, m_HUFF_OFFSET_24, m_HUFF_OFFSET_24,};
const HuffTabLookup_t huffTabLookup[m_HUFF_PAIRTABS] PROGMEM = {
{ 0, noBits },
{ 0, oneShot },
{ 0, oneShot },
{ 0, oneShot },
{ 0, invalidTab },
{ 0, oneShot },
{ 0, oneShot },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, invalidTab },
{ 0, loopNoLinbits },
{ 1, loopLinbits },
{ 2, loopLinbits },
{ 3, loopLinbits },
{ 4, loopLinbits },
{ 6, loopLinbits },
{ 8, loopLinbits },
{ 10, loopLinbits },
{ 13, loopLinbits },
{ 4, loopLinbits },
{ 5, loopLinbits },
{ 6, loopLinbits },
{ 7, loopLinbits },
{ 8, loopLinbits },
{ 9, loopLinbits },
{ 11, loopLinbits },
{ 13, loopLinbits },
};
const int32_t quadTabOffset[2] PROGMEM = {0, 64};
const int32_t quadTabMaxBits[2] PROGMEM = {6, 4};
/* indexing = [version][samplerate index]
* sample rate of frame (Hz)
*/
const int32_t samplerateTab[3][3] PROGMEM = {
{ 44100, 48000, 32000 }, /* MPEG-1 */
{ 22050, 24000, 16000 }, /* MPEG-2 */
{ 11025, 12000, 8000 }, /* MPEG-2.5 */
};
/* indexing = [version][layer]
* number of samples in one frame (per channel)
*/
const uint16_t samplesPerFrameTab[3][3] PROGMEM = { { 384, 1152, 1152 }, /* MPEG1 */
{ 384, 1152, 576 }, /* MPEG2 */
{ 384, 1152, 576 }, /* MPEG2.5 */
};
/* layers 1, 2, 3 */
const uint8_t bitsPerSlotTab[3] = { 32, 8, 8 };
/* indexing = [version][mono/stereo]
* number of bytes in side info section of bitstream
*/
const uint8_t sideBytesTab[3][2] PROGMEM = { { 17, 32 }, /* MPEG-1: mono, stereo */
{ 9, 17 }, /* MPEG-2: mono, stereo */
{ 9, 17 }, /* MPEG-2.5: mono, stereo */
};
/* indexing = [version][sampleRate][long (.l) or short (.s) block]
* sfBandTable[v][s].l[cb] = index of first bin in critical band cb (long blocks)
* sfBandTable[v][s].s[cb] = index of first bin in critical band cb (short blocks)
*/
const SFBandTable_t sfBandTable[3][3] PROGMEM = {
{ /* MPEG-1 (44, 48, 32 kHz) */
{ {0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, 576 },
{0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192} },
{ {0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, 576 },
{0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192} },
{ {0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, 576 },
{0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192} } },
{ /* MPEG-2 (22, 24, 16 kHz) */
{ {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 },
{0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192} },
{ {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464, 540, 576 },
{0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192} },
{ {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 },
{0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192} }, },
{ /* MPEG-2.5 (11, 12, 8 kHz) */
{ {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 },
{0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 } },
{ {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 },
{0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 } },
{ {0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570, 572, 574, 576 },
{0, 8, 16, 24, 36, 52, 72, 96, 124, 160, 162, 164, 166, 192 } }, },
};
/* indexing = [intensity scale on/off][left/right]
* format = Q30, range = [0.0, 1.414]
*
* illegal intensity position scalefactors (see comments on ISFMpeg1)
*/
const int32_t ISFIIP[2][2] PROGMEM = {
{0x40000000, 0x00000000}, /* mid-side off */
{0x40000000, 0x40000000}, /* mid-side on */
};
const uint8_t uniqueIDTab[8] = {0x5f, 0x4b, 0x43, 0x5f, 0x5f, 0x4a, 0x52, 0x5f};
/* anti-alias coefficients - see spec Annex B, table 3-B.9
* csa[0][i] = CSi, csa[1][i] = CAi
* format = Q31
*/
const uint32_t csa[8][2] PROGMEM = {
{0x6dc253f0, 0xbe2500aa},
{0x70dcebe4, 0xc39e4949},
{0x798d6e73, 0xd7e33f4a},
{0x7ddd40a7, 0xe8b71176},
{0x7f6d20b7, 0xf3e4fe2f},
{0x7fe47e40, 0xfac1a3c7},
{0x7ffcb263, 0xfe2ebdc6},
{0x7fffc694, 0xff86c25d},
};
/* format = Q30, right shifted by 12 (sign bits only in top 12 - undo this when rounding to short)
* this is to enable early-terminating multiplies on ARM
* range = [-1.144287109, 1.144989014]
* max gain of filter (per output sample) ~= 2.731
*
* new (properly sign-flipped) values
* - these actually are correct to 32 bits, (floating-pt coefficients in spec
* chosen such that only ~20 bits are required)
*
* Reordering - see table 3-B.3 in spec (appendix B)
*
* polyCoef[i] =
* D[ 0, 32, 64, ... 480], i = [ 0, 15]
* D[ 1, 33, 65, ... 481], i = [ 16, 31]
* D[ 2, 34, 66, ... 482], i = [ 32, 47]
* ...
* D[15, 47, 79, ... 495], i = [240,255]
*
* also exploits symmetry: D[i] = -D[512 - i], for i = [1, 255]
*
* polyCoef[256, 257, ... 263] are for special case of sample 16 (out of 0)
* see PolyphaseStereo() and PolyphaseMono()
*/
static const char* mpeg_version_table[] = {
"MPEG-2.5", // 0
"reserved", // 1
"MPEG-2", // 2
"MPEG-1" // 3
};
static const char* layer_table[] = {
"Unknown", // 0
"Layer I", // 1
"Layer II", // 2
"Layer III" // 3
};
// prototypes
bool MP3Decoder_AllocateBuffers(void);
bool MP3Decoder_IsInit();
void MP3Decoder_FreeBuffers();
int32_t MP3Decode( uint8_t *inbuf, int32_t *bytesLeft, int16_t *outbuf);
void MP3GetLastFrameInfo();
int32_t MP3GetNextFrameInfo(uint8_t *buf);
int32_t MP3FindSyncWord(uint8_t *buf, int32_t nBytes);
int32_t MP3GetSampRate();
int32_t MP3GetChannels();
int32_t MP3GetBitsPerSample();
int32_t MP3GetBitrate();
int32_t MP3GetOutputSamps();
const char* MP3GetLayer();
const char* MP3GetMPEGVersion();
//internally used
int MP3_AnalyzeFrame(const uint8_t *frame_data, size_t frame_len);
void MP3Decoder_ClearBuffer(void);
void PolyphaseMono(int16_t *pcm, int32_t *vbuf, const uint32_t* coefBase);
void PolyphaseStereo(int16_t *pcm, int32_t *vbuf, const uint32_t* coefBase);
void SetBitstreamPointer(BitStreamInfo_t *bsi, int32_t nBytes, uint8_t *buf);
uint32_t GetBits(BitStreamInfo_t *bsi, int32_t nBits);
int32_t CalcBitsUsed(BitStreamInfo_t *bsi, uint8_t *startBuf, int32_t startOffset);
int32_t DequantChannel(int32_t *sampleBuf, int32_t *workBuf, int32_t *nonZeroBound, SideInfoSub_t *sis, ScaleFactorInfoSub_t *sfis, CriticalBandInfo_t *cbi);
void MidSideProc(int32_t x[m_MAX_NCHAN][m_MAX_NSAMP], int32_t nSamps, int32_t mOut[2]);
void IntensityProcMPEG1(int32_t x[m_MAX_NCHAN][m_MAX_NSAMP], int32_t nSamps, ScaleFactorInfoSub_t *sfis, CriticalBandInfo_t *cbi, int32_t midSideFlag, int32_t mixFlag, int32_t mOut[2]);
void IntensityProcMPEG2(int32_t x[m_MAX_NCHAN][m_MAX_NSAMP], int32_t nSamps, ScaleFactorInfoSub_t *sfis, CriticalBandInfo_t *cbi, ScaleFactorJS_t *sfjs, int32_t midSideFlag, int32_t mixFlag, int32_t mOut[2]);
void FDCT32(int32_t *x, int32_t *d, int32_t offset, int32_t oddBlock, int32_t gb);// __attribute__ ((section (".data")));
int32_t CheckPadBit();
int32_t UnpackFrameHeader(uint8_t *buf);
int32_t UnpackSideInfo(uint8_t *buf);
int32_t DecodeHuffman( uint8_t *buf, int32_t *bitOffset, int32_t huffBlockBits, int32_t gr, int32_t ch);
int32_t MP3Dequantize( int32_t gr);
int32_t IMDCT( int32_t gr, int32_t ch);
int32_t UnpackScaleFactors( uint8_t *buf, int32_t *bitOffset, int32_t bitsAvail, int32_t gr, int32_t ch);
int32_t Subband(int16_t *pcmBuf);
int16_t ClipToShort(int32_t x, int32_t fracBits);
void RefillBitstreamCache(BitStreamInfo_t *bsi);
void UnpackSFMPEG1(BitStreamInfo_t *bsi, SideInfoSub_t *sis, ScaleFactorInfoSub_t *sfis, int32_t *scfsi, int32_t gr, ScaleFactorInfoSub_t *sfisGr0);
void UnpackSFMPEG2(BitStreamInfo_t *bsi, SideInfoSub_t *sis, ScaleFactorInfoSub_t *sfis, int32_t gr, int32_t ch, int32_t modeExt, ScaleFactorJS_t *sfjs);
int32_t MP3FindFreeSync(uint8_t *buf, uint8_t firstFH[4], int32_t nBytes);
void MP3ClearBadFrame( int16_t *outbuf);
int32_t DecodeHuffmanPairs(int32_t *xy, int32_t nVals, int32_t tabIdx, int32_t bitsLeft, uint8_t *buf, int32_t bitOffset);
int32_t DecodeHuffmanQuads(int32_t *vwxy, int32_t nVals, int32_t tabIdx, int32_t bitsLeft, uint8_t *buf, int32_t bitOffset);
int32_t DequantBlock(int32_t *inbuf, int32_t *outbuf, int32_t num, int32_t scale);
void AntiAlias(int32_t *x, int32_t nBfly);
void WinPrevious(int32_t *xPrev, int32_t *xPrevWin, int32_t btPrev);
int32_t FreqInvertRescale(int32_t *y, int32_t *xPrev, int32_t blockIdx, int32_t es);
void idct9(int32_t *x);
int32_t IMDCT36(int32_t *xCurr, int32_t *xPrev, int32_t *y, int32_t btCurr, int32_t btPrev, int32_t blockIdx, int32_t gb);
void imdct12(int32_t *x, int32_t *out);
int32_t IMDCT12x3(int32_t *xCurr, int32_t *xPrev, int32_t *y, int32_t btPrev, int32_t blockIdx, int32_t gb);
int32_t HybridTransform(int32_t *xCurr, int32_t *xPrev, int32_t y[m_BLOCK_SIZE][m_NBANDS], SideInfoSub_t *sis, BlockCount_t *bc);
inline uint64_t SAR64(uint64_t x, int32_t n) {return x >> n;}
inline int32_t MULSHIFT32(int32_t x, int32_t y) { int32_t z; z = (uint64_t) x * (uint64_t) y >> 32; return z;}
inline uint64_t MADD64(uint64_t sum64, int32_t x, int32_t y) {sum64 += (uint64_t) x * (uint64_t) y; return sum64;}/* returns 64-bit value in [edx:eax] */
inline uint64_t xSAR64(uint64_t x, int32_t n){return x >> n;}
inline int32_t FASTABS(int32_t x){ return __builtin_abs(x);} //xtensa has a fast abs instruction //fb
#define CLZ(x) __builtin_clz(x) //fb
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// 📌📌📌 L O G G I N G 📌📌📌
template <typename... Args>
void MP3_ERROR_IMPL(uint8_t level, const char* path, int line, const char* fmt, Args&&... args) {
extern __attribute__((weak)) void audio_info(const char*);
#define ANSI_ESC_RESET "\033[0m"
#define ANSI_ESC_BLACK "\033[30m"
#define ANSI_ESC_RED "\033[31m"
#define ANSI_ESC_GREEN "\033[32m"
#define ANSI_ESC_YELLOW "\033[33m"
#define ANSI_ESC_BLUE "\033[34m"
#define ANSI_ESC_MAGENTA "\033[35m"
#define ANSI_ESC_CYAN "\033[36m"
#define ANSI_ESC_WHITE "\033[37m"
ps_ptr<char> result;
ps_ptr<char> file;
file.copy_from(path);
while(file.contains("/")){
file.remove_before('/', false);
}
// First run: determine size
int len = std::snprintf(nullptr, 0, fmt, std::forward<Args>(args)...);
if (len <= 0) return;
result.alloc(len + 1, "result");
char* dst = result.get();
if (!dst) return;
std::snprintf(dst, len + 1, fmt, std::forward<Args>(args)...);
// build a final string with file/line prefix
ps_ptr<char> final;
int total_len = std::snprintf(nullptr, 0, "%s:%d:" ANSI_ESC_RED " %s" ANSI_ESC_RESET, file.c_get(), line, dst);
if (total_len <= 0) return;
final.alloc(total_len + 1, "final");
char* dest = final.get();
if (!dest) return; // Or error treatment
if(audio_info){
if (level == 1) snprintf(dest, total_len + 1, "%s:%d:" ANSI_ESC_RED " %s" ANSI_ESC_RESET, file.c_get(), line, dst);
else if(level == 2) snprintf(dest, total_len + 1, "%s:%d:" ANSI_ESC_YELLOW " %s" ANSI_ESC_RESET, file.c_get(), line, dst);
else if(level == 3) snprintf(dest, total_len + 1, "%s:%d:" ANSI_ESC_GREEN " %s" ANSI_ESC_RESET, file.c_get(), line, dst);
else snprintf(dest, total_len + 1, "%s:%d:" ANSI_ESC_BLUE " %s" ANSI_ESC_RESET, file.c_get(), line, dst);
audio_info(final.get());
}
else{
std::snprintf(dest, total_len + 1, "%s:%d: %s", file.c_get(), line, dst);
if (level == 1) log_e("%s", final.c_get());
else if(level == 2) log_w("%s", final.c_get());
else if(level == 3) log_i("%s", final.c_get());
else log_d("%s", final.c_get());
}
final.reset();
result.reset();
}
// Macro for comfortable calls
#define MP3_ERROR(fmt, ...) MP3_ERROR_IMPL(1, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define MP3_WARN(fmt, ...) MP3_ERROR_IMPL(2, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
#define MP3_INFO(fmt, ...) MP3_ERROR_IMPL(3, __FILE__, __LINE__, fmt, ##__VA_ARGS__)
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

View File

@@ -0,0 +1,352 @@
/*
AC101 - An AC101 Codec driver library for Arduino
Copyright (C) 2019, Ivo Pullens, Emmission
Inspired by:
https://github.com/donny681/esp-adf/tree/master/components/audio_hal/driver/AC101
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Febr 2021 modified by schreibfaul1 - set correct pll values
March 2021 modified by schreibfaul1 - can handle two i2c instances
May 2021 modified by schreibfaul1 - constructor changed
Oct 2021 modified by schreibfaul1 - I2C wrong ACK in ReadReg
Jan 2022 modified by schreibfaul1 - left right channel swapped
Jan 2022 modified by schreibfaul1 - suppress compiler warning: left shift of negative value
examples:
//one I2C bus: (default behaviour)
AC101 ac;
ac.begin(sda, scl);
//two I2C busses:
TwoWire i2cBusOne = TwoWire(0);
TwoWire i2cBusTwo = TwoWire(1);
AC101 ac(&i2cBusOne);
i2cBusOne.begin(sda, scl, 400000);
*/
#include "AC101.h"
#define BCLK // clock over BCLK comment out: clock over MCLK
#define AC101_ADDR 0x1A // Device address
#define CHIP_AUDIO_RS 0x00
#define PLL_CTRL1 0x01
#define PLL_CTRL2 0x02
#define SYSCLK_CTRL 0x03
#define MOD_CLK_ENA 0x04
#define MOD_RST_CTRL 0x05
#define I2S_SR_CTRL 0x06
#define I2S1LCK_CTRL 0x10
#define I2S1_SDOUT_CTRL 0x11
#define I2S1_SDIN_CTRL 0x12
#define I2S1_MXR_SRC 0x13
#define I2S1_VOL_CTRL1 0x14
#define I2S1_VOL_CTRL2 0x15
#define I2S1_VOL_CTRL3 0x16
#define I2S1_VOL_CTRL4 0x17
#define I2S1_MXR_GAIN 0x18
#define ADC_DIG_CTRL 0x40
#define ADC_VOL_CTRL 0x41
#define HMIC_CTRL1 0x44
#define HMIC_CTRL2 0x45
#define HMIC_STATUS 0x46
#define DAC_DIG_CTRL 0x48
#define DAC_VOL_CTRL 0x49
#define DAC_MXR_SRC 0x4C
#define DAC_MXR_GAIN 0x4D
#define ADC_APC_CTRL 0x50
#define ADC_SRC 0x51
#define ADC_SRCBST_CTRL 0x52
#define OMIXER_DACA_CTRL 0x53
#define OMIXER_SR 0x54
#define OMIXER_BST1_CTRL 0x55
#define HPOUT_CTRL 0x56
#define SPKOUT_CTRL 0x58
#define AC_DAC_DAPCTRL 0xA0
#define AC_DAC_DAPHHPFC 0xA1
#define AC_DAC_DAPLHPFC 0xA2
#define AC_DAC_DAPLHAVC 0xA3
#define AC_DAC_DAPLLAVC 0xA4
#define AC_DAC_DAPRHAVC 0xA5
#define AC_DAC_DAPRLAVC 0xA6
#define AC_DAC_DAPHGDEC 0xA7
#define AC_DAC_DAPLGDEC 0xA8
#define AC_DAC_DAPHGATC 0xA9
#define AC_DAC_DAPLGATC 0xAA
#define AC_DAC_DAPHETHD 0xAB
#define AC_DAC_DAPLETHD 0xAC
#define AC_DAC_DAPHGKPA 0xAD
#define AC_DAC_DAPLGKPA 0xAE
#define AC_DAC_DAPHGOPA 0xAF
#define AC_DAC_DAPLGOPA 0xB0
#define AC_DAC_DAPOPT 0xB1
#define DAC_DAP_ENA 0xB5
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
const uint8_t regs[] = {
CHIP_AUDIO_RS ,
PLL_CTRL1 ,
PLL_CTRL2 ,
SYSCLK_CTRL ,
MOD_CLK_ENA ,
MOD_RST_CTRL ,
I2S_SR_CTRL ,
I2S1LCK_CTRL ,
I2S1_SDOUT_CTRL ,
I2S1_SDIN_CTRL ,
I2S1_MXR_SRC ,
I2S1_VOL_CTRL1 ,
I2S1_VOL_CTRL2 ,
I2S1_VOL_CTRL3 ,
I2S1_VOL_CTRL4 ,
I2S1_MXR_GAIN ,
ADC_DIG_CTRL ,
ADC_VOL_CTRL ,
HMIC_CTRL1 ,
HMIC_CTRL2 ,
HMIC_STATUS ,
DAC_DIG_CTRL ,
DAC_VOL_CTRL ,
DAC_MXR_SRC ,
DAC_MXR_GAIN ,
ADC_APC_CTRL ,
ADC_SRC ,
ADC_SRCBST_CTRL ,
OMIXER_DACA_CTRL ,
OMIXER_SR ,
OMIXER_BST1_CTRL ,
HPOUT_CTRL ,
SPKOUT_CTRL ,
AC_DAC_DAPCTRL ,
AC_DAC_DAPHHPFC ,
AC_DAC_DAPLHPFC ,
AC_DAC_DAPLHAVC ,
AC_DAC_DAPLLAVC ,
AC_DAC_DAPRHAVC ,
AC_DAC_DAPRLAVC ,
AC_DAC_DAPHGDEC ,
AC_DAC_DAPLGDEC ,
AC_DAC_DAPHGATC ,
AC_DAC_DAPLGATC ,
AC_DAC_DAPHETHD ,
AC_DAC_DAPLETHD ,
AC_DAC_DAPHGKPA ,
AC_DAC_DAPLGKPA ,
AC_DAC_DAPHGOPA ,
AC_DAC_DAPLGOPA ,
AC_DAC_DAPOPT ,
DAC_DAP_ENA
};
//----------------------------------------------------------------------------------------------------------------------
bool AC101::WriteReg(uint8_t reg, uint16_t val)
{
_TwoWireInstance->beginTransmission(AC101_ADDR);
_TwoWireInstance->write(reg);
_TwoWireInstance->write(uint8_t((val >> 8) & 0xff));
_TwoWireInstance->write(uint8_t(val & 0xff));
return 0 == _TwoWireInstance->endTransmission(true);
}
uint16_t AC101::ReadReg(uint8_t reg)
{
_TwoWireInstance->beginTransmission(AC101_ADDR);
_TwoWireInstance->write(reg);
_TwoWireInstance->endTransmission(false);
uint16_t val = 0u;
if (2 == _TwoWireInstance->requestFrom(uint16_t(AC101_ADDR), uint8_t(2)))
{
val = uint16_t(_TwoWireInstance->read() << 8) + uint16_t(_TwoWireInstance->read());
}
_TwoWireInstance->endTransmission(true);
return val;
}
//----------------------------------------------------------------------------------------------------------------------
AC101::AC101( TwoWire *TwoWireInstance ){
_TwoWireInstance = TwoWireInstance;
}
//----------------------------------------------------------------------------------------------------------------------
bool AC101::begin(int32_t sda, int32_t scl, uint32_t frequency) {
bool ok;
if((sda >= 0) && (scl >= 0)){
ok = _TwoWireInstance->begin(sda, scl, frequency);
}
else {
ok = true;
}
// Reset all registers, readback default as sanity check
ok &= WriteReg(CHIP_AUDIO_RS, 0x123);
delay(100);
ok &= 0x0101 == ReadReg(CHIP_AUDIO_RS);
ok &= WriteReg(SPKOUT_CTRL, 0xe880);
// Enable the PLL from 256*44.1KHz MCLK source
ok &= WriteReg(PLL_CTRL1, 0x0141);
uint16_t N = 48 << 4; /* 512 / (M * (2*K+1)) / (CHANNELS * WORD_SIZE) -> 512 / 3 * (2 * 16) */
uint16_t PLL_EN = 1 << 15;
uint16_t N_f = 0<<0; /* 0.2 N */
ok &= WriteReg(PLL_CTRL2, N | PLL_EN | N_f);
// Clocking system
uint16_t PLLCLK_ENA = 1<<15; /* 0: Disable, 1: Enable */
#ifdef BCLK
uint16_t PLL_CLK = 0x2 << 12; /* bclk1 */
uint16_t I2S1CLK_SRC = 0x3<<8; /* PLL */
#else
uint16_t PLL_CLK = 0x0 << 12; /* MCLK1 */
uint16_t I2S1CLK_SRC = 0x0<<8; /* MLCK1 */
#endif
uint16_t I2S1CLK_ENA = 1<<11; /* 0: Disable, 1: Enable */
uint16_t SYSCLK_ENA = 1<<3;
ok &= WriteReg(SYSCLK_CTRL, PLLCLK_ENA|PLL_CLK| I2S1CLK_ENA|I2S1CLK_SRC|SYSCLK_ENA/*0x8b08*/);
ok &= WriteReg(MOD_CLK_ENA, 0x800c);
ok &= WriteReg(MOD_RST_CTRL, 0x800c);
// Set default at I2S, 44.1KHz, 16bit
ok &= SetI2sSampleRate(SAMPLE_RATE_44100);
ok &= SetI2sClock(BCLK_DIV_8, false, LRCK_DIV_32, false);
ok &= SetI2sMode(MODE_SLAVE);
ok &= SetI2sWordSize(WORD_SIZE_16_BITS);
ok &= SetI2sFormat(DATA_FORMAT_I2S);
// AIF config
ok &= WriteReg(I2S1_SDOUT_CTRL, 0xc000);
ok &= WriteReg(I2S1_SDIN_CTRL, 0xc000);
ok &= WriteReg(I2S1_MXR_SRC, 0x2200);
ok &= WriteReg(ADC_SRCBST_CTRL, 0xccc4);
ok &= WriteReg(ADC_SRC, 0x1040);
ok &= WriteReg(ADC_DIG_CTRL, 0x8000);
ok &= WriteReg(ADC_APC_CTRL, 0xbbc3);
// Path Configuration
ok &= WriteReg(DAC_MXR_SRC, 0xcc00);
ok &= WriteReg(DAC_DIG_CTRL, 0x8000);
ok &= WriteReg(OMIXER_SR, 0x0081);
ok &= WriteReg(OMIXER_DACA_CTRL, 0xf080);
ok &= SetMode( MODE_DAC );
return ok;
}
//----------------------------------------------------------------------------------------------------------------------
void AC101::DumpRegisters() {
for (size_t i = 0; i < ARRAY_SIZE(regs); ++i){
Serial.print(regs[i], HEX);
Serial.print(" = ");
Serial.println(ReadReg(regs[i]), HEX);
}
}
//----------------------------------------------------------------------------------------------------------------------
uint8_t AC101::GetVolumeSpeaker() {
// Times 2, to scale to same range as headphone volume
return (ReadReg(SPKOUT_CTRL) & 31) * 2;
}
bool AC101::SetVolumeSpeaker(uint8_t volume) {
// Divide by 2, as it is scaled to same range as headphone volume
volume /= 2;
if(volume > 31) volume = 31;
uint16_t val = ReadReg(SPKOUT_CTRL);
val &= ~31;
val |= volume;
return WriteReg(SPKOUT_CTRL, val);
}
//----------------------------------------------------------------------------------------------------------------------
uint8_t AC101::GetVolumeHeadphone() {
return (ReadReg(HPOUT_CTRL) >> 4) & 63;
}
bool AC101::SetVolumeHeadphone(uint8_t volume) {
if(volume > 63) volume = 63;
uint16_t val = ReadReg(HPOUT_CTRL);
val &= ~63U << 4;
val |= volume << 4;
return WriteReg(HPOUT_CTRL, val);
}
//----------------------------------------------------------------------------------------------------------------------
bool AC101::SetI2sSampleRate(I2sSampleRate_t rate) {
return WriteReg(I2S_SR_CTRL, rate);
}
//----------------------------------------------------------------------------------------------------------------------
bool AC101::SetI2sMode(I2sMode_t mode) {
uint16_t val = ReadReg(I2S1LCK_CTRL);
val &= ~0x8000;
val |= uint16_t(mode) << 15;
return WriteReg(I2S1LCK_CTRL, val);
}
//----------------------------------------------------------------------------------------------------------------------
bool AC101::SetI2sWordSize(I2sWordSize_t size) {
uint16_t val = ReadReg(I2S1LCK_CTRL);
val &= ~0x0030;
val |= uint16_t(size) << 4;
return WriteReg(I2S1LCK_CTRL, val);
}
//----------------------------------------------------------------------------------------------------------------------
bool AC101::SetI2sFormat(I2sFormat_t format) {
uint16_t val = ReadReg(I2S1LCK_CTRL);
val &= ~0x000C;
val |= uint16_t(format) << 2;
return WriteReg(I2S1LCK_CTRL, val);
}
//----------------------------------------------------------------------------------------------------------------------
bool AC101::SetI2sClock(I2sBitClockDiv_t bitClockDiv, bool bitClockInv, I2sLrClockDiv_t lrClockDiv, bool lrClockInv) {
uint16_t val = ReadReg(I2S1LCK_CTRL);
val &= ~0x7FC0;
val |= uint16_t(bitClockInv ? 1 : 0) << 14;
val |= uint16_t(bitClockDiv) << 9;
val |= uint16_t(lrClockInv ? 1 : 0) << 13;
val |= uint16_t(lrClockDiv) << 6;
return WriteReg(I2S1LCK_CTRL, val);
}
//----------------------------------------------------------------------------------------------------------------------
bool AC101::SetMode(Mode_t mode) {
bool ok = true;
if(MODE_LINE == mode) {
ok &= WriteReg(ADC_SRC, 0x0408);
ok &= WriteReg(ADC_DIG_CTRL, 0x8000);
ok &= WriteReg(ADC_APC_CTRL, 0x3bc0);
}
if((MODE_ADC == mode) or (MODE_ADC_DAC == mode) or (MODE_LINE == mode)) {
ok &= WriteReg(MOD_CLK_ENA, 0x800c);
ok &= WriteReg(MOD_RST_CTRL, 0x800c);
}
if((MODE_DAC == mode) or (MODE_ADC_DAC == mode) or (MODE_LINE == mode)) {
// Enable Headphone output
ok &= WriteReg(OMIXER_DACA_CTRL, 0xff80);
ok &= WriteReg(HPOUT_CTRL, 0xc3c1);
ok &= WriteReg(HPOUT_CTRL, 0xcb00);
delay(100);
ok &= WriteReg(HPOUT_CTRL, 0xfbc0);
ok &= SetVolumeHeadphone(30);
// Enable Speaker output
ok &= WriteReg(SPKOUT_CTRL, 0xeabd);
delay(10);
ok &= SetVolumeSpeaker(30);
}
return ok;
}

View File

@@ -0,0 +1,166 @@
/*
AC101 - An AC101 Codec driver library for Arduino
Copyright (C) 2019, Ivo Pullens, Emmission
Inspired by:
https://github.com/donny681/esp-adf/tree/master/components/audio_hal/driver/AC101
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef AC101_H
#define AC101_H
#include <Arduino.h>
#include <inttypes.h>
#include <Wire.h>
class AC101
{
public:
typedef enum {
SAMPLE_RATE_8000 = 0x0000,
SAMPLE_RATE_11052 = 0x1000,
SAMPLE_RATE_12000 = 0x2000,
SAMPLE_RATE_16000 = 0x3000,
SAMPLE_RATE_22050 = 0x4000,
SAMPLE_RATE_24000 = 0x5000,
SAMPLE_RATE_32000 = 0x6000,
SAMPLE_RATE_44100 = 0x7000,
SAMPLE_RATE_48000 = 0x8000,
SAMPLE_RATE_96000 = 0x9000,
SAMPLE_RATE_192000 = 0xa000,
} I2sSampleRate_t;
typedef enum {
MODE_MASTER = 0x00,
MODE_SLAVE = 0x01,
} I2sMode_t;
typedef enum {
WORD_SIZE_8_BITS = 0x00,
WORD_SIZE_16_BITS = 0x01,
WORD_SIZE_20_BITS = 0x02,
WORD_SIZE_24_BITS = 0x03,
} I2sWordSize_t;
typedef enum {
DATA_FORMAT_I2S = 0x00,
DATA_FORMAT_LEFT = 0x01,
DATA_FORMAT_RIGHT = 0x02,
DATA_FORMAT_DSP = 0x03,
} I2sFormat_t;
typedef enum {
BCLK_DIV_1 = 0x0,
BCLK_DIV_2 = 0x1,
BCLK_DIV_4 = 0x2,
BCLK_DIV_6 = 0x3,
BCLK_DIV_8 = 0x4,
BCLK_DIV_12 = 0x5,
BCLK_DIV_16 = 0x6,
BCLK_DIV_24 = 0x7,
BCLK_DIV_32 = 0x8,
BCLK_DIV_48 = 0x9,
BCLK_DIV_64 = 0xa,
BCLK_DIV_96 = 0xb,
BCLK_DIV_128 = 0xc,
BCLK_DIV_192 = 0xd,
} I2sBitClockDiv_t;
typedef enum {
LRCK_DIV_16 = 0x0,
LRCK_DIV_32 = 0x1,
LRCK_DIV_64 = 0x2,
LRCK_DIV_128 = 0x3,
LRCK_DIV_256 = 0x4,
} I2sLrClockDiv_t;
typedef enum {
MODE_ADC,
MODE_DAC,
MODE_ADC_DAC,
MODE_LINE
} Mode_t;
// Constructor.
AC101(TwoWire *TwoWireInstance = &Wire);
// Initialize codec, using provided I2C pins and bus frequency.
// @return True on success, false on failure.
bool begin(int32_t sda = -1, int32_t scl = -1, uint32_t frequency = 400000);
// Get speaker volume.
// @return Speaker volume, [63..0] for [0..-43.5] [dB], in increments of 2.
uint8_t GetVolumeSpeaker();
// Set speaker volume.
// @param volume Target volume, [63..0] for [0..-43.5] [dB], in increments of 2.
// @return True on success, false on failure.
bool SetVolumeSpeaker(uint8_t volume);
// Get headphone volume.
// @return Headphone volume, [63..0] for [0..-62] [dB]
uint8_t GetVolumeHeadphone();
// Set headphone volume
// @param volume Target volume, [63..0] for [0..-62] [dB]
// @return True on success, false on failure.
bool SetVolumeHeadphone(uint8_t volume);
// Configure I2S samplerate.
// @param rate Samplerate.
// @return True on success, false on failure.
bool SetI2sSampleRate(I2sSampleRate_t rate);
// Configure I2S mode (master/slave).
// @param mode Mode.
// @return True on success, false on failure.
bool SetI2sMode(I2sMode_t mode);
// Configure I2S word size (8/16/20/24 bits).
// @param size Word size.
// @return True on success, false on failure.
bool SetI2sWordSize(I2sWordSize_t size);
// Configure I2S format (I2S/Left/Right/Dsp).
// @param format I2S format.
// @return True on success, false on failure.
bool SetI2sFormat(I2sFormat_t format);
// Configure I2S clock.
// @param bitClockDiv I2S1CLK/BCLK1 ratio.
// @param bitClockInv I2S1 BCLK Polarity.
// @param lrClockDiv BCLK1/LRCK ratio.
// @param lrClockInv I2S1 LRCK Polarity.
// @return True on success, false on failure.
bool SetI2sClock(I2sBitClockDiv_t bitClockDiv, bool bitClockInv, I2sLrClockDiv_t lrClockDiv, bool lrClockInv);
// Configure the mode (Adc/Dac/Adc+Dac/Line)
// @param mode Operating mode.
// @return True on success, false on failure.
bool SetMode(Mode_t mode);
// Dumpt the current register configuration to serial.
void DumpRegisters();
protected:
bool WriteReg(uint8_t reg, uint16_t val);
uint16_t ReadReg(uint8_t reg);
private:
TwoWire *_TwoWireInstance = NULL; // TwoWire Instance
};
#endif

View File

@@ -0,0 +1,85 @@
#include "Arduino.h"
#include "WiFi.h"
#include "SPI.h"
#include "SD.h"
#include "FS.h"
#include "Wire.h"
#include "AC101.h"
#include "Audio.h"
// I2S GPIOs, the names refer on AC101, AS1 Audio Kit V2.2 2379
#define I2S_DSIN 35 // pin not used
#define I2S_BCLK 27
#define I2S_LRC 26
#define I2S_MCLK 0
#define I2S_DOUT 25
// I2C GPIOs
#define IIC_CLK 32
#define IIC_DATA 33
// amplifier enable
#define GPIO_PA_EN 21
//Switch S1: 1-OFF, 2-ON, 3-ON, 4-OFF, 5-OFF
String ssid = "*****";
String password = "*****";
static AC101 dac; // AC101
int volume = 40; // 0...100
Audio audio;
//#####################################################################
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), password.c_str());
while (WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(100);
}
Serial.printf_P(PSTR("Connected\r\nRSSI: "));
Serial.print(WiFi.RSSI());
Serial.print(" IP: ");
Serial.println(WiFi.localIP());
Serial.printf("Connect to DAC codec... ");
while (not dac.begin(IIC_DATA, IIC_CLK)){
Serial.printf("Failed!\n");
delay(1000);
}
Serial.printf("OK\n");
dac.SetVolumeSpeaker(volume);
dac.SetVolumeHeadphone(volume);
// ac.DumpRegisters();
// Enable amplifier
pinMode(GPIO_PA_EN, OUTPUT);
digitalWrite(GPIO_PA_EN, HIGH);
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT, I2S_MCLK);
audio.setVolume(10); // 0...21
audio.connecttohost("http://mp3channels.webradio.antenne.de:80/oldies-but-goldies");
// audio.connecttohost("http://dg-rbb-http-dus-dtag-cdn.cast.addradio.de/rbb/antennebrandenburg/live/mp3/128/stream.mp3");
// audio.connecttospeech("Wenn die Hunde schlafen, kann der Wolf gut Schafe stehlen.", "de");
}
//-----------------------------------------------------------------------
void loop(){
vTaskDelay(1);
audio.loop();
}

View File

@@ -0,0 +1,292 @@
// example AUDIO RECORDER
// starts an audio stream and records 10 seconds of it on the SD card.
#include "Arduino.h"
#include "Audio.h"
#include "WiFiMulti.h"
#include <atomic>
#include <algorithm>
Audio audio;
WiFiMulti wifiMulti;
//______________________________________________________________________________________________________________________________________________________________________________________________________
// A U D I O R E C O R D E R
//______________________________________________________________________________________________________________________________________________________________________________________________________
struct WAVHeader {
char riff[4] = {'R', 'I', 'F', 'F'};
uint32_t size;
char wave[4] = {'W', 'A', 'V', 'E'};
char fmt[4] = {'f', 'm', 't', ' '};
uint32_t fmtSize = 16;
uint16_t format = 1;
uint16_t channels = 2;
uint32_t sampleRate;
uint32_t byteRate;
uint16_t blockAlign;
uint16_t bits;
char data[4] = {'d', 'a', 't', 'a'};
uint32_t dataSize;
};
constexpr size_t REC_BUFFER_SIZE = 512 * 1024; // 512KB für 2-3 Sekunden Puffer
constexpr size_t WRITE_CHUNK_SIZE = 10242; // not too big!
constexpr size_t SD_FLUSH_INTERVAL = 65536; // Alle 64KB flush
ps_ptr<uint8_t> rec_buffer;
ps_ptr<uint8_t> writeBuffer;
class AudioRecorder {
public:
std::atomic<size_t> writePos{0};
std::atomic<size_t> readPos{0};
uint32_t totalBytes = 0;
uint16_t sampleRate = 44100;
uint32_t overflowCount = 0;
volatile bool startRequested = false;
volatile bool stopRequested = false;
volatile bool running = false;
bool push16(const int32_t* data, size_t frames) {
// frames = Stereo-Frames
size_t bytes16 = frames * 2 * sizeof(int16_t);
size_t currentWrite = writePos.load(std::memory_order_relaxed);
size_t currentRead = readPos.load(std::memory_order_acquire);
size_t free = (currentRead + REC_BUFFER_SIZE - currentWrite - 1) % REC_BUFFER_SIZE;
if (bytes16 > free) {
overflowCount++;
return false;
}
for (size_t i = 0; i < frames * 2; i++) {
// 32 → 16 Bit (High word)
int32_t v = data[i] >> 16;
// Optional Clipping (save)
if (v > 32767) v = 32767;
if (v < -32768) v = -32768;
int16_t s = (int16_t)v;
// Write byte by byte (LE)
rec_buffer[currentWrite] = s & 0xFF;
currentWrite = (currentWrite + 1) % REC_BUFFER_SIZE;
rec_buffer[currentWrite] = (s >> 8) & 0xFF;
currentWrite = (currentWrite + 1) % REC_BUFFER_SIZE;
}
writePos.store(currentWrite, std::memory_order_release);
return true;
}
// Copies data to dest, returns bytes actually read
size_t pop(uint8_t* dest, size_t maxLen) {
size_t currentRead = readPos.load(std::memory_order_relaxed);
size_t currentWrite = writePos.load(std::memory_order_acquire);
if (currentRead == currentWrite) return 0;
size_t avail = (currentWrite > currentRead) ? (currentWrite - currentRead) : (REC_BUFFER_SIZE - currentRead);
size_t toRead = std::min(avail, maxLen);
// Wrap-around handling
size_t firstChunk = std::min(toRead, REC_BUFFER_SIZE - currentRead);
memcpy(dest, &rec_buffer[currentRead], firstChunk);
if (toRead > firstChunk) { memcpy(dest + firstChunk, &rec_buffer[0], toRead - firstChunk); }
readPos.store((currentRead + toRead) % REC_BUFFER_SIZE, std::memory_order_release);
return toRead;
}
// For external access to buffers (e.g. for pop with pointer math, but not recommended)
size_t available() {
size_t w = writePos.load(std::memory_order_acquire);
size_t r = readPos.load(std::memory_order_acquire);
return (w >= r) ? (w - r) : (REC_BUFFER_SIZE - r + w);
}
};
AudioRecorder recorder;
void wavWriterTask(void*) {
File file;
WAVHeader hdr;
bool fileOpen = false;
size_t writeBufferFill = 0;
uint32_t bytesSinceFlush = 0;
while (true) {
// --- START REQUEST ---
if (recorder.startRequested && !fileOpen) {
recorder.startRequested = false;
// Datei mit Zeitstempel erstellen
char filename[64];
snprintf(filename, sizeof(filename), "/recording.wav");
file = SD_MMC.open(filename, FILE_WRITE);
if (!file) {
Serial.println("Failed to open file! \"/recording.wav\"");
continue;
}
// prepeare header
hdr.sampleRate = recorder.sampleRate;
hdr.byteRate = recorder.sampleRate * 2 * 2; // Stereo, 16-bit
hdr.blockAlign = 2 * 2; // 8 bytes per frame
hdr.bits = 16;
hdr.dataSize = 0;
hdr.size = 36; // 44 - 8 (RIFF header)
file.write((uint8_t*)&hdr, sizeof(hdr));
recorder.totalBytes = 0;
writeBufferFill = 0;
bytesSinceFlush = 0;
fileOpen = true;
recorder.running = true;
Serial.printf("Recording started: %s\n", filename);
}
// --- WRITE DATA ---
if (fileOpen) {
// fill local buffer
while (writeBufferFill < WRITE_CHUNK_SIZE) {
size_t spaceInLocalBuffer = WRITE_CHUNK_SIZE - writeBufferFill;
size_t bytesRead = recorder.pop(writeBuffer + writeBufferFill, spaceInLocalBuffer);
if (bytesRead == 0) break; // ringbuffer is empty
writeBufferFill += bytesRead;
}
// write full block to SD
if (writeBufferFill >= WRITE_CHUNK_SIZE) {
size_t written = file.write(writeBuffer.get(), WRITE_CHUNK_SIZE);
if (written != WRITE_CHUNK_SIZE) {
Serial.println("SD write error!");
// Optional: error handling, hold buffer?
}
recorder.totalBytes += written;
bytesSinceFlush += written;
writeBufferFill = 0; // buffer is empty (or move remaining data)
// Periodic flush for data integrity
if (bytesSinceFlush >= SD_FLUSH_INTERVAL) {
file.flush();
bytesSinceFlush = 0;
}
}
}
// --- STOP REQUEST ---
if (recorder.stopRequested && fileOpen) {
recorder.stopRequested = false;
// Write remaining data to local buffer
if (writeBufferFill > 0) {
file.write(writeBuffer.get(), writeBufferFill);
recorder.totalBytes += writeBufferFill;
}
// Update header
hdr.dataSize = recorder.totalBytes;
hdr.size = recorder.totalBytes + 36;
file.seek(0);
file.write((uint8_t*)&hdr, sizeof(hdr));
file.flush();
file.close();
fileOpen = false;
writeBufferFill = 0;
recorder.running = false;
Serial.printf("Recording stopped. Total bytes: %u, Overflows: %u\n", recorder.totalBytes, recorder.overflowCount);
}
// Small delay to feed watchdog and release CPU
// But not too long, so that the ring buffer does not overflow!
vTaskDelay(pdMS_TO_TICKS(1)); // 1ms = ~176 Bytes bei 44.1kHz Stereo 32-bit
}
}
//______________________________________________________________________________________________________________________________________________________________________________________________________
#define I2S_DOUT 25
#define I2S_BCLK 27
#define I2S_LRC 26
#define SD_MMC_D0 2
#define SD_MMC_CLK 14
#define SD_MMC_CMD 15
String ssid = "*****";
String password = "*****";
uint32_t t;
enum {IDLE, RECORDING, FINISH, PLAYBACK};
uint8_t state = IDLE;
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Serial.begin(115200);
Audio::audio_info_callback = my_audio_info;
Serial.print("\n\n");
wifiMulti.addAP(ssid.c_str(), password.c_str());
wifiMulti.run(); // if there are multiple access points, use the strongest one
while (WiFi.status() != WL_CONNECTED) delay(1500);
pinMode(SD_MMC_D0, INPUT_PULLUP);
SD_MMC.setPins(SD_MMC_CLK, SD_MMC_CMD, SD_MMC_D0);
SD_MMC.begin("/sdcard", true);
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(20); // default 0...21
audio.connecttohost("http://stream.antennethueringen.de/live/aac-64/stream.antennethueringen.de/"); // aac
rec_buffer.alloc_array(REC_BUFFER_SIZE, "rec_buffer"); // allocate in PSRAM
writeBuffer.alloc_array(WRITE_CHUNK_SIZE, "writeBuffer"); // allocate in PSRAM
xTaskCreatePinnedToCore(wavWriterTask, "wavWriter", 4096, nullptr, 1, nullptr, 0); // start recorder task
Serial.printf("recorder task started, Free heap: %u\n", ESP.getFreeHeap());
t = millis();
}
void loop() {
audio.loop();
vTaskDelay(1);
if (t + 5000 < millis() && state == IDLE && audio.isRunning()) {
Serial.println("start recording");
state = RECORDING;
recorder.sampleRate = audio.getSampleRate();
recorder.startRequested = true;
}
if (t + 15000 < millis() && state == RECORDING) {
Serial.println("stop recording");
state = FINISH;
recorder.stopRequested = true;
audio.stopSong();
}
if (t + 17000 < millis() && state == FINISH) {
state = PLAYBACK;
audio.connecttoFS(SD_MMC, "/recording.wav");
}
if (t + 29000 < millis() && state == PLAYBACK && !audio.isRunning()) {
state = IDLE;
audio.connecttohost("http://stream.antennethueringen.de/live/aac-64/stream.antennethueringen.de/");
t = millis();
}
}
//______________________________________________________________________________________________________________________________________________________________________________________________________
void audio_process_raw_samples(int32_t* outBuff, int16_t validSamples) { // samples are available, write in wav file
if (recorder.running == true) {
recorder.push16(outBuff, validSamples);
}
}

Binary file not shown.

View File

@@ -0,0 +1,316 @@
/*
ES8311 - An ES8311 Codec driver library for Arduino
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
examples:
//one I2C bus: (default behaviour)
ES8311 es;
es.begin(sda, scl);
//two I2C busses:
TwoWire i2cBusOne = TwoWire(0);
TwoWire i2cBusTwo = TwoWire(1);
ES8311 es(&i2cBusOne);
i2cBusOne.begin(sda, scl, 400000);
*/
#include "es8311.h"
/* codec hifi mclk clock divider coefficients */
static const struct _coeff_div coeff_div[] = {
/*!<mclk rate pre_div mult adc_div dac_div fs_mode lrch lrcl bckdiv osr */
/* 8k */
{12288000, 8000, 0x06, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 8000, 0x03, 0x01, 0x03, 0x03, 0x00, 0x05, 0xff, 0x18, 0x10, 0x10},
{16384000, 8000, 0x08, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{8192000, 8000, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 8000, 0x03, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{4096000, 8000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 8000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2048000, 8000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 8000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1024000, 8000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 11.025k */
{11289600, 11025, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{5644800, 11025, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2822400, 11025, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1411200, 11025, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 12k */
{12288000, 12000, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 12000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 12000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 12000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 16k */
{12288000, 16000, 0x03, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 16000, 0x03, 0x01, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10},
{16384000, 16000, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{8192000, 16000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 16000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{4096000, 16000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 16000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2048000, 16000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 16000, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1024000, 16000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 22.05k */
{11289600, 22050, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{5644800, 22050, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2822400, 22050, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1411200, 22050, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{705600, 22050, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 24k */
{12288000, 24000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 24000, 0x03, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 24000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 24000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 24000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 32k */
{12288000, 32000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 32000, 0x03, 0x02, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10},
{16384000, 32000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{8192000, 32000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 32000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{4096000, 32000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 32000, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2048000, 32000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 32000, 0x03, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
{1024000, 32000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 44.1k */
{11289600, 44100, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{5644800, 44100, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2822400, 44100, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1411200, 44100, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 48k */
{12288000, 48000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 48000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 48000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 48000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 48000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
/* 64k */
{12288000, 64000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 64000, 0x03, 0x02, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{16384000, 64000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{8192000, 64000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 64000, 0x01, 0x02, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{4096000, 64000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 64000, 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
{2048000, 64000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 64000, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0xbf, 0x03, 0x18, 0x18},
{1024000, 64000, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
/* 88.2k */
{11289600, 88200, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{5644800, 88200, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{2822400, 88200, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1411200, 88200, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
/* 96k */
{12288000, 96000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{18432000, 96000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{6144000, 96000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{3072000, 96000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
{1536000, 96000, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
};
ES8311::ES8311(TwoWire *TwoWireInstance){
_TwoWireInstance = TwoWireInstance;
}
ES8311::~ES8311(){
if (_TwoWireInstance != NULL) {
_TwoWireInstance->end();
}
}
/*
* look for the coefficient in coeff_div[] table
*/
int ES8311::get_coeff(uint32_t mclk, uint32_t rate){
for (int i = 0; i < (sizeof(coeff_div) / sizeof(coeff_div[0])); i++) {
if (coeff_div[i].rate == rate && coeff_div[i].mclk == mclk) {
return i;
}
}
return -1;
}
bool ES8311::begin(int32_t sda, int32_t scl, uint32_t frequency) {
bool ok = true;
uint8_t reg = 0;
if((sda >= 0) && (scl >= 0)){
ok = _TwoWireInstance->begin(sda, scl, frequency);
_TwoWireInstance->beginTransmission(ES8311_ADDR);
ok = (Wire.endTransmission() == 0);
if(!ok) {
_TwoWireInstance->end();
log_e("ES8311 not found"); return false;
}
}
else {
log_e("Invalid SDA/SCL pins");
return false;
}
ok |= WriteReg(0x00, 0x1F); // Reset
vTaskDelay(20 / portTICK_PERIOD_MS);
ok |= WriteReg(0x00, 0x00); // Release reset
ok |= WriteReg(0x00, 0x80); // Power on
ok |= WriteReg(0x01, 0x3F); // Enable all clocks
reg = ReadReg(0x06);
reg &= ~BIT(5); // SCLK (BCLK) pin not inverted
ok |= WriteReg(0x06, reg); //
ok |= setSampleRate(ES8311_SAMPLE_RATE48); // default
ok |= setBitsPerSample(ES8311_BITS_PER_SAMPLE16); // default
ok |= WriteReg(0x0D, 0x01); // Power up analog circuitry
ok |= WriteReg(0x0E, 0x02); // Enable analog PGA, enable ADC modulator
ok |= WriteReg(0x12, 0x00); // Power-up DAC
ok |= WriteReg(0x13, 0x10); // Enable output to HP drive
ok |= WriteReg(0x1C, 0x6A); // ADC Equalizer bypass, cancel DC offset in digital domain
ok |= WriteReg(0x37, 0x08); // Bypass DAC equalizer
return ok;
}
bool ES8311::setVolume(uint8_t volume){ // 0...100
if (volume > 100) {volume = 100;}
int reg32;
if (volume == 0) {reg32 = 0;}
else { reg32 = ((volume) * 256 / 100) - 1;}
return WriteReg(0x32, reg32);
}
uint8_t ES8311::getVolume(){
uint8_t reg32 = ReadReg(0x32);
uint8_t volume;
if (reg32 == 0) {
volume = 0;
} else {
volume = ((reg32 * 100) / 256) + 1;
}
return volume;
}
bool ES8311::setSampleRate(uint32_t sample_rate){
uint8_t reg = 0;
bool ok = true;
_mclk_hz = sample_rate * 256; // default MCLK frequency
if(sample_rate > 64000) _mclk_hz /= 2;
int coeff = get_coeff(_mclk_hz, sample_rate);
if (coeff < 0) {log_e("Invalid sample rate %i", sample_rate); return false;}
const struct _coeff_div *const selected_coeff = &coeff_div[coeff];
reg = ReadReg(0x02);
reg |= (selected_coeff->pre_div - 1) << 5;
reg |= selected_coeff->pre_multi << 3;
ok |= WriteReg(0x02, reg); // Set pre_div and pre_multi
const uint8_t reg03 = (selected_coeff->fs_mode << 6) | selected_coeff->adc_osr;
ok |= WriteReg(0x03, reg03); // Set fs_mode and adc_osr
ok |= WriteReg(0x04, selected_coeff->dac_osr); // Set dac_osr
const uint8_t reg05 = ((selected_coeff->adc_div - 1) << 4) | (selected_coeff->dac_div - 1);
ok |= WriteReg(0x05, reg05); // Set adc_div and dac_div
reg = ReadReg(0x06);
reg &= 0xE0;
if (selected_coeff->bclk_div < 19) {reg |= (selected_coeff->bclk_div - 1) << 0;}
else { reg |= (selected_coeff->bclk_div) << 0;}
ok |= WriteReg(0x06, reg); // Set bclk_div
reg = ReadReg(0x07);
reg &= 0xC0;
reg |= selected_coeff->lrck_h << 0;
ok |= WriteReg(0x07, reg); // Set lrck_h
ok |= WriteReg(0x08, selected_coeff->lrck_l); // Set lrck_l
return ok;
}
bool ES8311::setBitsPerSample(uint8_t bps){
uint8_t reg09 = ReadReg(0x09);
uint8_t reg0A = ReadReg(0x0A);
switch (bps) {
case 16: reg09 |= (3 << 2); reg0A |= (3 << 2); break;
case 18: reg09 |= (2 << 2); reg0A |= (2 << 2); break;
case 20: reg09 |= (1 << 2); reg0A |= (1 << 2); break;
case 24: reg09 |= (0 << 2); reg0A |= (0 << 2); break;
case 32: reg09 |= (4 << 2); reg0A |= (4 << 2); break;
default: return false; // Invalid bits per sample
}
bool ok = WriteReg(0x09, reg09);
ok |= WriteReg(0x0A, reg0A);
return ok;
}
bool ES8311::enableMicrophone(bool enable){
uint8_t reg = 0x1A; // enable analog MIC and max PGA gain
if (enable) {
reg |= BIT(6);
}
bool ok = WriteReg(0x17, 0xC8); // ADC_VOLUME
ok |= WriteReg(0x14, reg); // Enable MIC
return ok;
}
bool ES8311::setMicrophoneGain(uint8_t gain){ // 0...7
uint8_t reg = ReadReg(0x16);
reg &= 0xF8; // Clear gain bits
if (gain > 7) {gain = 7;}
reg |= gain; // Set gain bits
bool ok = WriteReg(0x16, gain); // ADC_VOLUME
return ok;
}
uint8_t ES8311::getMicrophoneGain(){
uint8_t reg = ReadReg(0x16);
return (reg & 0x07); // Get gain bits
}
bool ES8311::WriteReg(uint8_t reg, uint8_t val){
_TwoWireInstance->beginTransmission(ES8311_ADDR);
_TwoWireInstance->write(reg);
_TwoWireInstance->write(val);
return _TwoWireInstance->endTransmission() == 0;
}
uint8_t ES8311::ReadReg(uint8_t reg){
_TwoWireInstance->beginTransmission(ES8311_ADDR);
_TwoWireInstance->write(reg);
_TwoWireInstance->endTransmission(false);
uint8_t val = 0u;
_TwoWireInstance->requestFrom(uint16_t(ES8311_ADDR), (uint8_t)1, true);
if(_TwoWireInstance->available() >= 1){
val = _TwoWireInstance->read();
}
_TwoWireInstance->endTransmission();
return val;
}
void ES8311::read_all(){
for (uint8_t i = 0; i < 0x4A; i++) {
Serial.printf("0x%02X: 0x%02X\n", i, ReadReg(i));
}
}

View File

@@ -0,0 +1,48 @@
#pragma once
#include <Arduino.h>
#include <Wire.h>
#define ES8311_ADDR 0x18
#define ES8311_SAMPLE_RATE48 48000
#define ES8311_BITS_PER_SAMPLE16 16
struct _coeff_div { /* Clock coefficient structure */
uint32_t mclk; /* mclk frequency */
uint32_t rate; /* sample rate */
uint8_t pre_div; /* the pre divider with range from 1 to 8 */
uint8_t pre_multi; /* the pre multiplier with 0: 1x, 1: 2x, 2: 4x, 3: 8x selection */
uint8_t adc_div; /* adcclk divider */
uint8_t dac_div; /* dacclk divider */
uint8_t fs_mode; /* double speed or single speed, =0, ss, =1, ds */
uint8_t lrck_h; /* adclrck divider and daclrck divider */
uint8_t lrck_l;
uint8_t bclk_div; /* sclk divider */
uint8_t adc_osr; /* adc osr */
uint8_t dac_osr; /* dac osr */
};
class ES8311{
private:
TwoWire *_TwoWireInstance = NULL; // TwoWire Instance
uint32_t _mclk_hz = 48000 * 256; // default MCLK frequency
public:
// Constructor.
ES8311(TwoWire *TwoWireInstance = &Wire);
~ES8311();
bool begin(int32_t sda, int32_t scl, uint32_t frequency);
bool setVolume(uint8_t volume);
uint8_t getVolume();
bool setSampleRate(uint32_t sample_rate);
bool setBitsPerSample(uint8_t bps);
bool enableMicrophone(bool enable);
bool setMicrophoneGain(uint8_t gain);
uint8_t getMicrophoneGain();
void read_all();
protected:
int get_coeff(uint32_t mclk, uint32_t rate);
bool WriteReg(uint8_t reg, uint8_t val);
uint8_t ReadReg(uint8_t reg);
};

View File

@@ -0,0 +1,62 @@
#include "Arduino.h"
#include "Audio.h"
#include "WiFi.h"
#include "es8311.h"
#include "Wire.h"
// Pins: Waveshare ESP32-P4-Module-DEV-KIT and ESP32-P4-NANO High-performance Development Board
#define I2S_DOUT 9 // DSDIN pin(es8311)
#define I2S_BCLK 12 // SCLK
#define I2S_MCLK 13
#define I2S_LRC 10 // LRCK
#define I2C_SCL 8
#define I2C_SDA 7
#define PA_ENABLE 53
Audio audio;
ES8311 es;
String ssid = "*****";
String password = "*****";
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
Serial.begin(115200);
Serial.print("\n\n");
Serial.println("----------------------------------");
Serial.printf("ESP32 Chip: %s\n", ESP.getChipModel());
Serial.printf("Arduino Version: %d.%d.%d\n", ESP_ARDUINO_VERSION_MAJOR, ESP_ARDUINO_VERSION_MINOR, ESP_ARDUINO_VERSION_PATCH);
Serial.printf("ESP-IDF Version: %d.%d.%d\n", ESP_IDF_VERSION_MAJOR, ESP_IDF_VERSION_MINOR, ESP_IDF_VERSION_PATCH);
Serial.printf("ARDUINO_LOOP_STACK_SIZE %d words (32 bit)\n", CONFIG_ARDUINO_LOOP_STACK_SIZE);
Serial.println("----------------------------------");
Serial.print("\n\n");
WiFi.begin(ssid.c_str(), password.c_str());
while (WiFi.status() != WL_CONNECTED) {delay(1500); Serial.print(".");}
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT, I2S_MCLK);
audio.setVolume(21); // default 0...21
pinMode(PA_ENABLE, OUTPUT);
digitalWrite(PA_ENABLE, HIGH);
if(!es.begin(I2C_SDA, I2C_SCL, 400000)) log_e("ES8311 begin failed");
es.setVolume(50);
es.setBitsPerSample(16);
// es.setSampleRate(22050);
// es.read_all();
// audio.connecttohost("http://www.wdr.de/wdrlive/media/einslive.m3u");
audio.connecttohost("http://stream.antennethueringen.de/live/aac-64/stream.antennethueringen.de/"); // aac
}
void loop() {
audio.loop();
vTaskDelay(1);
}

View File

@@ -0,0 +1,270 @@
#include <Arduino.h>
#include "ES8388.h"
#include <Wire.h>
#define ES8388_ADDR 0x10
/* ES8388 register */
#define ES8388_CONTROL1 0x00
#define ES8388_CONTROL2 0x01
#define ES8388_CHIPPOWER 0x02
#define ES8388_ADCPOWER 0x03
#define ES8388_DACPOWER 0x04
#define ES8388_CHIPLOPOW1 0x05
#define ES8388_CHIPLOPOW2 0x06
#define ES8388_ANAVOLMANAG 0x07
#define ES8388_MASTERMODE 0x08
/* ADC */
#define ES8388_ADCCONTROL1 0x09
#define ES8388_ADCCONTROL2 0x0a
#define ES8388_ADCCONTROL3 0x0b
#define ES8388_ADCCONTROL4 0x0c
#define ES8388_ADCCONTROL5 0x0d
#define ES8388_ADCCONTROL6 0x0e
#define ES8388_ADCCONTROL7 0x0f
#define ES8388_ADCCONTROL8 0x10
#define ES8388_ADCCONTROL9 0x11
#define ES8388_ADCCONTROL10 0x12
#define ES8388_ADCCONTROL11 0x13
#define ES8388_ADCCONTROL12 0x14
#define ES8388_ADCCONTROL13 0x15
#define ES8388_ADCCONTROL14 0x16
/* DAC */
#define ES8388_DACCONTROL1 0x17
#define ES8388_DACCONTROL2 0x18
#define ES8388_DACCONTROL3 0x19
#define ES8388_DACCONTROL4 0x1a
#define ES8388_DACCONTROL5 0x1b
#define ES8388_DACCONTROL6 0x1c
#define ES8388_DACCONTROL7 0x1d
#define ES8388_DACCONTROL8 0x1e
#define ES8388_DACCONTROL9 0x1f
#define ES8388_DACCONTROL10 0x20
#define ES8388_DACCONTROL11 0x21
#define ES8388_DACCONTROL12 0x22
#define ES8388_DACCONTROL13 0x23
#define ES8388_DACCONTROL14 0x24
#define ES8388_DACCONTROL15 0x25
#define ES8388_DACCONTROL16 0x26
#define ES8388_DACCONTROL17 0x27
#define ES8388_DACCONTROL18 0x28
#define ES8388_DACCONTROL19 0x29
#define ES8388_DACCONTROL20 0x2a
#define ES8388_DACCONTROL21 0x2b
#define ES8388_DACCONTROL22 0x2c
#define ES8388_DACCONTROL23 0x2d
#define ES8388_DACCONTROL24 0x2e
#define ES8388_DACCONTROL25 0x2f
#define ES8388_DACCONTROL26 0x30
#define ES8388_DACCONTROL27 0x31
#define ES8388_DACCONTROL28 0x32
#define ES8388_DACCONTROL29 0x33
#define ES8388_DACCONTROL30 0x34
bool ES8388::write_reg(uint8_t slave_add, uint8_t reg_add, uint8_t data)
{
Wire.beginTransmission(slave_add);
Wire.write(reg_add);
Wire.write(data);
return Wire.endTransmission() == 0;
}
bool ES8388::read_reg(uint8_t slave_add, uint8_t reg_add, uint8_t &data)
{
bool retval = false;
Wire.beginTransmission(slave_add);
Wire.write(reg_add);
Wire.endTransmission(false);
Wire.requestFrom((uint16_t)slave_add, (uint8_t)1, true);
if (Wire.available() >= 1)
{
data = Wire.read();
retval = true;
}
return retval;
}
bool ES8388::begin(int32_t sda, int32_t scl, uint32_t frequency)
{
bool res = identify(sda, scl, frequency);
if (res == true)
{
/* mute DAC during setup, power up all systems, slave mode */
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL3, 0x04);
res &= write_reg(ES8388_ADDR, ES8388_CONTROL2, 0x50);
res &= write_reg(ES8388_ADDR, ES8388_CHIPPOWER, 0x00);
res &= write_reg(ES8388_ADDR, ES8388_MASTERMODE, 0x00);
/* power up DAC and enable LOUT1+2 / ROUT1+2, ADC sample rate = DAC sample rate */
res &= write_reg(ES8388_ADDR, ES8388_DACPOWER, 0x3e);
res &= write_reg(ES8388_ADDR, ES8388_CONTROL1, 0x12);
/* DAC I2S setup: 16 bit word length, I2S format; MCLK / Fs = 256*/
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL1, 0x18);
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL2, 0x02);
/* DAC to output route mixer configuration: ADC MIX TO OUTPUT */
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL16, 0x1B);
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL17, 0x90);
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL20, 0x90);
/* DAC and ADC use same LRCK, enable MCLK input; output resistance setup */
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL21, 0x80);
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL23, 0x00);
/* DAC volume control: 0dB (maximum, unattenuated) */
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL5, 0x00);
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL4, 0x00);
/* power down ADC while configuring; volume: +9dB for both channels */
res &= write_reg(ES8388_ADDR, ES8388_ADCPOWER, 0xff);
res &= write_reg(ES8388_ADDR, ES8388_ADCCONTROL1, 0x88); // +24db
/* select LINPUT2 / RINPUT2 as ADC input; stereo; 16 bit word length, format right-justified, MCLK / Fs = 256 */
res &= write_reg(ES8388_ADDR, ES8388_ADCCONTROL2, 0xf0); // 50
res &= write_reg(ES8388_ADDR, ES8388_ADCCONTROL3, 0x80); // 00
res &= write_reg(ES8388_ADDR, ES8388_ADCCONTROL4, 0x0e);
res &= write_reg(ES8388_ADDR, ES8388_ADCCONTROL5, 0x02);
/* set ADC volume */
res &= write_reg(ES8388_ADDR, ES8388_ADCCONTROL8, 0x20);
res &= write_reg(ES8388_ADDR, ES8388_ADCCONTROL9, 0x20);
/* set LOUT1 / ROUT1 volume: 0dB (unattenuated) */
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL24, 0x1e);
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL25, 0x1e);
/* set LOUT2 / ROUT2 volume: 0dB (unattenuated) */
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL26, 0x1e);
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL27, 0x1e);
/* power up and enable DAC; power up ADC (no MIC bias) */
res &= write_reg(ES8388_ADDR, ES8388_DACPOWER, 0x3c);
res &= write_reg(ES8388_ADDR, ES8388_DACCONTROL3, 0x00);
res &= write_reg(ES8388_ADDR, ES8388_ADCPOWER, 0x00);
/* set up MCLK) */
#ifdef FUNC_GPIO0_CLK_OUT1
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0_CLK_OUT1);
#endif
WRITE_PERI_REG(PIN_CTRL, 0xFFF0);
}
return res;
}
/**
* @brief (un)mute one of the two outputs or main dac output of the ES8388 by switching of the output register bits. Does not really mute the selected output, causes an attenuation.
* hence should be used in conjunction with appropriate volume setting. Main dac output mute does mute both outputs
*
* @param out
* @param muted
*/
void ES8388::mute(const ES8388_OUT out, const bool muted)
{
uint8_t reg_addr;
uint8_t mask_mute;
uint8_t mask_val;
switch (out)
{
case ES_OUT1:
reg_addr = ES8388_DACPOWER;
mask_mute = (3 << 4);
mask_val = muted ? 0 : mask_mute;
break;
case ES_OUT2:
reg_addr = ES8388_DACPOWER;
mask_mute = (3 << 2);
mask_val = muted ? 0 : mask_mute;
break;
case ES_MAIN:
default:
reg_addr = ES8388_DACCONTROL3;
mask_mute = 1 << 2;
mask_val = muted ? mask_mute : 0;
break;
}
uint8_t reg;
if (read_reg(ES8388_ADDR, reg_addr, reg))
{
reg = (reg & ~mask_mute) | (mask_val & mask_mute);
write_reg(ES8388_ADDR, reg_addr, reg);
}
}
/**
* @brief Set volume gain for the main dac, or for one of the two output channels. Final gain = main gain + out channel gain
*
* @param out which gain setting to control
* @param vol 0-100 (100 is max)
*/
void ES8388::volume(const ES8388_OUT out, const uint8_t vol)
{
const uint32_t max_vol = 100; // max input volume value
const int32_t max_vol_val = out == ES8388_OUT::ES_MAIN ? 96 : 0x21; // max register value for ES8388 out volume
uint8_t lreg = 0, rreg = 0;
switch (out)
{
case ES_MAIN:
lreg = ES8388_DACCONTROL4;
rreg = ES8388_DACCONTROL5;
break;
case ES_OUT1:
lreg = ES8388_DACCONTROL24;
rreg = ES8388_DACCONTROL25;
break;
case ES_OUT2:
lreg = ES8388_DACCONTROL26;
rreg = ES8388_DACCONTROL27;
break;
}
uint8_t vol_val = vol > max_vol ? max_vol_val : (max_vol_val * vol) / max_vol;
// main dac volume control is reverse scale (lowest value is loudest)
// hence we reverse the calculated value
if (out == ES_MAIN)
{
vol_val = max_vol_val - vol_val;
}
write_reg(ES8388_ADDR, lreg, vol_val);
write_reg(ES8388_ADDR, rreg, vol_val);
}
void ES8388::SetVolumeSpeaker(uint8_t vol) {
vol = vol * 1.6;
volume(ES_OUT1, vol);
volume(ES_MAIN, 100);
}
void ES8388::SetVolumeHeadphone(uint8_t vol){
vol = vol * 1.6;
volume(ES_OUT2, vol);
volume(ES_MAIN, 100);
}
/**
* @brief Test if device with I2C address for ES8388 is connected to the I2C bus
*
* @param sda which pin to use for I2C SDA
* @param scl which pin to use for I2C SCL
* @param frequency which frequency to use as I2C bus frequency
* @return true device was found
* @return false device was not found
*/
bool ES8388::identify(int32_t sda, int32_t scl, uint32_t frequency)
{
Wire.begin(sda, scl, frequency);
Wire.beginTransmission(ES8388_ADDR);
return Wire.endTransmission() == 0;
}

View File

@@ -0,0 +1,27 @@
#pragma once
#include <stdint.h>
class ES8388
{
bool write_reg(uint8_t slave_add, uint8_t reg_add, uint8_t data);
bool read_reg(uint8_t slave_add, uint8_t reg_add, uint8_t &data);
bool identify(int32_t sda, int32_t scl, uint32_t frequency);
public:
bool begin(int32_t sda = -1, int32_t scl = -1, uint32_t frequency = 400000U);
enum ES8388_OUT
{
ES_MAIN, // this is the DAC output volume (both outputs)
ES_OUT1, // this is the additional gain for OUT1
ES_OUT2 // this is the additional gain for OUT2
};
void SetVolumeSpeaker(uint8_t vol);
void SetVolumeHeadphone(uint8_t vol);
void mute(const ES8388_OUT out, const bool muted);
void volume(const ES8388_OUT out, const uint8_t vol);
};

View File

@@ -0,0 +1,109 @@
#include "Arduino.h"
#include "WiFi.h"
#include "SPI.h"
#include "SD.h"
#include "FS.h"
#include "Wire.h"
#include "ES8388.h"
#include "Audio.h"
// SPI GPIOs
#define SD_CS 13
#define SPI_MOSI 15
#define SPI_MISO 2
#define SPI_SCK 14
// I2S GPIOs, the names refer on ES8388, AS1 Audio Kit V2.2 3378
#define I2S_DSIN 35 // pin not used
#define I2S_BCLK 27
#define I2S_LRC 25
#define I2S_MCLK 0
#define I2S_DOUT 26
// I2C GPIOs
#define IIC_CLK 32
#define IIC_DATA 33
// buttons
// #define BUTTON_2_PIN 13 // shared mit SPI_CS
#define BUTTON_3_PIN 19
#define BUTTON_4_PIN 23
#define BUTTON_5_PIN 18 // Stop
#define BUTTON_6_PIN 5 // Play
// amplifier enable
#define GPIO_PA_EN 21
//Switch S1: 1-OFF, 2-ON, 3-ON, 4-OFF, 5-OFF
String ssid = "*****";
String password = "*****";
ES8388 dac; // ES8388 (new board)
int volume = 40; // 0...100
Audio audio;
//#####################################################################
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
Serial.begin(115200);
Serial.println("\r\nReset");
Serial.printf_P(PSTR("Free mem=%l\n"), ESP.getFreeHeap());
pinMode(SD_CS, OUTPUT);
digitalWrite(SD_CS, HIGH);
SPI.begin(SPI_SCK, SPI_MISO, SPI_MOSI);
SPI.setFrequency(1000000);
SD.begin(SD_CS);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), password.c_str());
while (WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(100);
}
Serial.printf_P(PSTR("Connected\r\nRSSI: "));
Serial.print(WiFi.RSSI());
Serial.print(" IP: ");
Serial.println(WiFi.localIP());
Serial.printf("Connect to DAC codec... ");
while (not dac.begin(IIC_DATA, IIC_CLK)){
Serial.printf("Failed!\n");
delay(1000);
}
Serial.printf("OK\n");
dac.SetVolumeSpeaker(volume);
dac.SetVolumeHeadphone(volume);
// ac.DumpRegisters();
// Enable amplifier
pinMode(GPIO_PA_EN, OUTPUT);
digitalWrite(GPIO_PA_EN, HIGH);
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT, I2S_MCLK);
audio.setVolume(10); // 0...21
audio.connecttohost("http://mp3channels.webradio.antenne.de:80/oldies-but-goldies");
// audio.connecttohost("http://dg-rbb-http-dus-dtag-cdn.cast.addradio.de/rbb/antennebrandenburg/live/mp3/128/stream.mp3");
// audio.connecttospeech("Wenn die Hunde schlafen, kann der Wolf gut Schafe stehlen.", "de");
}
//-----------------------------------------------------------------------
void loop(){
vTaskDelay(1);
audio.loop();
}

View File

@@ -0,0 +1,19 @@
# 32 bit ES9038
For those who have a board with a 32bit DAC
[DJ202](https://github.com/dj202) sent us a solution:
There are some great sounding and cheap 32 bit decoders available like boards with the ES9038Q2M that don't work because the library outputs 16 bits data.
You only need to change 3 lines lines of code to change it to 32bit:
## Audio.cpp
in Audio::Audio
````c++
m_i2s_std_cfg.slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO);
in Audio::resampleTo48kStereo:
m_samplesBuff48K[outputIndex * 2] = clipToInt16(outLeft);
m_samplesBuff48K[outputIndex * 2 + 1] = 0x00;
m_samplesBuff48K[outputIndex * 2 + 2] = clipToInt16(outRight);
m_samplesBuff48K[outputIndex * 2 + 3] = 0x00;
````

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

View File

@@ -0,0 +1,59 @@
// Copied from https://github.com/LilyGO/TTGO-TAudio/issues/12
// Required Libraries (Download zips and add to the Arduino IDE library).
#include "Arduino.h"
#include <WM8978.h> // https://github.com/CelliesProjects/wm8978-esp32
#include <Audio.h> // https://github.com/schreibfaul1/ESP32-audioI2S
// T-Audio 1.6 WM8978 I2C pins.
#define I2C_SDA 19
#define I2C_SCL 18
// T-Audio 1.6 WM8978 I2S pins.
#define I2S_BCK 33
#define I2S_WS 25
#define I2S_DOUT 26
// T-Audio 1.6 WM8978 MCLK gpio number
#define I2S_MCLKPIN 0
Audio audio;
WM8978 dac;
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
Serial.begin(115200);
// Setup wm8978 I2C interface.
if (!dac.begin(I2C_SDA, I2C_SCL)) {
ESP_LOGE(TAG, "Error setting up dac: System halted.");
while (1) delay(100);
}
// Select I2S pins
audio.setPinout(I2S_BCK, I2S_WS, I2S_DOUT);
audio.i2s_mclk_pin_select(I2S_MCLKPIN);
// WiFi Settings here.
WiFi.begin("EnterSSIDHere", "EnterPasswordHere");
while (!WiFi.isConnected()) {
delay(10);
}
ESP_LOGI(TAG, "Connected. Starting MP3...");
// Enter your Icecast station URL here.
audio.setVolume(21);
audio.connecttohost("http://hestia2.cdnstream.com/1458_128");
// Volume control.
dac.setSPKvol(63); // Change volume here for board speaker output (Max 63).
dac.setHPvol(63, 63); // Change volume here for headphone jack left, right channel.
}
void loop() {
vTaskDelay(1);
audio.loop();
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 271 KiB

View File

@@ -0,0 +1,92 @@
#include "Arduino.h"
#include "Audio.h"
#include "ETH.h"
#ifdef CONFIG_IDF_TARGET_ESP32
#define I2S_DOUT 25
#define I2S_BCLK 27
#define I2S_LRC 26
#define ETH_PHY_TYPE ETH_PHY_TLK110
#define ETH_PHY_MDC 23
#define ETH_PHY_MDIO 18
#define ETH_PHY_POWER -1
#define ETH_CLK_MODE ETH_CLOCK_GPIO0_IN
#endif
#ifdef CONFIG_IDF_TARGET_ESP32P4
#define I2S_DOUT 22
#define I2S_BCLK 20
#define I2S_LRC 21
#define ETH_PHY_TYPE ETH_PHY_TLK110
#define ETH_PHY_MDC 31
#define ETH_PHY_MDIO 52
#define ETH_PHY_POWER 51
#define ETH_CLK_MODE EMAC_CLK_EXT_IN
#endif
Audio audio;
static bool eth_connected = false;
void onEvent(arduino_event_id_t event) {
switch (event) {
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH Started");
// The hostname must be set after the interface is started, but needs
// to be set before DHCP, so set it from the event handler thread.
ETH.setHostname("esp32-ethernet");
break;
case ARDUINO_EVENT_ETH_CONNECTED: Serial.println("ETH Connected"); break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH Got IP");
Serial.println(ETH);
eth_connected = true;
break;
case ARDUINO_EVENT_ETH_LOST_IP:
Serial.println("ETH Lost IP");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH Disconnected");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH Stopped");
eth_connected = false;
break;
default: break;
}
}
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
Serial.begin(115200);
Serial.print("A\n\n");
Serial.println("----------------------------------");
Serial.printf("ESP32 Chip: %s\n", ESP.getChipModel());
Serial.printf("Arduino Version: %d.%d.%d\n", ESP_ARDUINO_VERSION_MAJOR, ESP_ARDUINO_VERSION_MINOR, ESP_ARDUINO_VERSION_PATCH);
Serial.printf("ESP-IDF Version: %d.%d.%d\n", ESP_IDF_VERSION_MAJOR, ESP_IDF_VERSION_MINOR, ESP_IDF_VERSION_PATCH);
Serial.printf("ARDUINO_LOOP_STACK_SIZE %d words (32 bit)\n", CONFIG_ARDUINO_LOOP_STACK_SIZE);
Serial.println("----------------------------------");
Serial.print("\n\n");
Network.onEvent(onEvent);
ETH.begin();
while (!eth_connected) delay(100);
Serial.println("ETH Connected");
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(21); // default 0...21
audio.connecttohost("http://stream.antennethueringen.de/live/aac-64/stream.antennethueringen.de/"); // aac
pinMode(53, OUTPUT);
digitalWrite(53, HIGH);
}
void loop() {
audio.loop();
vTaskDelay(1);
}

View File

@@ -0,0 +1,74 @@
#include "Arduino.h" // >= Arduino V3
#include <ETH.h>
#include <SPI.h>
#include "Audio.h"
Audio audio;
#define USE_TWO_ETH_PORTS 0
#define ETH_PHY_TYPE ETH_PHY_W5500
// GPIOs
#define ETH_PHY_ADDR 1
#define ETH_PHY_CS 3
#define ETH_PHY_IRQ 8
#define ETH_PHY_RST 4
#define ETH_SPI_SCK 7
#define ETH_SPI_MISO 6
#define ETH_SPI_MOSI 5
#define I2S_DOUT 12
#define I2S_BCLK 13
#define I2S_LRC 14
static bool eth_connected = false;
void onEvent(arduino_event_id_t event, arduino_event_info_t info) {
switch (event) {
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH Started");
ETH.setHostname("esp32-eth0"); //set eth hostname here
break;
case ARDUINO_EVENT_ETH_CONNECTED: Serial.println("ETH Connected"); break;
case ARDUINO_EVENT_ETH_GOT_IP: Serial.printf("ETH Got IP: '%s'\n", esp_netif_get_desc(info.got_ip.esp_netif)); Serial.println(ETH);
eth_connected = true;
break;
case ARDUINO_EVENT_ETH_LOST_IP:
Serial.println("ETH Lost IP");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH Disconnected");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH Stopped");
eth_connected = false;
break;
default: break;
}
}
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
Serial.begin(115200);
Serial.print("\n\n");
Network.onEvent(onEvent);
SPI.begin(ETH_SPI_SCK, ETH_SPI_MISO, ETH_SPI_MOSI);
ETH.begin(ETH_PHY_TYPE, ETH_PHY_ADDR, ETH_PHY_CS, ETH_PHY_IRQ, ETH_PHY_RST, SPI);
while (!eth_connected) delay(100);
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(21); // default 0...21
audio.connecttohost("https://wdr-wdr2-ruhrgebiet.icecastssl.wdr.de/wdr/wdr2/ruhrgebiet/mp3/128/stream.mp3"); // mp3
}
void loop(){
audio.loop();
vTaskDelay(5 /portTICK_PERIOD_MS);
}

View File

@@ -0,0 +1,88 @@
#include "Arduino.h"
#include "Audio.h"
#include "SD.h"
#include "FS.h"
// Digital I/O used
#define SD_CS 5
#define SPI_MOSI 2
#define SPI_MISO 4
#define SPI_SCK 17
#define I2S_DOUT 12
#define I2S_BCLK 14
#define I2S_LRC 15
#define ETH_PHY_TYPE ETH_PHY_LAN8720
#define ETH_PHY_MDC 23
#define ETH_PHY_MDIO 18
#ifdef CONFIG_IDF_TARGET_ESP32
#define ETH_CLK_MODE ETH_CLOCK_GPIO0_IN
#endif
#ifdef CONFIG_IDF_TARGET_ESP32P4
#define ETH_CLK_MODE EMAC_CLK_EXT_IN
#endif
#include "ETH.h"
Audio audio;
static bool eth_connected = false;
void onEvent(arduino_event_id_t event) {
switch (event) {
case ARDUINO_EVENT_ETH_START:
Serial.println("ETH Started");
// The hostname must be set after the interface is started, but needs
// to be set before DHCP, so set it from the event handler thread.
ETH.setHostname("esp32-ethernet");
break;
case ARDUINO_EVENT_ETH_CONNECTED: Serial.println("ETH Connected"); break;
case ARDUINO_EVENT_ETH_GOT_IP:
Serial.println("ETH Got IP");
Serial.println(ETH);
eth_connected = true;
break;
case ARDUINO_EVENT_ETH_LOST_IP:
Serial.println("ETH Lost IP");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_DISCONNECTED:
Serial.println("ETH Disconnected");
eth_connected = false;
break;
case ARDUINO_EVENT_ETH_STOP:
Serial.println("ETH Stopped");
eth_connected = false;
break;
default: break;
}
}
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
pinMode(SD_CS, OUTPUT); digitalWrite(SD_CS, HIGH);
SPI.begin(SPI_SCK, SPI_MISO, SPI_MOSI);
Serial.begin(115200);
SD.begin(SD_CS);
Network.onEvent(onEvent);
ETH.begin();
while (!eth_connected) delay(100);
// Eth Connected,
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(21); // default 0...21
audio.connecttohost("https://wdr-wdr2-ruhrgebiet.icecastssl.wdr.de/wdr/wdr2/ruhrgebiet/mp3/128/stream.mp3"); // mp3
}
void loop(){
vTaskDelay(1);
audio.loop();
}

View File

@@ -0,0 +1,159 @@
#pragma once
#include <vector>
#include <cstdint>
#include <cstring>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <driver/i2s_std.h>
#include "esp_log.h"
class AudioResampleBuffer {
public:
static constexpr size_t FIFO_SIZE_BYTES = 16384; // Muss Vielfaches von 4 sein (Stereo, 16 Bit)
static constexpr size_t I2S_BLOCK_SIZE = 512; // DMA Blockgröße
AudioResampleBuffer()
:fifoWrite(0), fifoRead(0), m_resampleCursor(0.0f) {
memset(fifo, 0, sizeof(fifo));
memset(m_inputHistory, 0, sizeof(m_inputHistory));
}
void setChannelHandle(i2s_chan_handle_t i2sHandle){
m_i2s = i2sHandle;
}
// Set the input samplerates (updated by the LRCK monitoring)
void setInputSamplerate(uint32_t samplerate) {
if (samplerate == 8000 || samplerate == 22050 || samplerate == 44100 || samplerate == 48000) {
m_sampleRate = samplerate;
ESP_LOGI("ResampleBuffer", "Input samplerate set to %u Hz", samplerate);
} else {
ESP_LOGW("ResampleBuffer", "Invalid samplerate %u Hz, defaulting to 44100 Hz", samplerate);
m_sampleRate = 44100;
}
}
// Muss zyklisch aufgerufen werden (z. B. aus Task)
void loopResample() {
alignas(4) uint8_t i2sBuf[I2S_BLOCK_SIZE];
size_t bytesRead = 0;
if (i2s_channel_read(m_i2s, i2sBuf, I2S_BLOCK_SIZE, &bytesRead, 50) != ESP_OK || bytesRead == 0)
return;
size_t inSamples = bytesRead / 4; // Stereo, 16 Bit
int16_t* inData = reinterpret_cast<int16_t*>(i2sBuf);
int16_t resampled[1024];
size_t outSamples = resampleTo441Stereo(inData, inSamples, resampled);
size_t outBytes = outSamples * 4;
if (fifoFree() >= outBytes) {
fifoWriteBytes(reinterpret_cast<uint8_t*>(resampled), outBytes);
} else {
vTaskDelay(100);
// ESP_LOGW("ResampleBuffer", "FIFO voll, Daten verworfen %i Bytes", outBytes - fifoFree());
}
}
// Bluetooth Callback: muss exakt "bytes" liefern
int32_t getData(uint8_t* data, int32_t bytes) {
while (fifoAvailable() < static_cast<size_t>(bytes)) {
vTaskDelay(1);
}
fifoReadBytes(data, bytes);
return bytes;
}
private:
private:
i2s_chan_handle_t m_i2s;
uint8_t fifo[FIFO_SIZE_BYTES];
size_t fifoWrite;
size_t fifoRead;
float m_sampleRate = 44100.0f;
float m_resampleCursor;
int16_t m_inputHistory[6]; // 3 Stereo-Samples
size_t fifoAvailable() const {
return (fifoWrite + FIFO_SIZE_BYTES - fifoRead) % FIFO_SIZE_BYTES;
}
size_t fifoFree() const {
return FIFO_SIZE_BYTES - fifoAvailable() - 1;
}
void fifoWriteBytes(const uint8_t* data, size_t len) {
for (size_t i = 0; i < len; ++i) {
fifo[fifoWrite] = data[i];
fifoWrite = (fifoWrite + 1) % FIFO_SIZE_BYTES;
}
}
void fifoReadBytes(uint8_t* out, size_t len) {
for (size_t i = 0; i < len; ++i) {
out[i] = fifo[fifoRead];
fifoRead = (fifoRead + 1) % FIFO_SIZE_BYTES;
}
}
// Catmull-Rom Spline Resampling von 48 kHz auf 44,1 kHz
size_t resampleTo441Stereo(const int16_t* input, size_t inputSamples, int16_t* output) {
float ratio = m_sampleRate / 44100.0f;
float cursor = m_resampleCursor;
size_t extendedSamples = inputSamples + 3;
std::vector<int16_t> extendedInput(extendedSamples * 2);
memcpy(&extendedInput[0], m_inputHistory, 6 * sizeof(int16_t));
memcpy(&extendedInput[6], input, inputSamples * 2 * sizeof(int16_t));
size_t outputIndex = 0;
auto catmullRom = [](float t, float xm1, float x0, float x1, float x2) {
return 0.5f * (
(2.0f * x0) +
(-xm1 + x1) * t +
(2.0f * xm1 - 5.0f * x0 + 4.0f * x1 - x2) * t * t +
(-xm1 + 3.0f * x0 - 3.0f * x1 + x2) * t * t * t
);
};
auto clip = [](float v) -> int16_t {
return v > 32767.0f ? 32767 : (v < -32768.0f ? -32768 : static_cast<int16_t>(v));
};
for (size_t inIdx = 1; inIdx < extendedSamples - 2; ++inIdx) {
int16_t xm1_l = extendedInput[(inIdx - 1) * 2];
int16_t x0_l = extendedInput[(inIdx + 0) * 2];
int16_t x1_l = extendedInput[(inIdx + 1) * 2];
int16_t x2_l = extendedInput[(inIdx + 2) * 2];
int16_t xm1_r = extendedInput[(inIdx - 1) * 2 + 1];
int16_t x0_r = extendedInput[(inIdx + 0) * 2 + 1];
int16_t x1_r = extendedInput[(inIdx + 1) * 2 + 1];
int16_t x2_r = extendedInput[(inIdx + 2) * 2 + 1];
while (cursor < 1.0f) {
float t = cursor;
output[outputIndex * 2] = clip(catmullRom(t, xm1_l, x0_l, x1_l, x2_l));
output[outputIndex * 2 + 1] = clip(catmullRom(t, xm1_r, x0_r, x1_r, x2_r));
++outputIndex;
cursor += ratio;
}
cursor -= 1.0f;
}
// Historie sichern
for (int i = 0; i < 3; ++i) {
size_t idx = inputSamples - 3 + i;
m_inputHistory[i * 2] = input[idx * 2];
m_inputHistory[i * 2 + 1] = input[idx * 2 + 1];
}
m_resampleCursor = cursor;
return outputIndex;
}
};

View File

@@ -0,0 +1,26 @@
**I2S Bluetooth Transmitter**
Such boards can be connected directly to the I2S output: <br>
But to do this, `#define SR_48K` must be activated in Audio.h so that the I2S frequency is always 48KHz.
![image](https://github.com/user-attachments/assets/9e2d8066-f41e-41eb-9db5-e7b7a6e554e8)
If you still have an old ESP32 in your box, you can use it to simulate this board. PSRAM is not required.
The BT transmitter is the slave and is connected in this way, the DAC serves as an analogue output, but is not necessary.
![image](https://github.com/user-attachments/assets/ac17cfa3-e473-4750-94ce-ee218827b3c3)
The ESP32-A2DP library is used by P. Schatzmann, https://github.com/pschatzmann/ESP32-A2DP.git
As the I2S output of the audioI2S library not always outputs 44.1KHz, it is scaled internally to 44.1KHz for compatibility. 8000Hz, 22050Hz, 44100Hz and 48000Hz are possible.
This is necessary because the ESP32 BT library expects this sample rate. This means that old BT devices can also be used.
It doesn't matter what sample rate the audio source has.
![image](https://github.com/user-attachments/assets/0009dd9d-96b2-48b7-a6cc-bfc45dbc94d0)
Test circuit: the audioI2S library is running on the left, the BT transmitter on the right

View File

@@ -0,0 +1,168 @@
#include "Arduino.h"
/*
I2S Bluetooth Transmitter
Can be connected to an I2S Master.Sampling rate must be 48KHz
Include PSchatzmann /ESP32-A2DP https://github.com/pschatzmann/ESP32-A2DP.git
*/
#include "Arduino.h"
#include "esp_bt.h"
#include "BluetoothA2DPCommon.h"
#include "BluetoothA2DPSource.h"
#include <driver/i2s_std.h>
#include "AudioResampler.hpp"
#define RX_I2S_DIN 25 // connect with I2S Master (signal dout)
#define RX_I2S_BCLK 27 // connect with I2S Master (bit clock)
#define RX_I2S_LRC 26 // connect with I2S Master (word select)
#define MEASUREMENT_INTERVAL_MS 100 // Messintervall in ms
#define TOLERANCE_PERCENT 5 // Toleranz für Schwankungen in %
static volatile uint32_t lrck_count = 0;
static uint32_t current_samplerate = 0;
BluetoothA2DPSource a2dp_source;
AudioResampleBuffer resampler;
char BT_SINK_NAME[] = " Pebble V3\r\n"; // set your sink devicename here
//char BT_SINK_NAME[] = "Manhattan-165327";
i2s_chan_handle_t i2s_rx_handle = {};
i2s_chan_config_t i2s_chan_cfg = {}; // stores I2S channel values
i2s_std_config_t i2s_std_cfg = {}; // stores I2S driver values
const i2s_port_t i2s_num = I2S_NUM_0;
//--------------------------------Recognise Host Samplerate-------------------------------------------------------------------------------------
// Interrupt-Handler for LRCK-Pulse
void IRAM_ATTR lrck_interrupt_handler(void *arg) {
lrck_count+=1;
}
// Initialize GPIO interrupt for LRCK
void init_lrck_monitor() {
gpio_config_t io_conf = {
.pin_bit_mask = (1ULL << RX_I2S_LRC),
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_DISABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_POSEDGE // Interrupt bei steigender Flanke
};
gpio_config(&io_conf);
gpio_install_isr_service(0);
gpio_isr_handler_add((gpio_num_t)RX_I2S_LRC, lrck_interrupt_handler, NULL);
}
// calculate samplerates based on LRCK counter
uint32_t measure_samplerate() {
lrck_count = 0;
vTaskDelay(MEASUREMENT_INTERVAL_MS / portTICK_PERIOD_MS);
uint32_t samplerate = (lrck_count * 1000) / MEASUREMENT_INTERVAL_MS; // Hz
return samplerate;
}
// check whether samplerates are one of the expected values
uint32_t map_to_valid_samplerate(uint32_t measured) {
const uint32_t valid_rates[] = {8000, 22050, 44100, 48000};
const uint32_t num_rates = sizeof(valid_rates) / sizeof(valid_rates[0]);
uint32_t closest_rate = valid_rates[0];
int min_diff = abs((int)measured - (int)valid_rates[0]);
for (int i = 1; i < num_rates; i++) {
int diff = abs((int)measured - (int)valid_rates[i]);
if (diff < min_diff) {
min_diff = diff;
closest_rate = valid_rates[i];
}
}
// check tolerance
if (min_diff <= (closest_rate * TOLERANCE_PERCENT / 100)) {
return closest_rate;
}
return 0; // Invalid samplerates
}
// task to monitor the samplerates
void samplerate_monitor_task(void *pvParameters) {
init_lrck_monitor();
while (1) {
uint32_t new_samplerate = map_to_valid_samplerate(measure_samplerate());
if (new_samplerate != 0 && new_samplerate != current_samplerate) {
log_w("Samplerate changed to %u Hz", new_samplerate);
resampler.setInputSamplerate(new_samplerate);
// response to samplerates change
if (new_samplerate == 48000) {
log_w("Activating resampling to 44100 Hz");
// activate resampling logic here
} else if (new_samplerate == 44100) {
log_w("No resampling needed");
// deactivate Resampling, direct transmission
} else {
log_w("Unsupported samplerate: %u Hz", new_samplerate);
// treat 8000 or 22050 Hz, if necessary
}
current_samplerate = new_samplerate;
}
vTaskDelay(500 / portTICK_PERIOD_MS); // Prüfe alle 500 ms
}
}
//---------------------------------------------------------------------------------------------------------------------
void i2s_install(){
i2s_chan_cfg.id = (i2s_port_t)i2s_num; // I2S_NUM_AUTO, I2S_NUM_0, I2S_NUM_1
i2s_chan_cfg.role = I2S_ROLE_SLAVE; // I2S controller slave role, bclk and lrc signal will be set to input
i2s_chan_cfg.dma_desc_num = 8; // number of DMA buffer
i2s_chan_cfg.dma_frame_num = 512; // I2S frame number in one DMA buffer.
i2s_chan_cfg.auto_clear = true; // i2s will always send zero automatically if no data to send
i2s_new_channel(&i2s_chan_cfg, NULL, &i2s_rx_handle);
i2s_std_cfg.slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO); // Set to enable bit shift in Philips mode
i2s_std_cfg.gpio_cfg.bclk = (gpio_num_t)RX_I2S_BCLK; // BCLK Assignment
i2s_std_cfg.gpio_cfg.din = (gpio_num_t)RX_I2S_DIN; // DIN Assignment
i2s_std_cfg.gpio_cfg.dout = I2S_GPIO_UNUSED; //
i2s_std_cfg.gpio_cfg.mclk = I2S_GPIO_UNUSED; //
i2s_std_cfg.gpio_cfg.ws = (gpio_num_t)RX_I2S_LRC; // LRC Assignment
i2s_std_cfg.gpio_cfg.invert_flags.mclk_inv = false;
i2s_std_cfg.gpio_cfg.invert_flags.bclk_inv = false;
i2s_std_cfg.gpio_cfg.invert_flags.ws_inv = false;
i2s_std_cfg.clk_cfg.sample_rate_hz = 44800;
i2s_std_cfg.clk_cfg.clk_src = I2S_CLK_SRC_DEFAULT; // Select PLL_F160M as the default source clock
i2s_std_cfg.clk_cfg.mclk_multiple = I2S_MCLK_MULTIPLE_128; //
i2s_channel_init_std_mode(i2s_rx_handle, &i2s_std_cfg);
i2s_channel_enable(i2s_rx_handle);
}
//---------------------------------------------CallBacks--------------------------------------------------------------------
int32_t get_data(uint8_t *data, int32_t bytes) {
return resampler.getData(data, bytes); // Holt exakt die benötigten Daten
}
// gets called when button on bluetooth speaker is pressed
void button_handler(uint8_t id, bool isReleased){
if (isReleased) {
Serial.print("button id ");
Serial.print(id);
Serial.println(" released");
}
}
//---------------------------------------------SETUP--------------------------------------------------------------------
void setup(){
Serial.begin(115200);
i2s_install();
a2dp_source.set_data_callback(get_data);
a2dp_source.set_avrc_passthru_command_callback(button_handler);
a2dp_source.start(BT_SINK_NAME);
resampler.setChannelHandle(i2s_rx_handle);
xTaskCreate(samplerate_monitor_task, "samplerate_monitor", 2048, NULL, 5, NULL);
}
//----------------------------------------------LOOP--------------------------------------------------------------------
void loop() {
vTaskDelay(1);
resampler.loopResample();
}

View File

@@ -0,0 +1,31 @@
#include "Arduino.h"
#include "Audio.h"
#include "WiFi.h"
#define I2S_DOUT 9
#define I2S_BCLK 3
#define I2S_LRC 1
Audio audio;
String ssid = "*****";
String password = "*****";
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
Serial.begin(115200);
WiFi.begin(ssid.c_str(), password.c_str());
while (WiFi.status() != WL_CONNECTED) delay(1500);
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(12); // default 0...21
audio.connecttospeech("Wenn die Hunde schlafen, kann der Wolf gut Schafe stehlen.", "de"); // Google TTS
}
void loop() {
audio.loop();
vTaskDelay(1);
}

View File

@@ -0,0 +1,30 @@
#include "Arduino.h"
#include "Audio.h"
#include "WiFi.h"
#define I2S_DOUT 9
#define I2S_BCLK 3
#define I2S_LRC 1
Audio audio;
String ssid = "*****";
String password = "*****";
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
Serial.begin(115200);
WiFi.begin(ssid.c_str(), password.c_str());
while (WiFi.status() != WL_CONNECTED) delay(1500);
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(12); // default 0...21
audio.openai_speech("openAI-key", "tts-1", "Today is a wonderful day to build something people love!", "", "shimer", "mp3", "1");}
void loop() {
audio.loop();
vTaskDelay(1);
}

View File

@@ -0,0 +1,53 @@
//**********************************************************************************************************
//* audioI2S-- I2S audiodecoder for ESP32, *
//**********************************************************************************************************
//
// first release on 11/2018
// Version 4 , Aug.22/2025
//
//
// THE SOFTWARE IS PROVIDED "AS IS" FOR PRIVATE USE ONLY, IT IS NOT FOR COMMERCIAL USE IN WHOLE OR PART OR CONCEPT.
// FOR PERSONAL USE IT IS SUPPLIED WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR
// OR COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
//
#include "Arduino.h"
#include "Audio.h"
#include "SPI.h"
#include "SD.h"
#include "FS.h"
// Digital I/O used
#define SD_CS 5
#define SPI_MOSI 23
#define SPI_MISO 19
#define SPI_SCK 18
#define I2S_DOUT 25
#define I2S_BCLK 27
#define I2S_LRC 26
Audio audio;
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
pinMode(SD_CS, OUTPUT);
digitalWrite(SD_CS, HIGH);
SPI.begin(SPI_SCK, SPI_MISO, SPI_MOSI);
SPI.setFrequency(1000000);
Serial.begin(115200);
SD.begin(SD_CS);
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(12); // 0...21
audio.connecttoFS(SD, "test.wav");
}
void loop(){
vTaskDelay(1);
audio.loop();
}

View File

@@ -0,0 +1,38 @@
#include "Arduino.h"
#include "Audio.h"
#include "SD_MMC.h"
#define I2S_DOUT 9
#define I2S_BCLK 3
#define I2S_LRC 1
#define SD_MMC_D0 11
#define SD_MMC_CLK 13
#define SD_MMC_CMD 14
Audio audio;
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
Serial.begin(115200);
pinMode(SD_MMC_D0, INPUT_PULLUP);
SD_MMC.setPins(SD_MMC_CLK, SD_MMC_CMD, SD_MMC_D0);
SD_MMC.begin("/sdcard", true);
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(12); // default 0...21
audio.connecttoFS(SD_MMC, "/test.wav");
}
void loop() {
audio.loop();
vTaskDelay(1);
}
// optional
void audio_info(const char *info){
Serial.print("info "); Serial.println(info);
}

View File

@@ -0,0 +1,77 @@
//**********************************************************************************************************
//* audioI2S-- I2S audiodecoder for M5Stack Core2 *
//**********************************************************************************************************
//
// first release on May.12/2021
//
//
// THE SOFTWARE IS PROVIDED "AS IS" FOR PRIVATE USE ONLY, IT IS NOT FOR COMMERCIAL USE IN WHOLE OR PART OR CONCEPT.
// FOR PERSONAL USE IT IS SUPPLIED WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR
// OR COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
//
#include <M5Core2.h>
#include "Audio.h"
// Digital I/O used
#define SD_CS 4
#define SD_MOSI 23
#define SD_MISO 38
#define SD_SCK 18
#define I2S_DOUT 2
#define I2S_BCLK 12
#define I2S_LRC 0
Audio audio;
String ssid = "xxxxxx";
String password = "xxxxxx";
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
M5.begin(true, true, true, true);
M5.Axp.SetSpkEnable(true);
M5.Lcd.fillScreen(BLACK);
M5.Lcd.setTextColor(WHITE);
M5.Lcd.setTextSize(2);
pinMode(SD_CS, OUTPUT);
digitalWrite(SD_CS, HIGH);
SPI.begin(SD_SCK, SD_MISO, SD_MOSI);
SPI.setFrequency(1000000);
SD.begin(SD_CS);
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(15); // 0...21
WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), password.c_str());
while (!WiFi.isConnected()) {
delay(10);
}
ESP_LOGI(TAG, "Connected");
ESP_LOGI(TAG, "Starting MP3...\n");
// audio.connecttoFS(SD, "/320k_test.mp3");
// audio.connecttoFS(SD, "test.wav");
audio.connecttohost("http://air.ofr.fm:8008/jazz/mp3/128");
// audio.connecttospeech("Миска вареників з картоплею та шкварками, змащених салом!", "uk-UA");
}
void loop() {
vTaskDelay(1);
audio.loop();
if(Serial.available()){ // put streamURL in serial monitor
audio.stopSong();
String r=Serial.readString();
r.trim();
if(r.length()>5) audio.connecttohost(r.c_str());
log_i("free heap=%i", ESP.getFreeHeap());
}
}

View File

@@ -0,0 +1,53 @@
// M5Stack Node support
// thanks to Cellie - issue #35 25.Apr.2020
// M5Stack board with Node base also need a MCLK signal on GPIO0.
#include <WM8978.h> /* https://github.com/CelliesProjects/wm8978-esp32 */
#include <Audio.h> /* https://github.com/schreibfaul1/ESP32-audioI2S */
/* M5Stack Node WM8978 I2C pins */
#define I2C_SDA 21
#define I2C_SCL 22
/* M5Stack Node I2S pins */
#define I2S_BCK 5
#define I2S_WS 13
#define I2S_DOUT 2
#define I2S_DIN 34
/* M5Stack WM8978 MCLK gpio number */
#define I2S_MCLKPIN 0
WM8978 dac;
Audio audio;
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
/* Setup wm8978 I2C interface */
if (!dac.begin(I2C_SDA, I2C_SCL)) {
log_e("Error setting up dac. System halted");
while (1) delay(100);
}
dac.setSPKvol(40); /* max 63 */
dac.setHPvol(32, 32);
/* Setup wm8978 I2S interface */
audio.setPinout(I2S_BCK, I2S_WS, I2S_DOUT, I2S_MCLKPIN);
WiFi.begin("xxx", "xxx");
while (!WiFi.isConnected()) { delay(10); }
log_i("Connected\nStarting MP3...\n");
audio.connecttohost("http://icecast.omroep.nl/3fm-bb-mp3");
}
void loop() {
vTaskDelay(1);
audio.loop();
}

View File

@@ -0,0 +1,59 @@
//**********************************************************************************************************
//* audioI2S-- I2S audiodecoder for M5StickC Plus and SPK HAT *
//**********************************************************************************************************
//
// first release on May.12/2021
//
//
// THE SOFTWARE IS PROVIDED "AS IS" FOR PRIVATE USE ONLY, IT IS NOT FOR COMMERCIAL USE IN WHOLE OR PART OR CONCEPT.
// FOR PERSONAL USE IT IS SUPPLIED WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR
// OR COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
//
#include <M5StickCPlus.h>
#include "Audio.h"
Audio audio = Audio(true);
String ssid = "xxxxxxxx";
String password = "xxxxxxxx";
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
M5.begin(false); // Lcd disabled to reduce noise
M5.Axp.ScreenBreath(1); // Lower Lcd backlight
pinMode(36, INPUT);
gpio_pulldown_dis(GPIO_NUM_25);
gpio_pullup_dis(GPIO_NUM_25);
M5.Beep.tone(44100); // Built-in buzzer tone
M5.Beep.end(); // disabled
audio.setVolume(15); // 0...21
WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), password.c_str());
while (!WiFi.isConnected()) { delay(10); }
ESP_LOGI(TAG, "Connected");
ESP_LOGI(TAG, "Starting MP3...\n");
audio.connecttohost("http://air.ofr.fm:8008/jazz/mp3/128");
// audio.connecttospeech("Миска вареників з картоплею та шкварками, змащених салом!", "uk-UA");
}
void loop() {
vTaskDelay(1);
audio.loop();
if(Serial.available()){ // put streamURL in serial monitor
audio.stopSong();
String r=Serial.readString();
r.trim();
if(r.length()>5) audio.connecttohost(r.c_str());
log_i("free heap=%i", ESP.getFreeHeap());
}
}

View File

@@ -0,0 +1,44 @@
import numpy as np
# import matplotlib
# matplotlib.use("TkAgg") # oder "QtAgg", falls Qt installiert ist
import matplotlib.pyplot as plt
from scipy.signal import freqz
# =========================
# PARAMETER
# =========================
fs = 44100 # Samplerate
N = 8192 # FFT-Auflösung
# Liste von Biquads (Reihenfolge = Signalfluss)
biquads = [
([1.026721, -1.919612, 0.901093], [1.0, -1.922258, 0.925168]), # LOWSHELF
([0.802626, -1.424665, 0.670208 ], [1.0, -1.424665, 0.472834 ]), # PEAKINGEQ
([2.092489, -2.262849, 0.808592], [1.0, -0.597000, 0.235232]), # HIGHSHELF
]
w = np.linspace(0, np.pi, N)
H = np.ones_like(w, dtype=complex)
for b, a in biquads:
_, h = freqz(b, a, worN=w)
H *= h
f = w * fs / (2*np.pi)
mag_db = 20 * np.log10(np.abs(H) + 1e-12)
# =========================
# PLOT
# =========================
plt.figure(figsize=(9,5))
plt.semilogx(f, mag_db)
plt.xlim(20, fs/2)
plt.ylim(-15, 15)
plt.grid(True, which='both')
plt.xlabel("Frequency (Hz)")
plt.ylabel("Amplitude (dB)")
plt.title("Biquad frequency response")
plt.tight_layout()
# plt.show()
plt.savefig("biquad_response.png", dpi=150)
print("Plot gespeichert als biquad_response.png")

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

View File

@@ -0,0 +1,98 @@
#include "Arduino.h"
#include "Audio.h"
#include "SD_MMC.h"
#include "FS.h"
#include <vector>
#define I2S_LRC 26
#define I2S_DOUT 25
#define I2S_BCLK 27
#define SD_MMC_D0 2
#define SD_MMC_CLK 14
#define SD_MMC_CMD 15
void listDir(fs::FS &fs, const char * dirname, uint8_t levels); //proto
std::vector<char*> v_audioContent;
int pirPin = 4;
Audio audio;
File dir;
const char audioDir[] = "/mp3";
void my_audio_info(Audio::msg_t m) {
Serial.printf("%s: %s\n", m.s, m.msg);
}
void setup() {
Audio::audio_info_callback = my_audio_info;
Serial.begin(115200);
pinMode(SD_MMC_D0, INPUT_PULLUP);
SD_MMC.setPins(SD_MMC_CLK,SD_MMC_CMD, SD_MMC_D0);
if(!SD_MMC.begin( "/sdmmc", true, false, 20000)){
Serial.println("Card Mount Failed");
return;
}
audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
audio.setVolume(17); // 0...21 Will need to add a volume setting in the app
dir = SD_MMC.open(audioDir);
listDir(SD_MMC, audioDir, 1);
if(v_audioContent.size() > 0){
const char* s = (const char*)v_audioContent[v_audioContent.size() -1];
Serial.printf("playing %s\n", s);
audio.connecttoFS(SD_MMC, s);
v_audioContent.pop_back();
}
}
void loop(){
audio.loop();
vTaskDelay(1); // Audio is distoreted without this
}
void listDir(fs::FS &fs, const char * dirname, uint8_t levels){
Serial.printf("Listing directory: %s\n", dirname);
File root = fs.open(dirname);
if(!root){
Serial.println("Failed to open directory");
return;
}
if(!root.isDirectory()){
Serial.println("Not a directory");
return;
}
File file = root.openNextFile();
while(file){
if(file.isDirectory()){
Serial.print(" DIR : ");
Serial.println(file.name());
if(levels){
listDir(fs, file.path(), levels -1);
}
} else {
Serial.print(" FILE: ");
Serial.print(file.name());
Serial.print(" SIZE: ");
Serial.println(file.size());
v_audioContent.insert(v_audioContent.begin(), strdup(file.path()));
}
file = root.openNextFile();
}
Serial.printf("num files %i", v_audioContent.size());
root.close();
file.close();
}
void vector_clear_and_shrink(vector<char*>&vec){
uint size = vec.size();
for (int i = 0; i < size; i++) {
if(vec[i]){
free(vec[i]);
vec[i] = NULL;
}
}
vec.clear();
vec.shrink_to_fit();
}

View File

@@ -0,0 +1,23 @@
{
"name": "ESP32-audioI2S",
"version": "3.4.6",
"description": "With this library You can easily build a WebRadio with a ESP32 board and a I2S-module",
"keywords": "audio, i2s, esp32, esp32-s3, esp32-p4",
"repository": {
"type": "git",
"url": "https://github.com/schreibfaul1/ESP32-audioI2S.git"
},
"authors": [
{
"name": "schreibfaul1"
}
],
"license": "GPL-3.0",
"homepage": "https://github.com/schreibfaul1/ESP32-audioI2S",
"dependencies": {},
"frameworks": [
"arduino",
"espidf"
],
"platforms": "espressif32"
}

View File

@@ -0,0 +1,9 @@
name=ESP32-audioI2S-master
version=3.4.6
author=schreibfaul1
maintainer=schreibfaul1
sentence=With this library You can easily build a audio app with a ESP32, ESP32-S3, ESP32-P4 board with PSRAM and a external DAC or I2S-BT-module.
paragraph=Data format can be only mp3, aac, flac, opus, vorbis or m4a.
category=Device Control
url=https://github.com/schreibfaul1/ESP32-audioI2S
architectures=esp32

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,811 @@
/*
* Audio.h
*
*/
#pragma once
#pragma GCC optimize("Ofast")
#include "audiolib_structs.hpp"
#include "esp_arduino_version.h"
#include "esp_dsp.h"
#include "psram_unique_ptr.hpp"
#include <Arduino.h>
#include <FFat.h>
#include <FS.h>
#include <NetworkClient.h>
#include <NetworkClientSecure.h>
#include <SD.h>
#include <SD_MMC.h>
#include <WiFi.h>
#include <atomic>
#include <charconv>
#include <codecvt>
#include <deque>
#include <driver/i2s_std.h>
#include <esp32-hal-log.h>
#include <functional>
#include <libb64/cencode.h>
#include <locale>
#include <memory>
#include <optional>
#include <span>
#include <vector>
#ifndef I2S_GPIO_UNUSED
#define I2S_GPIO_UNUSED -1 // = I2S_PIN_NO_CHANGE in IDF < 5
#endif
extern __attribute__((weak)) void audio_process_raw_samples(int32_t* outBuff, int16_t validSamples); // before volume, gain and equalizer, record audiodata
extern __attribute__((weak)) void audio_process_i2s(int32_t* outBuff, int16_t validSamples, bool* continueI2S); // after volume, gain and equalizer, send via BT
extern char audioI2SVers[];
class Decoder; // prototype
//----------------------------------------------------------------------------------------------------------------------
class AudioBuffer {
public:
AudioBuffer(); // constructor
~AudioBuffer(); // frees the buffer
size_t init(); // set default values
bool isInitialized() { return m_init; };
size_t getBufsize();
size_t getMaxBlockSize(); // returns maxBlockSize
void setMaxBlocksize(uint32_t mbs);
size_t freeSpace(); // number of free bytes to overwrite
size_t writeSpace(); // space fom writepointer to bufferend
size_t bufferFilled(); // returns the number of filled bytes
size_t readSpace(); // max readable bytes in one block
void bytesWritten(size_t bw); // update writepointer
void bytesWasRead(size_t br); // update readpointer
uint8_t* getWritePtr(); // returns the current writepointer
uint8_t* getReadPtr(); // returns the current readpointer
void reset(); // restore defaults
void showStatus();
protected:
size_t m_mainBuffSize = 0; // most webstreams limit the advance to 100...300Kbytes
size_t m_freeSpace = 0;
size_t m_writeSpace = 0;
size_t m_resBuffSize = 0;
size_t m_maxBlockSize = 0;
size_t m_readSpace = 0;
const size_t m_maxRet = UINT16_MAX;
ps_ptr<uint8_t> m_buffer;
uint8_t* m_buffEnd = nullptr;
uint8_t* m_writePtr = nullptr;
uint8_t* m_readPtr = nullptr;
uint8_t* m_endPtr = nullptr;
uint8_t* m_startPtr = nullptr;
ps_ptr<char> m_log;
bool m_init = false;
bool m_isEmpty = true;
bool m_isFull = false;
private:
SemaphoreHandle_t m_mutex = nullptr;
#define ANSI_ESC_RED "\033[31m"
};
//----------------------------------------------------------------------------------------------------------------------
class Audio {
private:
AudioBuffer InBuff; // instance of input buffer
public:
Audio(uint8_t i2sPort = I2S_NUM_0);
~Audio();
std::mutex mutex_info; // mutex_info as member
// callbacks ---------------------------------------------------------
typedef enum {
evt_info = 0,
evt_id3data,
evt_eof,
evt_name,
evt_icydescription,
evt_streamtitle,
evt_bitrate,
evt_icyurl,
evt_icylogo,
evt_genre,
evt_lasthost,
evt_image,
evt_lyrics,
evt_log,
} event_t;
// Audio event type descriptions
static constexpr std::array<const char*, 14> eventStr = {
"info", // evt_info
"id3data", // evt_id3data
"eof", // evt_eof
"station_name", // evt_name
"icy_description", // evt_icydescription
"streamtitle", // evt_streamtitle
"bitrate (b/s)", // evt_bitrate
"icy_url", // evt_icyurl
"icy_logo", // evt_icylogo
"genre", // evt_genre
"lasthost", // evt_lasthost
"cover_image", // evt_image
"lyrics", // evt_lyrics
"log", // evt_log
};
typedef struct _msg { // used in info(audio_info_callback());
const char* msg = nullptr;
const char* s = nullptr;
event_t e = (event_t)0; // event type
int32_t i2s_num = 0;
int32_t arg1 = 0;
int32_t arg2 = 0;
std::vector<uint32_t> vec = {}; // apic [pos, len, pos, len, pos, len, ....]
} msg_t;
inline static std::function<void(msg_t i)> audio_info_callback;
using VolumeCurveFn = std::function<float(float t)>;
// -------------------------------------------------------------------
typedef enum : uint32_t { SR_ORIGIN = 0, SR_44100 = 44100, SR_48000 = 48000 } OutputSR_t;
bool openai_speech(const String& api_key, const String& model, const String& input, const String& instructions, const String& voice, const String& response_format, const String& speed);
audiolib::hwoe_t dismantle_host(const char* host);
bool connecttohost(const char* host, const char* user = nullptr, const char* pwd = nullptr);
bool connecttospeech(const char* speech, const char* lang);
bool connecttoFS(fs::FS& fs, const char* path, int32_t fileStartTime = -1);
void setConnectionTimeout(uint16_t timeout_ms, uint16_t timeout_ms_ssl);
bool setAudioPlayTime(uint16_t sec);
bool setTimeOffset(int sec);
bool setPinout(uint8_t BCLK, uint8_t LRC, uint8_t DOUT, int8_t MCLK = I2S_GPIO_UNUSED);
bool pauseResume();
bool isRunning() { return m_f_running; }
void loop();
uint32_t stopSong();
void forceMono(bool m);
void setOutputSampleRate(OutputSR_t sr);
void setBalance(float balance = 0.0f);
void setVolumeSteps(uint8_t steps);
uint8_t getVolumeSteps();
void setVolume(uint8_t vol, uint8_t curve = 0);
void setVolumeCurve(VolumeCurveFn curve);
uint8_t getVolume();
void setMute(bool mute);
bool getMute();
int32_t getI2sPort();
uint32_t getFileSize();
uint32_t getSampleRate();
uint8_t getBitsPerSample();
uint8_t getChannels();
uint32_t getBitRate();
uint32_t getAudioFileDuration();
uint32_t getAudioCurrentTime();
uint32_t getAudioFilePosition();
bool setAudioFilePosition(uint32_t pos);
uint16_t getVUlevel();
uint32_t inBufferFilled(); // returns the number of stored bytes in the inputbuffer
uint32_t inBufferFree(); // returns the number of free bytes in the inputbuffer
uint32_t getInBufferSize(); // returns the size of the inputbuffer in bytes
void inBufferStatus() { InBuff.showStatus(); }
void setTone(float gainLowPass, float gainBandPass, float gainHighPass);
void setI2SCommFMT_LSB(bool commFMT);
int getCodec() { return m_codec; }
const char* getCodecname() { return codecname[m_codec]; }
const char* getVersion();
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
private:
// ------- PRIVATE MEMBERS ----------------------------------------
bool i2s_config();
std::unique_ptr<Decoder> createDecoder(const std::string& type);
void destroy_decoder();
bool fsRange(uint32_t range);
void latinToUTF8(ps_ptr<char>& buff, bool UTF8check = true);
void htmlToUTF8(char* str);
void setDefaults(); // free buffers and set defaults
int32_t audioFileRead();
int32_t audioFileRead(uint16_t timeout_ms);
int32_t audioFileRead(uint8_t* buff, size_t len);
int32_t audioFileRead(uint8_t* buff, size_t len, uint16_t timeout_ms);
int32_t audioFileSeek(uint32_t position, size_t len = 0);
void initInBuff();
bool httpPrint(const char* host);
bool httpRange(uint32_t range, uint32_t length = UINT32_MAX);
void processLocalFile();
void processWebStream();
void processWebFile();
void processWebStreamTS();
void processWebStreamHLS();
void playAudioData();
bool readPlayListData();
const char* parsePlaylist_M3U();
const char* parsePlaylist_PLS();
const char* parsePlaylist_ASX();
ps_ptr<char> parsePlaylist_M3U8();
uint16_t accomplish_m3u8_url();
int16_t prepare_first_m3u8_url(ps_ptr<char>& playlistBuff);
ps_ptr<char> m3u8redirection(uint8_t* codec);
void showCodecParams();
int findNextSync(uint8_t* data, size_t len);
uint32_t decodeError(int8_t res, uint8_t* data, int32_t bytesDecoded);
uint32_t decodeContinue(int8_t res, uint8_t* data, int32_t bytesDecoded, int32_t* bytesLeft);
int sendBytes(uint8_t* data, size_t len);
void setDecoderItems();
void calculateAudioTime(uint16_t bytesDecoderIn, uint16_t bytesDecoderOut);
void showID3Tag(const char* tag, const char* val);
size_t readAudioHeader(uint32_t bytes);
int read_WAV_Header(uint8_t* data, size_t len);
int read_FLAC_Header(uint8_t* data, size_t len);
int read_ID3_Header(uint8_t* data, size_t len);
int read_M4A_Header(uint8_t* data, size_t len);
size_t process_m3u8_ID3_Header(uint8_t* packet);
bool setSampleRate(uint32_t hz);
bool setBitsPerSample(int bits);
bool setChannels(int channels);
uint32_t resampleI2Soutput(audiolib::resampler_t& resampler, int32_t* input, uint32_t inputSamples, int32_t* output);
void playChunk();
void calculateVUlevel(int32_t* sample);
void processSpectrum();
void gain_ramp();
void calculateVolumeLimits();
void Gain(int32_t* sample);
void showstreamtitle(char* ml);
bool parseContentType(ps_ptr<char> ct);
bool parseHttpResponseHeader();
bool parseHttpRangeHeader();
bool initializeDecoder();
esp_err_t I2Sstart();
esp_err_t I2Sstop();
void zeroI2Sbuff();
void reconfigI2S();
void stereo2mono(int32_t* buff, uint16_t validSamples);
void IIR_calculateCoefficients();
void IIR_filter(int32_t* iir_in);
uint32_t streamavail() { return m_client ? m_client->available() : 0; }
bool ts_parsePacket(uint8_t* packet, uint8_t* packetStart, uint8_t* packetLength);
uint64_t getLastGranulePosition(uint8_t codec);
//+++ create a T A S K for playAudioData(), output via I2S +++
public:
void setAudioTaskCore(uint8_t coreID);
uint32_t getHighWatermark();
private:
void startAudioTask(); // starts a task for decode and play
void stopAudioTask(); // stops task for audio
static void audioTaskWrapper(void* param);
void audioTask();
void performAudioTask();
//+++ H E L P F U N C T I O N S +++
bool readMetadata(uint32_t b, uint16_t* readedBytes, bool first = false);
int32_t getChunkSize(uint16_t* readedBytes, bool first = false);
bool readID3V1Tag();
int32_t newInBuffStart(int32_t resumeFilePos);
boolean streamDetection(uint32_t bytesAvail);
uint32_t m4a_correctResumeFilePos();
uint32_t ogg_correctResumeFilePos();
int32_t flac_correctResumeFilePos();
int32_t mp3_correctResumeFilePos();
int32_t wav_correctResumeFilePos();
uint8_t determineCodec(uint8_t presumed_codec);
bool get_info();
void trim(char* str);
bool startsWith(const char* base, const char* str);
int indexOf(const char* base, const char* str, int startIndex = 0);
int indexOf(const char* base, char ch, int startIndex = 0);
int specialIndexOf(uint8_t* base, const char* str, int baselen, bool exact = false);
int32_t min3(int32_t a, int32_t b, int32_t c);
uint64_t bigEndian(uint8_t* base, uint8_t numBytes, uint8_t shiftLeft = 8);
bool b64encode(const char* source, uint16_t sourceLength, char* dest);
void vector_clear_and_shrink(std::vector<ps_ptr<char>>& vec);
void deque_clear_and_shrink(std::deque<ps_ptr<char>>& deq);
uint32_t simpleHash(const char* str);
ps_ptr<char> urlencode(const char* str, bool spacesOnly);
audiolib::BiquadCoeffs makeButterworthLPF_Q31(float fs);
private:
enum : int { APLL_AUTO = -1, APLL_ENABLE = 1, APLL_DISABLE = 0 };
enum : int { EXTERNAL_I2S = 0, INTERNAL_DAC = 1, INTERNAL_PDM = 2 };
enum : int { FORMAT_NONE = 0, FORMAT_M3U = 1, FORMAT_PLS = 2, FORMAT_ASX = 3, FORMAT_M3U8 = 4 }; // playlist formats
const char* plsFmtStr[5] = {"NONE", "M3U", "PLS", "ASX", "M3U8"}; // playlist format string
enum : int { AUDIO_NONE, HTTP_RESPONSE_HEADER, HTTP_RANGE_HEADER, AUDIO_DATA, AUDIO_LOCALFILE, AUDIO_PLAYLISTINIT, AUDIO_PLAYLISTHEADER, AUDIO_PLAYLISTDATA };
const char* dataModeStr[8] = {"AUDIO_NONE", "HTTP_RESPONSE_HEADER", "HTTP_RANGE_HEADER", "AUDIO_DATA", "AUDIO_LOCALFILE", "AUDIO_PLAYLISTINIT", "AUDIO_PLAYLISTHEADER", "AUDIO_PLAYLISTDATA"};
enum : int { FLAC_BEGIN = 0, FLAC_MAGIC = 1, FLAC_MBH = 2, FLAC_SINFO = 3, FLAC_PADDING = 4, FLAC_APP = 5, FLAC_SEEK = 6, FLAC_VORBIS = 7, FLAC_CUESHEET = 8, FLAC_PICTURE = 9, FLAC_OKAY = 100 };
enum : int { MP3_BEGIN = 0, MP3_ID3HEADER, MP3_NEXTID3, MP3_EXTHEADER, MP3_ID3FRAME, MP3_FRAMESIZE, MP3_SKIP, MP3_TAG, MP3_SYLT, MP3_ID3V22, MP3_LASTFRAMES, MP3_XING, MP3_OKAY = 100 };
enum : int {
M4A_BEGIN = 0,
M4A_FTYP = 1,
M4A_CHK = 2,
M4A_MOOV = 3,
M4A_FREE = 4,
M4A_TRAK = 5,
M4A_MDAT = 6,
M4A_ILST = 7,
M4A_MP4A = 8,
M4A_ESDS = 9,
M4A_MDIA = 10,
M4A_MINF = 11,
M4A_STBL = 12,
M4A_STSD = 13,
M4A_UDTA = 14,
M4A_STSZ = 15,
M4A_META = 16,
M4A_MDHD = 17,
M4A_CHPL = 18,
M4A_AMRDY = 99,
M4A_OKAY = 100,
};
enum : int { CODEC_NONE = 0, CODEC_WAV = 1, CODEC_MP3 = 2, CODEC_AAC = 3, CODEC_M4A = 4, CODEC_FLAC = 5, CODEC_OPUS = 6, CODEC_VORBIS = 7, CODEC_OGG = 8 };
const char* codecname[10] = {"unknown", "WAV", "MP3", "AAC", "M4A", "FLAC", "OPUS", "VORBIS", "OGG"};
enum : int { ST_NONE = 0, ST_WEBFILE = 1, ST_WEBSTREAM = 2 };
const char* streamTypeStr[3] = {"NONE", "WEBFILE", "WEBSTREAM"};
typedef enum { LEFTCHANNEL = 0, RIGHTCHANNEL = 1 } SampleIndex;
typedef enum { LOWSHELF = 0, PEAKINGEQ = 1, HIFGSHELF = 2 } FilterType;
private:
typedef struct _filter {
float a0;
float a1;
float a2;
float b1;
float b2;
} filter_t;
typedef struct _pis_array {
int number;
int pids[4];
} pid_array;
public:
struct audioSettings {
uint16_t DMA_DESC_NUM = 32; // number of I2S DMA buffer
uint16_t DMA_FRAME_NUM = 256; // number of frames in one DMA buffer
uint16_t FREQ_LS_HZ = 500; // IIR Filter, lowshelf
uint16_t FREQ_PEAK_HZ = 1800; // IIR Filter, peakingEQ
uint16_t FREQ_HS_HZ = 6000; // IIR Filter, highshelf
float QUALITY_SLOPE = 0.707; // Quality (all shelfes)
uint16_t PEAK_HOLD_SAMPLES = 2000; // VU_meter, (2000) ca. 20 ms @ 48 kHz
uint8_t PEAK_RELEASE = 1; // VU_meter, Fall rate
bool VU_LEVEL = true; // true: vu meter is enabled
bool IIR_FILTER = true; // true: IIR filter (highshelf, bandpass, lowshelf) are enabled
bool SPECTRUM = false; // true: spectrum analyzer is enabled
bool VOLUME_CONTROL = true; // true: volume and balance control is enabled
float VOL_FADING_SPEED = 50.0; // mute, volume fading 1.0f (fast) ... 100.0f (slow)
uint32_t BUFFER_TRESHOLD_HLS = 120000; // Level at which the HLS-TS stream starts and is reloaded
} settings;
private:
File m_audiofile;
NetworkClient client;
NetworkClientSecure clientsecure;
NetworkClient* m_client = nullptr;
SemaphoreHandle_t mutex_playAudioData;
SemaphoreHandle_t mutex_audioTask;
SemaphoreHandle_t mutex_audioTaskIsDecoding;
TaskHandle_t m_audioTaskHandle = nullptr;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
i2s_chan_handle_t m_i2s_tx_handle = {};
i2s_chan_config_t m_i2s_chan_cfg = {}; // stores I2S channel values
i2s_std_config_t m_i2s_std_cfg = {}; // stores I2S driver values
#pragma GCC diagnostic pop
std::vector<ps_ptr<char>> m_playlistContent; // m3u8 playlist buffer from responseHeader
std::vector<ps_ptr<char>> m_playlistURL; // m3u8 streamURLs buffer
std::deque<ps_ptr<char>> m_linesWithURL; // extract from m_playlistContent, contains URL and MediaSequenceNumber
std::vector<ps_ptr<char>> m_linesWithEXTINF; // extract from m_playlistContent, contains length and metadata
std::vector<ps_ptr<char>> m_syltLines; // SYLT line table
std::vector<uint32_t> m_syltTimeStamp; // SYLT time table
static const uint8_t m_tsPacketSize = 188;
static const uint8_t m_tsHeaderSize = 4;
std::unique_ptr<Decoder> m_decoder = {};
ps_ptr<int32_t> m_outBuff; // Interleaved L/R
ps_ptr<int32_t> m_resamplesBuff; // Interleaved L/R
ps_ptr<char> m_metadataBuff; // icy-metadata max (16 * 256 + 1) bytes
ps_ptr<char> m_httpRespHdrBuff; // store http response header
ps_ptr<char> m_ibuff; // used in log_info()
ps_ptr<char> m_lastHost; // Store the last URL to a webstream
ps_ptr<char> m_currentHost; // can be changed by redirection or playlist
ps_ptr<char> m_m3u8_host;
ps_ptr<char> m_speechtxt; // stores tts text
ps_ptr<char> m_streamTitle; // stores the last StreamTitle
ps_ptr<char> m_streamURL; // stores the last StreamURL
ps_ptr<char> m_playlistBuff;
VolumeCurveFn m_volumeCurve = nullptr;
const uint16_t m_plsBuffEntryLen = 256; // length of each entry in playlistBuff
int m_LFcount = 0; // Detection of end of header
uint32_t m_avr_bitrate = 0; // average bitrate, median calculated by VBR
uint32_t m_nominal_bitrate = 0; // given br from header
uint32_t m_audioFilePosition = 0; // current position, counts every readed byte
uint32_t m_audioDataReadPtr = 0; // used in playAudioData
uint32_t m_audioFileSize = 0; // local and web files
int m_readbytes = 0; // bytes read
uint32_t m_metacount = 0; // counts down bytes between metadata
int m_controlCounter = 0; // Status within readID3data() and readWaveHeader()
uint8_t m_timeoutCounter = 0; // timeout counter
uint8_t m_bitsPerSample = 16; // bitsPerSample
uint8_t m_channels = 2; //
uint8_t m_playlistFormat = 0; // M3U, PLS, ASX
uint8_t m_codec = CODEC_NONE; //
uint8_t m_m3u8Codec = CODEC_AAC; // codec of m3u8 stream
uint8_t m_expectedCodec = CODEC_NONE; // set in connecttohost (e.g. http://url.mp3 -> CODEC_MP3)
uint8_t m_expectedPlsFmt = FORMAT_NONE; // set in connecttohost (e.g. streaming01.m3u) -> FORMAT_M3U)
uint8_t m_streamType = ST_NONE; //
uint8_t m_ID3Size = 0; // lengt of ID3frame - ID3header
uint8_t m_audioTaskCoreId = 0; //
uint8_t m_M4A_objectType = 0; // set in read_M4A_Header
uint8_t m_M4A_chConfig = 0; // set in read_M4A_Header
uint16_t m_M4A_sampleRate = 0; // set in read_M4A_Header
int16_t m_validSamples = 0; //
int16_t m_curSample = 0; //
uint16_t m_dataMode = 0; // Statemaschine
uint16_t m_streamTitleHash = 0; // remember streamtitle, ignore multiple occurence in metadata
uint16_t m_timeout_ms = 250; //
uint16_t m_timeout_ms_ssl = 2700; //
uint32_t m_metaint = 0; // Number of databytes between metadata
uint32_t m_chunkcount = 0; // Counter for chunked transfer
uint32_t m_t0 = 0; // store millis(), is needed for a small delay
uint32_t m_bytesNotConsumed = 0; // pictures or something else that comes with the stream
uint64_t m_lastGranulePosition = 0; // necessary to calculate the duration in OPUS and VORBIS
int32_t m_resumeFilePos = -1; // the return value from stopSong(), (-1) is idle
int32_t m_fileStartTime = -1; // may be set in connecttoFS()
uint16_t m_m3u8_targetDuration = 10; //
uint32_t m_stsz_numEntries = 0; // num of entries inside stsz atom (uint32_t)
uint32_t m_stsz_position = 0; // pos of stsz atom within file
uint32_t m_haveNewFilePos = 0; // user changed the file position
bool m_f_alt_user_agent = false; // use default or alternative user agent
bool m_f_I2S_init = false; //
bool m_f_unsync = false; // set within ID3 tag but not used
bool m_f_exthdr = false; // ID3 extended header
bool m_f_ssl = false; //
bool m_f_running = false; //
bool m_f_firstCall = false; // InitSequence for processWebstream and processLokalFile
bool m_f_firstLoop = false; // InitSequence in loop()
bool m_f_firstPlayCall = false; // InitSequence for playAudioData
bool m_f_ID3v1TagFound = false; // ID3v1 tag found
bool m_f_chunked = false; // Station provides chunked transfer
bool m_f_firstmetabyte = false; // True if first metabyte (counter)
bool m_f_playing = false; // valid mp3 stream recognized
bool m_f_tts = false; // text to speech
bool m_f_ogg = false; // OGG stream
bool m_f_forceMono = false; // if true stereo -> mono
bool m_f_rtsp = false; // set if RTSP is used (m3u8 stream)
bool m_f_m3u8data = false; // used in processM3U8entries
bool m_f_continue = false; // next m3u8 chunk is available
bool m_f_ts = true; // transport stream
bool m_f_m4aID3dataAreRead = false; // has the m4a-ID3data already been read?
bool m_f_psramFound = false; // set in constructor, result of psramInit()
bool m_f_timeout = false; //
bool m_f_audioTaskIsRunning = false; //
bool m_f_allDataReceived = false; //
bool m_f_stream = false; // stream ready for output?
bool m_f_decode_ready = false; // if true data for decode are ready
bool m_f_eof = false; // end of file
bool m_f_lockInBuffer = false; // lock inBuffer for manipulation
bool m_f_audioTaskIsDecoding = false; //
bool m_f_acceptRanges = false; //
bool m_f_reset_m3u8Codec = true; // reset codec for m3u8 stream
bool m_f_connectionClose = false; // set in parseHttpResponseHeader
bool m_f_i2s_channel_enabled = false; // true if enabled
uint32_t m_audioFileDuration = 0; // seconds
uint32_t m_audioCurrentTime = 0; // seconds
uint32_t m_audioDataStart = 0; // in bytes
OutputSR_t m_output_sr = SR_ORIGIN; // output samplerate
size_t m_audioDataSize = 0; //
size_t m_ibuffSize = 0; // log buffer size for audio_info()
size_t m_i2s_bytesWritten = 0; // set in i2s_write() but not used
pid_array m_pidsOfPMT;
int16_t m_pidOfAAC;
uint8_t m_packetBuff[m_tsPacketSize];
int16_t m_pesDataLength = 0;
// audiolib structs
audiolib::ID3Hdr_t m_ID3Hdr;
audiolib::pwsHLS_t m_pwsHLS;
audiolib::pplM3u8_t m_pplM3U8;
audiolib::m4aHdr_t m_m4aHdr;
audiolib::plCh_t m_plCh;
audiolib::lVar_t m_lVar;
audiolib::prlf_t m_prlf;
audiolib::cat_t m_cat;
audiolib::ifCh_t m_ifCh;
audiolib::tspp_t m_tspp;
audiolib::pwst_t m_pwst;
audiolib::gchs_t m_gchs;
audiolib::pwf_t m_pwf;
audiolib::pad_t m_pad;
audiolib::sbyt_t m_sbyt;
audiolib::rmet_t m_rmet;
audiolib::pwsts_t m_pwsst;
audiolib::rwh_t m_rwh;
audiolib::rflh_t m_rflh;
audiolib::phreh_t m_phreh;
audiolib::phrah_t m_phrah;
audiolib::sdet_t m_sdet;
audiolib::fnsy_t m_fnsy;
audiolib::audioItems_t m_audio_items;
audiolib::vu_items_t m_vu_items;
audiolib::fft_items_t m_fft_items;
audiolib::i2s_items_t m_i2s_items;
audiolib::resampler_t m_resampler;
audiolib::info_queue_t m_info_queue;
audiolib::icy_items_t m_icy_items;
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
public:
template <typename... Args> static bool info(Audio& instance, event_t e, const char* fmt, Args&&... args) {
std::lock_guard<std::mutex> lock(instance.mutex_info);
if (!fmt) return false;
if (!audio_info_callback) return false;
ps_ptr<char> result;
result.assignf(fmt, std::forward<Args>(args)...);
if (!result.get()) return false;
auto extract_last_number = [](std::string_view s) -> std::optional<int32_t> {
auto is_space = [](char c) { return std::isspace(static_cast<unsigned char>(c)); };
auto is_digit = [](char c) { return std::isdigit(static_cast<unsigned char>(c)); };
auto it = s.end();
// skip trailing whitespace
while (it != s.begin() && is_space(*(it - 1))) { --it; }
auto end = it;
// Reading numbers backwards
while (it != s.begin() && is_digit(*(it - 1))) { --it; }
// optional sign
if (it != s.begin()) {
char c = *(it - 1);
if (c == '+' || c == '-') { --it; }
}
// found nothing?
if (it == end) { return std::nullopt; }
// There must be a leading space or a space before the number
if (it != s.begin() && !is_space(*(it - 1))) { return std::nullopt; }
int32_t value{};
auto [ptr, ec] = std::from_chars(it, end, value);
// Was the full parse successful?
if (ec == std::errc{} && ptr == end) { return value; }
return std::nullopt;
};
std::vector<uint32_t> v;
v.push_back(0);
instance.m_info_queue.msg.emplace_front(result);
instance.m_info_queue.s.emplace_front(eventStr[e]);
instance.m_info_queue.arg1.emplace_front(extract_last_number(result.c_get()).value_or(0));
instance.m_info_queue.arg2.emplace_front(0);
instance.m_info_queue.vec.emplace_front(v);
instance.m_info_queue.e.emplace_front((uint8_t)e);
result.reset();
return true;
}
static bool info(Audio& instance, event_t e, std::vector<uint32_t>& v) {
if (!audio_info_callback) return false;
std::lock_guard<std::mutex> lock(instance.mutex_info); // lock mutex
ps_ptr<char> apic;
apic.assignf("APIC found at pos {}", v[0]);
// msg_t i;
// i.msg = apic.c_get();
// i.e = e;
// i.s = eventStr[e];
// i.i2s_num = instance.m_i2s_items.i2s_num;
// i.vec = v;
// audio_info_callback(i);
instance.m_info_queue.msg.emplace_front(apic);
instance.m_info_queue.s.emplace_front(eventStr[e]);
instance.m_info_queue.arg1.emplace_front(0);
instance.m_info_queue.arg2.emplace_front(0);
instance.m_info_queue.vec.emplace_front(v);
instance.m_info_queue.e.emplace_front((uint8_t)e);
return true;
}
//----------------------------------------------------------------------------------------------------------------------
template <typename... Args> static void AUDIO_LOG_IMPL(uint8_t level, const char* path, int line, const char* func, const char* fmt, Args&&... args) {
#define ANSI_ESC_RESET "\033[0m"
#define ANSI_ESC_BLACK "\033[30m"
#define ANSI_ESC_RED "\033[31m"
#define ANSI_ESC_GREEN "\033[32m"
#define ANSI_ESC_YELLOW "\033[33m"
#define ANSI_ESC_BLUE "\033[34m"
#define ANSI_ESC_MAGENTA "\033[35m"
#define ANSI_ESC_CYAN "\033[36m"
#define ANSI_ESC_WHITE "\033[37m"
ps_ptr<char> logStr = path;
while (logStr.contains("/")) { logStr.remove_before('/', false); }
logStr.appendf(":{} {}] ", line, func ? func : "");
logStr.insert("[", 0);
if (level == 1 && CORE_DEBUG_LEVEL >= 1) {
logStr.append(ANSI_ESC_RED);
} else if (level == 2 && CORE_DEBUG_LEVEL >= 2) {
logStr.append(ANSI_ESC_YELLOW);
} else if (level == 3 && CORE_DEBUG_LEVEL >= 3) {
logStr.append(ANSI_ESC_GREEN);
} else if (level == 4 && CORE_DEBUG_LEVEL >= 4) {
logStr.append(ANSI_ESC_CYAN);
} // debug
else if (level == 5 && CORE_DEBUG_LEVEL >= 4) {
logStr.append(ANSI_ESC_WHITE);
} // verbose
else
return;
int add_len = std::snprintf(nullptr, 0, fmt, std::forward<Args>(args)...);
if (add_len > 0) {
logStr.appendf(fmt, std::forward<Args>(args)...); // <-- neue appendf()
}
logStr.append(ANSI_ESC_RESET);
msg_t msg;
msg.msg = logStr.get();
const char* tag[7] = {"", "LOGE", "LOGW", "LOGI", "LOGD", "LOGV", ""};
msg.s = tag[level];
msg.e = evt_log;
if (audio_info_callback)
audio_info_callback(msg);
else {
if (level == 1)
log_e("%s", logStr.c_get());
else if (level == 2)
log_w("%s", logStr.c_get());
else if (level == 3)
log_i("%s", logStr.c_get());
else if (level == 4)
log_d("%s", logStr.c_get());
else
log_v("%s", logStr.c_get());
}
logStr.reset();
}
// Macro for comfortable calls
#define AUDIO_LOG_ERROR(fmt, ...) AUDIO_LOG_IMPL(1, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define AUDIO_LOG_WARN(fmt, ...) AUDIO_LOG_IMPL(2, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define AUDIO_LOG_INFO(fmt, ...) AUDIO_LOG_IMPL(3, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define AUDIO_LOG_DEBUG(fmt, ...) AUDIO_LOG_IMPL(4, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
};
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// 📌📌📌 D E C O D E R 📌📌📌
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
class Decoder {
public:
virtual ~Decoder() = default;
virtual bool init() = 0;
virtual void clear() = 0;
virtual void reset() = 0;
virtual bool isValid() = 0;
virtual int32_t findSyncWord(uint8_t* buf, int32_t nBytes) = 0;
virtual uint8_t getChannels() = 0;
virtual uint32_t getSampleRate() = 0;
virtual uint8_t getBitsPerSample() = 0;
virtual uint32_t getBitRate() = 0;
virtual uint32_t getAudioDataStart() = 0;
virtual uint32_t getAudioFileDuration() = 0;
virtual uint32_t getOutputSamples() = 0;
virtual int32_t decode(uint8_t* inbuf, int32_t* bytesLeft, int32_t* outbuf1) = 0;
virtual void setRawBlockParams(uint8_t param1, uint32_t param2, uint8_t param3, uint32_t param4, uint32_t param5) = 0;
virtual const char* getStreamTitle();
virtual const char* whoIsIt();
virtual std::vector<uint32_t> getMetadataBlockPicture() = 0;
virtual const char* arg1() = 0; // decoder specific
virtual const char* arg2() = 0; // decoder specific
virtual int32_t val1() = 0; // decoder specific
virtual int32_t val2() = 0; // decoder specific
protected:
Decoder(Audio& audioRef) : audio(audioRef) {}
Audio& audio; // protected reference, usable by all subclasses
private:
Decoder() = delete; // Deactivate default constructor explicitly (optional but good against abuse)
};
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// 📌📌📌 A U T O L O G G E R for detecting memory leaks 📌📌📌
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/* usage
void myFunction(){
HEAP_GUARD(); // <--- automatic check
my code ...
my code ...
}
{ // Or in small critical code blocks:
HEAP_GUARD();
fill_content(inbuf, to_read);
}
*/
struct _HeapGuardSnapshot {
size_t free_dram_before{};
size_t free_psram_before{};
bool integrity_before{};
const char* func{};
bool active{false};
_HeapGuardSnapshot(const char* f) : func(f), active(true) {
free_dram_before = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
free_psram_before = heap_caps_get_free_size(MALLOC_CAP_SPIRAM);
integrity_before = heap_caps_check_integrity_all(true);
if (!integrity_before) {
printf(ANSI_ESC_RED "HEAPGUARD [%s] ❌ Heap corruption detected BEFORE!" ANSI_ESC_RESET "\n", func);
} else {
printf(ANSI_ESC_GREEN "HEAPGUARD [%s] Begin: DRAM=%u, PSRAM=%u" ANSI_ESC_RESET "\n", func, (unsigned)free_dram_before, (unsigned)free_psram_before);
}
}
~_HeapGuardSnapshot() {
if (!active) return; // falls moved / deaktiviert
size_t free_dram_after = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
size_t free_psram_after = heap_caps_get_free_size(MALLOC_CAP_SPIRAM);
bool ok = heap_caps_check_integrity_all(true);
int delta_dram = (int)(free_dram_after - free_dram_before);
int delta_psram = (int)(free_psram_after - free_psram_before);
if (!ok) {
printf(ANSI_ESC_RED "HEAPGUARD [%s] ❌ Heap corruption detected AFTER!" ANSI_ESC_RESET "\n", func);
} else {
printf(ANSI_ESC_GREEN "HEAPGUARD [%s] ✅ Heap OK | ΔDRAM=%+d | ΔPSRAM=%+d" ANSI_ESC_RESET "\n", func, delta_dram, delta_psram);
}
}
};
#define HEAP_GUARD() _HeapGuardSnapshot _heapguard_instance_##__LINE__(__func__)
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// 📌📌📌 A U T O P R O F I L E R RAII-class for timekeeping 📌📌📌
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/* usage
void decodeNative(uint8_t* inbuf, int bytesLeft, uint8_t* outbuf) {
PROFILE_SCOPE_N(1000); // automatically measures 1000 views on average
// ... my code ...
}
{ // Or in small critical code blocks:
PROFILE_SCOPE_N(100); // measures this block over 100 runs
do_fft_processing(data);
}
*/
class _AutoProfiler {
public:
_AutoProfiler(const char* name, uint32_t report_interval) : tag(name), N(report_interval) { start = esp_timer_get_time(); }
~_AutoProfiler() {
uint64_t elapsed = esp_timer_get_time() - start;
sum += elapsed;
count++;
if(max_dt < elapsed) max_dt = elapsed;
if (count >= N) {
double avg_us = (double)sum / count;
printf(ANSI_ESC_CYAN "PROFILER [%s] avg: %.2f µs over %lu runs, max %lu µs" ANSI_ESC_RESET "\n", tag, avg_us, count, max_dt);
sum = 0;
count = 0;
max_dt = 0;
}
}
private:
const char* tag;
uint32_t N;
uint64_t start;
static inline uint32_t max_dt = 0;
static inline uint64_t sum = 0;
static inline uint32_t count = 0;
};
// Macro for automatic use with function name
#define PROFILE_SCOPE_N(N) _AutoProfiler _prof_instance_##__LINE__(__func__, N)
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

View File

@@ -0,0 +1,234 @@
/*
* aac_decoder.cpp
* faad2 - ESP32 adaptation
* Created on: 12.09.2023
* Updated on: 26.06.2026
*/
#include "aac_decoder.h"
#include "Arduino.h"
#include "libfaad/neaacdec.h"
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
AACDecoder::AACDecoder(Audio& audioRef) : Decoder(audioRef), audio(audioRef), m_neaacdec(std::make_unique<NeaacDecoder>()) {}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
bool AACDecoder::init() {
m_hAac = m_neaacdec->NeAACDecOpen();
m_conf = m_neaacdec->NeAACDecGetCurrentConfiguration(m_hAac);
m_out16.alloc_array(4608 * 2, "m_out16");
if (m_hAac && m_out16.valid()) m_f_decoderIsInit = true;
m_f_firstCall = false;
m_f_setRaWBlockParams = false;
return m_f_decoderIsInit;
}
void AACDecoder::clear() {
m_out16.clear();
return; // nothing todo
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
void AACDecoder::reset() {
m_neaacdec->NeAACDecClose(m_hAac);
m_hAac = NULL;
m_f_decoderIsInit = false;
m_f_firstCall = false;
m_out16.reset();
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
bool AACDecoder::isValid() {
return m_f_decoderIsInit;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
int32_t AACDecoder::findSyncWord(uint8_t* buf, int32_t nBytes) {
const int MIN_ADTS_HEADER_SIZE = 7;
if (buf == nullptr || nBytes < MIN_ADTS_HEADER_SIZE) { return -1; }
auto validate = [MIN_ADTS_HEADER_SIZE](const uint8_t* buf, int32_t bytesAvailable) -> bool { // check the ADTS header for validity
if (bytesAvailable < MIN_ADTS_HEADER_SIZE) { return false; }
// Layer (bits 14-15) must be 00
if ((buf[1] & 0x06) != 0x00) { return false; }
// Sampling Frequency Index (Bits 18-21) cannot be invalid
uint8_t sampling_frequency_index = (buf[2] & 0x3C) >> 2;
if (sampling_frequency_index > 12) { return false; }
// Frame length (bits 30-42) must be at least the header size
int frame_length = ((buf[3] & 0x03) << 11) | (buf[4] << 3) | ((buf[5] & 0xE0) >> 5);
if (frame_length < MIN_ADTS_HEADER_SIZE) { return false; }
return true;
};
/* find byte-aligned syncword (12 bits = 0xFFF) */
for (int32_t i = 0; i <= nBytes - MIN_ADTS_HEADER_SIZE; i++) {
if ((buf[i + 0] & SYNCWORDH) == SYNCWORDH && (buf[i + 1] & SYNCWORDL) == SYNCWORDL) {
int32_t bytesAvailable = nBytes - i;
if (!validate(&buf[i], bytesAvailable)) { continue; }
int frame_length = ((buf[i + 3] & 0x03) << 11) | (buf[i + 4] << 3) | ((buf[i + 5] & 0xE0) >> 5);
if (i + frame_length + 1 >= nBytes) {
return -1; // Puffergrenze überschritten, kein gültiger Header
}
/* find a second byte-aligned syncword (12 bits = 0xFFF) */
if ((buf[i + frame_length + 0] & SYNCWORDH) == SYNCWORDH && (buf[i + frame_length + 1] & SYNCWORDL) == SYNCWORDL) { return i; }
}
}
return -1;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint8_t AACDecoder::getChannels() {
return m_aacChannels;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint32_t AACDecoder::getSampleRate() {
return m_aacSamplerate;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint32_t AACDecoder::getOutputSamples() {
return m_validSamples;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint8_t AACDecoder::getBitsPerSample() {
return 16;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint32_t AACDecoder::getBitRate() {
uint32_t br = getBitsPerSample() * getChannels() * getSampleRate();
return (br / m_compressionRatio);
;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint32_t AACDecoder::getAudioDataStart() {
return 0; // nothing todo
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint32_t AACDecoder::getAudioFileDuration() {
return 0; // nothing todo
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
const char* AACDecoder::getStreamTitle() {
return nullptr; // nothing todo
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
const char* AACDecoder::whoIsIt() {
return "AAC";
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
error_info_t AACDecoder::getErrorMessage(int8_t err) {
return m_neaacdec->NeAACDecGetErrorMessage(abs(err));
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
int32_t AACDecoder::decode(uint8_t* inbuf, int32_t* bytesLeft, int32_t* outbuf) {
uint8_t* ob = (uint8_t*)m_out16.get();
if (m_f_firstCall == false) {
if (m_f_setRaWBlockParams) { // set raw AAC values, e.g. for M4A config.
m_f_setRaWBlockParams = false;
m_conf->defSampleRate = m_aacSamplerate;
m_conf->outputFormat = FAAD_FMT_16BIT;
m_conf->useOldADTSFormat = 1;
m_conf->defObjectType = 2;
int8_t ret = m_neaacdec->NeAACDecSetConfiguration(m_hAac, m_conf);
(void)ret;
uint8_t specificInfo[2];
createAudioSpecificConfig(specificInfo, m_aacProfile, m_neaacdec->get_sr_index(m_aacSamplerate), m_aacChannels);
int8_t err = m_neaacdec->NeAACDecInit2(m_hAac, specificInfo, 2, &m_aacSamplerate, &m_aacChannels);
(void)err;
} else {
m_neaacdec->NeAACDecSetConfiguration(m_hAac, m_conf);
int8_t err = m_neaacdec->NeAACDecInit(m_hAac, inbuf, *bytesLeft, &m_aacSamplerate, &m_aacChannels);
(void)err;
}
m_f_firstCall = true;
}
m_neaacdec->NeAACDecDecode2(m_hAac, &m_frameInfo, inbuf, *bytesLeft, (void**)&ob, 2048 * 2 * sizeof(int16_t));
*bytesLeft -= m_frameInfo.bytesconsumed;
m_validSamples = m_frameInfo.samples;
int8_t err = 0 - m_frameInfo.error;
m_compressionRatio = (float)m_frameInfo.samples * 2 / m_frameInfo.bytesconsumed;
if (err < 0) {
if (err == -100) return AAC_ID3_HDR; // ID3 header found
else{
if(getErrorMessage(abs(err)).level == AAC_ERROR) AAC_LOG_ERROR("{}", getErrorMessage(abs(err)).text);
if(getErrorMessage(abs(err)).level == AAC_WARN) AAC_LOG_WARN("{}", getErrorMessage(abs(err)).text);
if(getErrorMessage(abs(err)).level == AAC_INFO) AAC_LOG_INFO("{}", getErrorMessage(abs(err)).text);
if(getErrorMessage(abs(err)).level == AAC_DEBUG) AAC_LOG_DEBUG("{}", getErrorMessage(abs(err)).text);
if(getErrorMessage(abs(err)).level == AAC_VERBOSE) AAC_LOG_VERBOSE("{}", getErrorMessage(abs(err)).text);
}
} else {
if (m_aacChannels == 1) {
for (int i = 0; i < m_validSamples; i++) {
outbuf[i * 2] = m_out16[i] << 16;
outbuf[i * 2 + 1] = m_out16[i] << 16;
}
}
if (m_aacChannels == 2) {
for (int i = 0; i < m_validSamples * 2; i++) { outbuf[i] = m_out16[i] << 16; }
}
}
return err;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
void AACDecoder::setRawBlockParams(uint8_t channels, uint32_t sampleRate, uint8_t dummy1, uint32_t profile, uint32_t dummy2) {
m_f_setRaWBlockParams = true;
m_aacChannels = channels; // 1: Mono, 2: Stereo
m_aacSamplerate = sampleRate; // 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000
m_aacProfile = profile; // 1: AAC Main, 2: AAC LC (Low Complexity), 3: AAC SSR (Scalable Sample Rate), 4: AAC LTP (Long Term Prediction)
return;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
std::vector<uint32_t> AACDecoder::getMetadataBlockPicture() {
std::vector<uint32_t> a;
return a;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
const char* AACDecoder::arg1() { // AAC format
m_arg1.assign("AAC HeaderFormat: ");
if (m_frameInfo.header_type == 0)
m_arg1.append("RAW");
else if (m_frameInfo.header_type == 1)
m_arg1.append("ADIF"); /* single ADIF header at the beginning of the file */
else if (m_frameInfo.header_type == 2)
m_arg1.append("ADTS"); /* ADTS header at the beginning of each frame */
else
m_arg1.append("unknown");
return m_arg1.c_get();
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
const char* AACDecoder::arg2() {
if (m_frameInfo.sbr == 1) return "upsampled SBR";
if (m_frameInfo.sbr == 2) return "downsampled SBR";
if (m_frameInfo.sbr == 3) return "no SBR used, but file is upsampled by a factor 2";
return "without SBR";
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
int32_t AACDecoder::val1() { // Parametric Stereo
return m_frameInfo.isPS;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
int32_t AACDecoder::val2() { // Spectral Band Replication
return m_frameInfo.sbr; // NO_SBR 0 /* no SBR used in this file */
// SBR_UPSAMPLED 1 /* upsampled SBR used */
// SBR_DOWNSAMPLED 2 /* downsampled SBR used */
// NO_SBR_UPSAMPLED 3 /* no SBR used, but file is upsampled by a factor 2 anyway */
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
void AACDecoder::createAudioSpecificConfig(uint8_t* config, uint8_t audioObjectType, uint8_t samplingFrequencyIndex, uint8_t channelConfiguration) {
config[0] = (audioObjectType << 3) | (samplingFrequencyIndex >> 1);
config[1] = (samplingFrequencyIndex << 7) | (channelConfiguration << 3);
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// extern uint8_t NeaacDecoder::get_sr_index(const uint32_t samplerate);
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

View File

@@ -0,0 +1,82 @@
/*
* aac_decoder.h
* faad2 - ESP32 adaptation
* Created on: 12.09.2023
* Updated on: 13.06.2026
*/
#pragma once
#include "../Audio.h"
#include "libfaad/aac_settings.h"
#include "libfaad/aac_structs.h"
#include "libfaad/aac_defines.h"
#include "libfaad/aac_tables.h"
#include "libfaad/neaacdec.h"
#pragma GCC diagnostic warning "-Wunused-function"
class AACDecoder : public Decoder {
public:
enum : int8_t {
AAC_ID3_HDR = 100,
AAC_NONE = 0,
AAC_ERR = -1,
};
AACDecoder(Audio& audioRef);
~AACDecoder() { reset(); }
bool init() override;
void clear() override;
void reset() override;
bool isValid() override;
int32_t findSyncWord(uint8_t* buf, int32_t nBytes) override;
uint8_t getChannels() override;
uint32_t getSampleRate() override;
uint32_t getOutputSamples();
uint8_t getBitsPerSample() override;
uint32_t getBitRate() override;
uint32_t getAudioDataStart() override;
uint32_t getAudioFileDuration() override;
const char* getStreamTitle() override;
const char* whoIsIt() override;
int32_t decode(uint8_t* inbuf, int32_t* bytesLeft, int32_t* outbuf) override;
void setRawBlockParams(uint8_t channels, uint32_t sampleRate, uint8_t BPS, uint32_t tsis, uint32_t AuDaLength) override;
std::vector<uint32_t> getMetadataBlockPicture() override;
const char* arg1() override;
const char* arg2() override;
virtual int32_t val1() override; // Paramertric Stereo
virtual int32_t val2() override; // SBR
private:
Audio& audio;
ps_ptr<char> m_arg1;
ps_ptr<int16_t> m_out16;
void createAudioSpecificConfig(uint8_t* config, uint8_t audioObjectType, uint8_t samplingFrequencyIndex, uint8_t channelConfiguration);
error_info_t getErrorMessage(int8_t err);
NeAACDecHandle m_hAac;
NeAACDecFrameInfo m_frameInfo;
NeAACDecConfigurationPtr m_conf;
const uint8_t SYNCWORDH = 0xff; /* 12-bit syncword */
const uint8_t SYNCWORDL = 0xf0;
bool m_f_decoderIsInit = false;
bool m_f_firstCall = false;
bool m_f_setRaWBlockParams = false;
uint32_t m_aacSamplerate = 0;
uint8_t m_aacChannels = 0;
uint8_t m_aacProfile = 0;
uint16_t m_validSamples = 0;
float m_compressionRatio = 1;
std::unique_ptr<NeaacDecoder> m_neaacdec;
struct AudioSpecificConfig {
uint8_t audioObjectType;
uint8_t samplingFrequencyIndex;
uint8_t channelConfiguration;
};
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
};

View File

@@ -0,0 +1,450 @@
#pragma once
#include "Arduino.h"
#include "../../Audio.h"
#include "aac_settings.h"
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/* defines if an object type can be decoded by this library or not */
__unused static uint8_t ObjectTypesTable[32] = {
0, /* 0 NULL */
#ifdef MAIN_DEC
1, /* 1 AAC Main */
#else
0, /* 1 AAC Main */
#endif
1, /* 2 AAC LC */
#ifdef SSR_DEC
1, /* 3 AAC SSR */
#else
0, /* 3 AAC SSR */
#endif
#ifdef LTP_DEC
1, /* 4 AAC LTP */
#else
0, /* 4 AAC LTP */
#endif
#ifdef SBR_DEC
1, /* 5 SBR */
#else
0, /* 5 SBR */
#endif
0, /* 6 AAC Scalable */
0, /* 7 TwinVQ */
0, /* 8 CELP */
0, /* 9 HVXC */
0, /* 10 Reserved */
0, /* 11 Reserved */
0, /* 12 TTSI */
0, /* 13 Main synthetic */
0, /* 14 Wavetable synthesis */
0, /* 15 General MIDI */
0, /* 16 Algorithmic Synthesis and Audio FX */
/* MPEG-4 Version 2 */
#ifdef ERROR_RESILIENCE
1, /* 17 ER AAC LC */
0, /* 18 (Reserved) */
#ifdef LTP_DEC
1, /* 19 ER AAC LTP */
#else
0, /* 19 ER AAC LTP */
#endif
0, /* 20 ER AAC scalable */
0, /* 21 ER TwinVQ */
0, /* 22 ER BSAC */
#ifdef LD_DEC
1, /* 23 ER AAC LD */
#else
0, /* 23 ER AAC LD */
#endif
0, /* 24 ER CELP */
0, /* 25 ER HVXC */
0, /* 26 ER HILN */
0, /* 27 ER Parametric */
#else /* No ER defined */
0, /* 17 ER AAC LC */
0, /* 18 (Reserved) */
0, /* 19 ER AAC LTP */
0, /* 20 ER AAC scalable */
0, /* 21 ER TwinVQ */
0, /* 22 ER BSAC */
0, /* 23 ER AAC LD */
0, /* 24 ER CELP */
0, /* 25 ER HVXC */
0, /* 26 ER HILN */
0, /* 27 ER Parametric */
#endif
0, /* 28 (Reserved) */
#ifdef PS_DEC
1, /* 29 AAC LC + SBR + PS */
#else
0, /* 29 AAC LC + SBR + PS */
#endif
0, /* 30 (Reserved) */
0 /* 31 (Reserved) */
};
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
#define ZERO_HCB 0
#define FIRST_PAIR_HCB 5
#define ESC_HCB 11
#define QUAD_LEN 4
#define PAIR_LEN 2
#define NOISE_HCB 13
#define INTENSITY_HCB2 14
#define INTENSITY_HCB 15
#define DRC_REF_LEVEL 20 * 4 /* -20 dB */
#define DRM_PARAMETRIC_STEREO 0
#define DRM_NUM_SA_BANDS 8
#define DRM_NUM_PAN_BANDS 20
#define NUM_OF_LINKS 3
#define NUM_OF_QMF_CHANNELS 64
#define NUM_OF_SUBSAMPLES 30
#define MAX_SA_BAND 46
#define MAX_PAN_BAND 64
#define MAX_DELAY 5
#define EXTENSION_ID_PS 2
#define MAX_PS_ENVELOPES 5
#define NO_ALLPASS_LINKS 3
#define BYTE_NUMBIT 8
#define BYTE_NUMBIT_LD 3
#define bit2byte(a) ((a + 7) >> BYTE_NUMBIT_LD)
#define NUM_ERROR_MESSAGES 34
#define ESC_VAL 7
#define SSR_BANDS 4
#define PQFTAPS 96
#ifdef DRM
#define DECAY_CUTOFF 3
#define DECAY_SLOPE 0.05f
/* type definitaions */
typedef const int8_t (*drm_ps_huff_tab)[2];
#endif
#define FLOAT_SCALE (1.0f / (1 << 15))
#define DM_MUL REAL_CONST(0.3203772410170407) // 1/(1+sqrt(2) + 1/sqrt(2))
#define RSQRT2 REAL_CONST(0.7071067811865475244) // 1/sqrt(2)
#define NUM_CB 6
#define NUM_CB_ER 22
#define MAX_CB 32
#define VCB11_FIRST 16
#define VCB11_LAST 31
#define TNS_MAX_ORDER 20
#define MAIN 1
#define LC 2
#define SSR 3
#define LTP 4
#define HE_AAC 5
#define LD 23
#define ER_LC 17
#define ER_LTP 19
#define DRM_ER_LC 27 /* special object type for DRM */
/* header types */
#define RAW 0
#define ADIF 1
#define ADTS 2
#define LATM 3
/* SBR signalling */
#define NO_SBR 0
#define SBR_UPSAMPLED 1
#define SBR_DOWNSAMPLED 2
#define NO_SBR_UPSAMPLED 3
/* DRM channel definitions */
#define DRMCH_MONO 1
#define DRMCH_STEREO 2
#define DRMCH_SBR_MONO 3
#define DRMCH_SBR_STEREO 4
#define DRMCH_SBR_PS_STEREO 5
/* First object type that has ER */
#define ER_OBJECT_START 17
/* Bitstream */
#define LEN_SE_ID 3
#define LEN_TAG 4
#define LEN_BYTE 8
#define EXT_FIL 0
#define EXT_FILL_DATA 1
#define EXT_DATA_ELEMENT 2
#define EXT_DYNAMIC_RANGE 11
#define ANC_DATA 0
/* Syntax elements */
#define ID_SCE 0x0
#define ID_CPE 0x1
#define ID_CCE 0x2
#define ID_LFE 0x3
#define ID_DSE 0x4
#define ID_PCE 0x5
#define ID_FIL 0x6
#define ID_END 0x7
#define INVALID_ELEMENT_ID 255
#define ONLY_LONG_SEQUENCE 0x0
#define LONG_START_SEQUENCE 0x1
#define EIGHT_SHORT_SEQUENCE 0x2
#define LONG_STOP_SEQUENCE 0x3
#define ZERO_HCB 0
#define FIRST_PAIR_HCB 5
#define ESC_HCB 11
#define QUAD_LEN 4
#define PAIR_LEN 2
#define NOISE_HCB 13
#define INTENSITY_HCB2 14
#define INTENSITY_HCB 15
#define INVALID_SBR_ELEMENT 255
#define T_HFGEN 8
#define T_HFADJ 2
#define EXT_SBR_DATA 13
#define EXT_SBR_DATA_CRC 14
#define FIXFIX 0
#define FIXVAR 1
#define VARFIX 2
#define VARVAR 3
#define LO_RES 0
#define HI_RES 1
#define NO_TIME_SLOTS_960 15
#define NO_TIME_SLOTS 16
#define RATE 2
#define NOISE_FLOOR_OFFSET 6
#ifdef PS_DEC
#define NEGATE_IPD_MASK (0x1000)
#define DECAY_SLOPE FRAC_CONST(0.05)
#define COEF_SQRT2 COEF_CONST(1.4142135623731)
#endif // PS_DEC
#define MAX_NTSRHFG 40 /* MAX_NTSRHFG: maximum of number_time_slots * rate + HFGen. 16*2+8 */
#define MAX_NTSR 32 /* max number_time_slots * rate, ok for DRM and not DRM mode */
#define MAX_M 49 /* MAX_M: maximum value for M */
#define MAX_L_E 5 /* MAX_L_E: maximum value for L_E */
#ifdef SBR_DEC
#ifdef FIXED_POINT
#define _EPS (1) /* smallest number available in fixed point */
#else
#define _EPS (1e-12)
#endif
#endif // SBR_DEC
#ifdef FIXED_POINT /* int32_t */
#define LOG2_MIN_INF REAL_CONST(-10000)
#define COEF_BITS 28
#define COEF_PRECISION (1 << COEF_BITS)
#define REAL_BITS 14 // MAXIMUM OF 14 FOR FIXED POINT SBR
#define REAL_PRECISION (1 << REAL_BITS)
/* FRAC is the fractional only part of the fixed point number [0.0..1.0) */
#define FRAC_SIZE 32 /* frac is a 32 bit integer */
#define FRAC_BITS 31
#define FRAC_PRECISION ((uint32_t)(1 << FRAC_BITS))
#define FRAC_MAX 0x7FFFFFFF
typedef int32_t real_t;
#define REAL_CONST(A) (((A) >= 0) ? ((real_t)((A) * (REAL_PRECISION) + 0.5)) : ((real_t)((A) * (REAL_PRECISION) - 0.5)))
#define COEF_CONST(A) (((A) >= 0) ? ((real_t)((A) * (COEF_PRECISION) + 0.5)) : ((real_t)((A) * (COEF_PRECISION) - 0.5)))
#define FRAC_CONST(A) (((A) == 1.00) ? ((real_t)FRAC_MAX) : (((A) >= 0) ? ((real_t)((A) * (FRAC_PRECISION) + 0.5)) : ((real_t)((A) * (FRAC_PRECISION) - 0.5))))
// #define FRAC_CONST(A) (((A) >= 0) ? ((real_t)((A)*(FRAC_PRECISION)+0.5)) : ((real_t)((A)*(FRAC_PRECISION)-0.5)))
#define Q2_BITS 22
#define Q2_PRECISION (1 << Q2_BITS)
#define Q2_CONST(A) (((A) >= 0) ? ((real_t)((A) * (Q2_PRECISION) + 0.5)) : ((real_t)((A) * (Q2_PRECISION) - 0.5)))
/* multiply with real shift */
#define MUL_R(A, B) (real_t)(((int64_t)(A) * (int64_t)(B) + (1 << (REAL_BITS - 1))) >> REAL_BITS)
/* multiply with coef shift */
#define MUL_C(A, B) (real_t)(((int64_t)(A) * (int64_t)(B) + (1 << (COEF_BITS - 1))) >> COEF_BITS)
/* multiply with fractional shift */
#define _MulHigh(A, B) (real_t)(((int64_t)(A) * (int64_t)(B) + (1 << (FRAC_SIZE - 1))) >> FRAC_SIZE)
#define MUL_F(A, B) (real_t)(((int64_t)(A) * (int64_t)(B) + (1 << (FRAC_BITS - 1))) >> FRAC_BITS)
#define MUL_Q2(A, B) (real_t)(((int64_t)(A) * (int64_t)(B) + (1 << (Q2_BITS - 1))) >> Q2_BITS)
#define MUL_SHIFT6(A, B) (real_t)(((int64_t)(A) * (int64_t)(B) + (1 << (6 - 1))) >> 6)
#define MUL_SHIFT23(A, B) (real_t)(((int64_t)(A) * (int64_t)(B) + (1 << (23 - 1))) >> 23)
#define DIV_R(A, B) (((int64_t)A << REAL_BITS) / B)
#define DIV_C(A, B) (((int64_t)A << COEF_BITS) / B)
/* Complex multiplication */
static inline void ComplexMult(real_t* y1, real_t* y2, real_t x1, real_t x2, real_t c1, real_t c2) { // FIXED POINT
*y1 = (_MulHigh(x1, c1) + _MulHigh(x2, c2)) << (FRAC_SIZE - FRAC_BITS);
*y2 = (_MulHigh(x2, c1) - _MulHigh(x1, c2)) << (FRAC_SIZE - FRAC_BITS);
}
// static inline void ComplexMult(int32_t* y1, int32_t* y2, int32_t x1, int32_t x2, int32_t c1, int32_t c2) { // only XTENSA chips
// asm volatile (
// // y1 = (x1 * c1) + (x2 * c2)
// "mulsh a2, %2, %4\n" // a2 = x1 * c1 (Low 32 bits)
// "mulsh a3, %3, %5\n" // a3 = x2 * c2 (Low 32 bits)
// "add a2, a2, a3\n" // a2 = (x1 * c1) + (x2 * c2)
// "slli a2, a2, 1\n" // a2 = a2 >> 31 (Fixed-Point scaling)
// "s32i a2, %0 \n" // Store result in *y1
// // y2 = (x2 * c1) - (x1 * c2)
// "mulsh a2, %3, %4\n" // a2 = x2 * c1 (Low 32 bits)
// "mulsh a3, %2, %5\n" // a3 = x1 * c2 (Low 32 bits)
// "sub a2, a2, a3\n" // a2 = (x2 * c1) - (x1 * c2)
// "slli a2, a2, 1\n" // a2 = a2 >> 31 (Fixed-Point scaling)
// "s32i a2, %1 \n" // Store result in *y2
// : "=m" (*y1), "=m" (*y2) // Output
// : "r" (x1), "r" (x2), "r" (c1), "r" (c2) // Input
// : "a2", "a3" // Clobbers
// );
// }
#define DIV(A, B) (((int64_t)A << REAL_BITS) / B)
#define step(shift) \
if ((0x40000000l >> shift) + root <= value) { \
value -= (0x40000000l >> shift) + root; \
root = (root >> 1) | (0x40000000l >> shift); \
} else { \
root = root >> 1; \
}
real_t const pow2_table[] = {COEF_CONST(1.0), COEF_CONST(1.18920711500272), COEF_CONST(1.41421356237310), COEF_CONST(1.68179283050743)};
#endif // FIXED_POINT
#ifndef FIXED_POINT
#ifdef MAIN_DEC
#define ALPHA REAL_CONST(0.90625)
#define A REAL_CONST(0.953125)
#endif
#define IQ_TABLE_SIZE 8192
#define DIV_R(A, B) ((A) / (B))
#define DIV_C(A, B) ((A) / (B))
#ifdef USE_DOUBLE_PRECISION /* double */
typedef double real_t;
#include <math.h>
#define MUL_R(A, B) ((A) * (B))
#define MUL_C(A, B) ((A) * (B))
#define MUL_F(A, B) ((A) * (B))
#define REAL_CONST(A) ((real_t)(A))
#define COEF_CONST(A) ((real_t)(A))
#define Q2_CONST(A) ((real_t)(A))
#define FRAC_CONST(A) ((real_t)(A)) /* pure fractional part */
/* Complex multiplication */
static void ComplexMult(real_t* y1, real_t* y2, real_t x1, real_t x2, real_t c1, real_t c2) {
*y1 = MUL_F(x1, c1) + MUL_F(x2, c2);
*y2 = MUL_F(x2, c1) - MUL_F(x1, c2);
}
#else /* Normal floating point operation */
typedef float real_t;
#define MUL_R(A, B) ((A) * (B))
#define MUL_C(A, B) ((A) * (B))
#define MUL_F(A, B) ((A) * (B))
#define REAL_CONST(A) ((real_t)(A))
#define COEF_CONST(A) ((real_t)(A))
#define Q2_CONST(A) ((real_t)(A))
#define FRAC_CONST(A) ((real_t)(A)) /* pure fractional part */
/* Complex multiplication */
__unused static void ComplexMult(real_t* y1, real_t* y2, real_t x1, real_t x2, real_t c1, real_t c2) {
*y1 = MUL_F(x1, c1) + MUL_F(x2, c2);
*y2 = MUL_F(x2, c1) - MUL_F(x1, c2);
}
#endif /* USE_DOUBLE_PRECISION */
#endif // FIXED_POINT
#ifdef SBR_LOW_POWER
#define qmf_t real_t
#define QMF_RE(A) (A)
#define QMF_IM(A)
#else
#define qmf_t complex_t
#define QMF_RE(A) RE(A)
#define QMF_IM(A) IM(A)
#endif
typedef real_t complex_t[2];
#define RE(A) A[0]
#define IM(A) A[1]
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#if !defined(max) && !defined(__cplusplus)
#define max(a, b) (((a) > (b)) ? (a) : (b))
#endif
#if !defined(min) && !defined(__cplusplus)
#define min(a, b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef FAAD2_VERSION
#define FAAD2_VERSION "unknown"
#endif
/* object types for AAC */
#define MAIN 1
#define LC 2
#define SSR 3
#define LTP 4
#define HE_AAC 5
#define ER_LC 17
#define ER_LTP 19
#define LD 23
#define DRM_ER_LC 27 /* special object type for DRM */
/* header types */
#define RAW 0
#define ADIF 1
#define ADTS 2
#define LATM 3
/* SBR signalling */
#define NO_SBR 0
#define SBR_UPSAMPLED 1
#define SBR_DOWNSAMPLED 2
#define NO_SBR_UPSAMPLED 3
/* library output formats */
#define FAAD_FMT_16BIT 1
#define FAAD_FMT_24BIT 2
#define FAAD_FMT_32BIT 3
#define FAAD_FMT_FLOAT 4
#define FAAD_FMT_FIXED FAAD_FMT_FLOAT
#define FAAD_FMT_DOUBLE 5
/* Capabilities */
#define LC_DEC_CAP (1 << 0) /* Can decode LC */
#define MAIN_DEC_CAP (1 << 1) /* Can decode MAIN */
#define LTP_DEC_CAP (1 << 2) /* Can decode LTP */
#define LD_DEC_CAP (1 << 3) /* Can decode LD */
#define ERROR_RESILIENCE_CAP (1 << 4) /* Can decode ER */
#define FIXED_POINT_CAP (1 << 5) /* Fixed point */
/* Channel definitions */
#define FRONT_CHANNEL_CENTER (1)
#define FRONT_CHANNEL_LEFT (2)
#define FRONT_CHANNEL_RIGHT (3)
#define SIDE_CHANNEL_LEFT (4)
#define SIDE_CHANNEL_RIGHT (5)
#define BACK_CHANNEL_LEFT (6)
#define BACK_CHANNEL_RIGHT (7)
#define BACK_CHANNEL_CENTER (8)
#define LFE_CHANNEL (9)
#define UNKNOWN_CHANNEL (0)
/* DRM channel definitions */
#define DRMCH_MONO 1
#define DRMCH_STEREO 2
#define DRMCH_SBR_MONO 3
#define DRMCH_SBR_STEREO 4
#define DRMCH_SBR_PS_STEREO 5
/* A decode call can eat up to FAAD_MIN_STREAMSIZE bytes per decoded channel,
so at least so much bytes per channel should be available in this stream */
#define FAAD_MIN_STREAMSIZE 768 /* 6144 bits/channel */
#define MAX_CHANNELS 64
#define MAX_SYNTAX_ELEMENTS 48
#define MAX_WINDOW_GROUPS 8
#define MAX_SFB 51
#define MAX_LTP_SFB 40
#define MAX_LTP_SFB_S 8
#define MAX_ASC_BYTES 64
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
#ifndef FIXED_POINT
#ifndef HAS_LRINTF
#define CLIP(sample, max, min) \
if (sample >= 0.0f) { \
sample += 0.5f; \
if (sample >= max) sample = max; \
} else { \
sample += -0.5f; \
if (sample <= min) sample = min; \
}
#else
#define CLIP(sample, max, min) \
if (sample >= 0.0f) { \
if (sample >= max) sample = max; \
} else { \
if (sample <= min) sample = min; \
}
#endif
#define CONV(a, b) ((a << 1) | (b & 0x1))
#endif
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// Macro for comfortable calls
#define AAC_LOG_ERROR(fmt, ...) Audio::AUDIO_LOG_IMPL(1, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define AAC_LOG_WARN(fmt, ...) Audio::AUDIO_LOG_IMPL(2, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define AAC_LOG_INFO(fmt, ...) Audio::AUDIO_LOG_IMPL(3, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define AAC_LOG_DEBUG(fmt, ...) Audio::AUDIO_LOG_IMPL(4, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define AAC_LOG_VERBOSE(fmt, ...) Audio::AUDIO_LOG_IMPL(5, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

View File

@@ -0,0 +1,90 @@
#pragma once
/* ----------------------COMPILE TIME DEFINITIONS ---------------- */
#define PREFER_POINTERS // Use if target platform has address generators with autoincrement
// #define BIG_IQ_TABLE
// #define USE_DOUBLE_PRECISION // use double precision
// #define FIXED_POINT // use fixed point reals, undefs MAIN_DEC and SSR_DEC
// #define ERROR_RESILIENCE 2
// #define MAIN_DEC // Allow decoding of MAIN profile AAC
// #define SSR_DEC // Allow decoding of SSR profile AAC
#define LTP_DEC // Allow decoding of LTP (Long Term Prediction) profile AAC
#define LD_DEC // Allow decoding of LD (Low Delay) profile AAC
// #define DRM_SUPPORT // Allow decoding of Digital Radio Mondiale (DRM)
#if (defined CONFIG_IDF_TARGET_ESP32S3 || defined CONFIG_IDF_TARGET_ESP32P4)
#define SBR_DEC // Allow decoding of SBR (Spectral Band Replication) profile AAC
#define PS_DEC // Allow decoding of PS (Parametric Stereo) profile AAC
#endif
// #define SBR_LOW_POWER
#define ALLOW_SMALL_FRAMELENGTH
// #define LC_ONLY_DECODER // if you want a pure AAC LC decoder (independant of SBR_DEC and PS_DEC)
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
#ifdef DRM_SUPPORT // Allow decoding of Digital Radio Mondiale (DRM)
#define DRM
#define DRM_PS
#undef PS_DEC
#endif
#ifdef LD_DEC /* LD can't do without LTP */
#ifndef ERROR_RESILIENCE
#define ERROR_RESILIENCE
#endif
#ifndef LTP_DEC
#define LTP_DEC
#endif
#endif
#ifdef LC_ONLY_DECODER
#undef LD_DEC
#undef LTP_DEC
#undef MAIN_DEC
#undef SSR_DEC
#undef DRM
#undef DRM_PS
#undef ALLOW_SMALL_FRAMELENGTH
#undef ERROR_RESILIENCE
#endif
#ifdef SBR_LOW_POWER
#undef PS_DEC
#endif
#ifdef FIXED_POINT /* No MAIN decoding */
#ifdef MAIN_DEC
#undef MAIN_DEC
#endif
#endif // FIXED_POINT
#ifdef DRM
#ifndef ALLOW_SMALL_FRAMELENGTH
#define ALLOW_SMALL_FRAMELENGTH
#endif
#undef LD_DEC
#undef LTP_DEC
#undef MAIN_DEC
#undef SSR_DEC
#endif
/* END COMPILE TIME DEFINITIONS */
#ifdef WORDS_BIGENDIAN
#define ARCH_IS_BIG_ENDIAN
#endif
/* FIXED_POINT doesn't work with MAIN and SSR yet */
#ifdef FIXED_POINT
#undef MAIN_DEC
#undef SSR_DEC
#endif
#if defined(FIXED_POINT)
#elif defined(USE_DOUBLE_PRECISION)
#else /* Normal floating point operation */
#ifdef HAVE_LRINTF
#define HAS_LRINTF
#define _ISOC9X_SOURCE 1
#define _ISOC99_SOURCE 1
#define __USE_ISOC9X 1
#define __USE_ISOC99 1
#endif
#endif
#ifndef HAS_LRINTF
/* standard cast */
// #define int32_t(f) ((int32_t)(f))
#endif

View File

@@ -0,0 +1,672 @@
/*
** FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR decoding
** Copyright (C) 2003-2005 M. Bakker, Nero AG, http://www.nero.com
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program 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 General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
** Any non-GPL usage of this software or parts of this software is strictly
** forbidden.
**
** The "appropriate copyright message" mentioned in section 2c of the GPLv2
** must read: "Code from FAAD2 is copyright (c) Nero AG, www.nero.com"
**
** Commercial non-GPL licensing of this software is possible.
** For more info contact Nero AG through Mpeg4AAClicense@nero.com.
**
** $Id: structs.h,v 1.49 2009/01/26 23:51:15 menno Exp $
**/
#pragma once
#include "Arduino.h"
#include "aac_defines.h"
#include "aac_settings.h"
typedef void* NeAACDecHandle;
typedef struct mp4AudioSpecificConfig {
/* Audio Specific Info */
unsigned char objectTypeIndex;
unsigned char samplingFrequencyIndex;
uint32_t samplingFrequency;
unsigned char channelsConfiguration;
/* GA Specific Info */
unsigned char frameLengthFlag;
unsigned char dependsOnCoreCoder;
unsigned short coreCoderDelay;
unsigned char extensionFlag;
unsigned char aacSectionDataResilienceFlag;
unsigned char aacScalefactorDataResilienceFlag;
unsigned char aacSpectralDataResilienceFlag;
unsigned char epConfig;
char sbr_present_flag;
char forceUpSampling;
char downSampledSBR;
} mp4AudioSpecificConfig;
typedef struct NeAACDecFrameInfo {
uint32_t bytesconsumed;
uint32_t samples;
unsigned char channels;
unsigned char error;
uint32_t samplerate;
/* SBR: 0: off, 1: on; upsample, 2: on; downsampled, 3: off; upsampled */
unsigned char sbr;
/* MPEG-4 ObjectType */
unsigned char object_type;
/* AAC header type; MP4 will be signalled as RAW also */
unsigned char header_type;
/* multichannel configuration */
unsigned char num_front_channels;
unsigned char num_side_channels;
unsigned char num_back_channels;
unsigned char num_lfe_channels;
unsigned char channel_position[64];
/* PS: 0: off, 1: on */
unsigned char ps;
uint8_t isPS;
} NeAACDecFrameInfo;
/* used to save the prediction state */
typedef struct {
uint16_t n;
uint16_t ifac[15];
complex_t* work;
complex_t* tab;
} cfft_info;
typedef struct {
int16_t r[2];
int16_t COR[2];
int16_t VAR[2];
} pred_state;
typedef struct {
uint16_t N;
cfft_info* cfft;
complex_t* sincos;
int64_t cycles;
int64_t fft_cycles;
} mdct_info;
typedef struct {
const real_t* long_window[2];
const real_t* short_window[2];
const real_t* ld_window[2];
int64_t cycles;
} fb_info;
typedef struct {
uint8_t present;
uint8_t num_bands;
uint8_t pce_instance_tag;
uint8_t excluded_chns_present;
uint8_t band_top[17];
uint8_t prog_ref_level;
uint8_t dyn_rng_sgn[17];
uint8_t dyn_rng_ctl[17];
uint8_t exclude_mask[MAX_CHANNELS];
uint8_t additional_excluded_chns[MAX_CHANNELS];
real_t ctrl1;
real_t ctrl2;
} drc_info;
typedef struct {
uint8_t element_instance_tag;
uint8_t object_type;
uint8_t sf_index;
uint8_t num_front_channel_elements;
uint8_t num_side_channel_elements;
uint8_t num_back_channel_elements;
uint8_t num_lfe_channel_elements;
uint8_t num_assoc_data_elements;
uint8_t num_valid_cc_elements;
uint8_t mono_mixdown_present;
uint8_t mono_mixdown_element_number;
uint8_t stereo_mixdown_present;
uint8_t stereo_mixdown_element_number;
uint8_t matrix_mixdown_idx_present;
uint8_t pseudo_surround_enable;
uint8_t matrix_mixdown_idx;
uint8_t front_element_is_cpe[16];
uint8_t front_element_tag_select[16];
uint8_t side_element_is_cpe[16];
uint8_t side_element_tag_select[16];
uint8_t back_element_is_cpe[16];
uint8_t back_element_tag_select[16];
uint8_t lfe_element_tag_select[16];
uint8_t assoc_data_element_tag_select[16];
uint8_t cc_element_is_ind_sw[16];
uint8_t valid_cc_element_tag_select[16];
uint8_t channels;
uint8_t comment_field_bytes;
uint8_t comment_field_data[257];
uint8_t num_front_channels; /* extra added values */
uint8_t num_side_channels;
uint8_t num_back_channels;
uint8_t num_lfe_channels;
uint8_t sce_channel[16];
uint8_t cpe_channel[16];
} program_config;
typedef struct {
uint16_t syncword;
uint8_t id;
uint8_t layer;
uint8_t protection_absent;
uint8_t profile;
uint8_t sf_index;
uint8_t private_bit;
uint8_t channel_configuration;
uint8_t original;
uint8_t home;
uint8_t emphasis;
uint8_t copyright_identification_bit;
uint8_t copyright_identification_start;
uint16_t aac_frame_length;
uint16_t adts_buffer_fullness;
uint8_t no_raw_data_blocks_in_frame;
uint16_t crc_check;
uint8_t old_format; /* control param */
} adts_header;
typedef struct {
uint8_t copyright_id_present;
int8_t copyright_id[10];
uint8_t original_copy;
uint8_t home;
uint8_t bitstream_type;
uint32_t bitrate;
uint8_t num_program_config_elements;
uint32_t adif_buffer_fullness;
/* maximum of 16 PCEs */
program_config pce[16];
} adif_header;
typedef struct {
uint8_t last_band;
uint8_t data_present;
uint16_t lag;
uint8_t lag_update;
uint8_t coef;
uint8_t long_used[MAX_SFB];
uint8_t short_used[8];
uint8_t short_lag_present[8];
uint8_t short_lag[8];
} ltp_info;
typedef struct {
uint8_t limit;
uint8_t predictor_reset;
uint8_t predictor_reset_group_number;
uint8_t prediction_used[MAX_SFB];
} pred_info;
typedef struct {
uint8_t number_pulse;
uint8_t pulse_start_sfb;
uint8_t pulse_offset[4];
uint8_t pulse_amp[4];
} pulse_info;
typedef struct {
uint8_t n_filt[8];
uint8_t coef_res[8];
uint8_t length[8][4];
uint8_t order[8][4];
uint8_t direction[8][4];
uint8_t coef_compress[8][4];
uint8_t coef[8][4][32];
} tns_info;
typedef struct {
uint8_t max_band;
uint8_t adjust_num[4][8];
uint8_t alevcode[4][8][8];
uint8_t aloccode[4][8][8];
} ssr_info;
typedef struct {
uint8_t max_sfb;
uint8_t num_swb;
uint8_t num_window_groups;
uint8_t num_windows;
uint8_t window_sequence;
uint8_t window_group_length[8];
uint8_t window_shape;
uint8_t scale_factor_grouping;
uint16_t sect_sfb_offset[8][15 * 8];
uint16_t swb_offset[52];
uint16_t swb_offset_max;
uint8_t sect_cb[8][15 * 8];
uint16_t sect_start[8][15 * 8];
uint16_t sect_end[8][15 * 8];
uint8_t sfb_cb[8][8 * 15];
uint8_t num_sec[8]; /* number of sections in a group */
uint8_t global_gain;
int16_t scale_factors[8][51]; /* [0..255] */
uint8_t ms_mask_present;
uint8_t ms_used[MAX_WINDOW_GROUPS][MAX_SFB];
uint8_t noise_used;
uint8_t is_used;
uint8_t pulse_data_present;
uint8_t tns_data_present;
uint8_t gain_control_data_present;
uint8_t predictor_data_present;
pulse_info pul;
tns_info tns;
pred_info pred;
ltp_info ltp;
ltp_info ltp2;
ssr_info ssr;
uint16_t length_of_reordered_spectral_data; /* ER HCR data */
uint8_t length_of_longest_codeword;
uint8_t sf_concealment; /* ER RLVC data */
uint8_t rev_global_gain;
uint16_t length_of_rvlc_sf;
uint16_t dpcm_noise_nrg;
uint8_t sf_escapes_present;
uint8_t length_of_rvlc_escapes;
uint16_t dpcm_noise_last_position;
} ic_stream; /* individual channel stream */
typedef struct {
uint8_t channel;
int16_t paired_channel;
uint8_t element_instance_tag;
uint8_t common_window;
ic_stream ics1;
ic_stream ics2;
} element; /* syntax element (SCE, CPE, LFE) */
typedef struct {
int inited;
int version, versionA;
int framelen_type;
int useSameStreamMux;
int allStreamsSameTimeFraming;
int numSubFrames;
int numPrograms;
int numLayers;
int otherDataPresent;
uint32_t otherDataLenBits;
uint32_t frameLength;
uint8_t ASC[MAX_ASC_BYTES];
uint32_t ASCbits;
} latm_header;
typedef struct NeAACDecConfiguration {
unsigned char defObjectType;
unsigned long defSampleRate;
unsigned char outputFormat;
unsigned char downMatrix;
unsigned char useOldADTSFormat;
unsigned char dontUpSampleImplicitSBR;
} NeAACDecConfiguration, *NeAACDecConfigurationPtr;
typedef struct {
uint8_t drm_ps_data_available;
uint8_t bs_enable_sa;
uint8_t bs_enable_pan;
uint8_t bs_sa_dt_flag;
uint8_t bs_pan_dt_flag;
uint8_t g_last_had_sa;
uint8_t g_last_had_pan;
int8_t bs_sa_data[DRM_NUM_SA_BANDS];
int8_t bs_pan_data[DRM_NUM_PAN_BANDS];
int8_t g_sa_index[DRM_NUM_SA_BANDS];
int8_t g_pan_index[DRM_NUM_PAN_BANDS];
int8_t g_prev_sa_index[DRM_NUM_SA_BANDS];
int8_t g_prev_pan_index[DRM_NUM_PAN_BANDS];
int8_t sa_decode_error;
int8_t pan_decode_error;
int8_t g_last_good_sa_index[DRM_NUM_SA_BANDS];
int8_t g_last_good_pan_index[DRM_NUM_PAN_BANDS];
qmf_t SA[NUM_OF_SUBSAMPLES][MAX_SA_BAND];
complex_t d_buff[2][MAX_SA_BAND];
complex_t d2_buff[NUM_OF_LINKS][MAX_DELAY][MAX_SA_BAND];
uint8_t delay_buf_index_ser[NUM_OF_LINKS];
real_t prev_nrg[MAX_SA_BAND];
real_t prev_peakdiff[MAX_SA_BAND];
real_t peakdecay_fast[MAX_SA_BAND];
} drm_ps_info;
typedef struct {
/* bitstream parameters */
uint8_t enable_iid;
uint8_t enable_icc;
uint8_t enable_ext;
uint8_t iid_mode;
uint8_t icc_mode;
uint8_t nr_iid_par;
uint8_t nr_ipdopd_par;
uint8_t nr_icc_par;
uint8_t frame_class;
uint8_t num_env;
uint8_t border_position[MAX_PS_ENVELOPES + 1];
uint8_t iid_dt[MAX_PS_ENVELOPES];
uint8_t icc_dt[MAX_PS_ENVELOPES];
uint8_t enable_ipdopd;
uint8_t ipd_mode;
uint8_t ipd_dt[MAX_PS_ENVELOPES];
uint8_t opd_dt[MAX_PS_ENVELOPES];
/* indices */
int8_t iid_index_prev[34];
int8_t icc_index_prev[34];
int8_t ipd_index_prev[17];
int8_t opd_index_prev[17];
int8_t iid_index[MAX_PS_ENVELOPES][34];
int8_t icc_index[MAX_PS_ENVELOPES][34];
int8_t ipd_index[MAX_PS_ENVELOPES][17];
int8_t opd_index[MAX_PS_ENVELOPES][17];
int8_t ipd_index_1[17];
int8_t opd_index_1[17];
int8_t ipd_index_2[17];
int8_t opd_index_2[17];
/* ps data was correctly read */
uint8_t ps_data_available;
/* a header has been read */
uint8_t header_read;
/* hybrid filterbank parameters */
void* hyb;
uint8_t use34hybrid_bands;
uint8_t numTimeSlotsRate;
/**/
uint8_t num_groups;
uint8_t num_hybrid_groups;
uint8_t nr_par_bands;
uint8_t nr_allpass_bands;
uint8_t decay_cutoff;
uint8_t* group_border;
uint16_t* map_group2bk;
/* filter delay handling */
uint8_t saved_delay;
uint8_t delay_buf_index_ser[NO_ALLPASS_LINKS];
uint8_t num_sample_delay_ser[NO_ALLPASS_LINKS];
uint8_t delay_D[64];
uint8_t delay_buf_index_delay[64];
complex_t delay_Qmf[14][64]; /* 14 samples delay max, 64 QMF channels */
complex_t delay_SubQmf[2][32]; /* 2 samples delay max (SubQmf is always allpass filtered) */
complex_t delay_Qmf_ser[NO_ALLPASS_LINKS][5][64]; /* 5 samples delay max (table 8.34), 64 QMF channels */
complex_t delay_SubQmf_ser[NO_ALLPASS_LINKS][5][32]; /* 5 samples delay max (table 8.34) */
/* transients */
real_t alpha_decay;
real_t alpha_smooth;
real_t P_PeakDecayNrg[34];
real_t P_prev[34];
real_t P_SmoothPeakDecayDiffNrg_prev[34];
/* mixing and phase */
complex_t h11_prev[50];
complex_t h12_prev[50];
complex_t h21_prev[50];
complex_t h22_prev[50];
uint8_t phase_hist;
complex_t ipd_prev[20][2];
complex_t opd_prev[20][2];
} ps_info;
typedef struct {
real_t* x;
int16_t x_index;
uint8_t channels;
} qmfa_info;
typedef struct {
real_t* v;
int16_t v_index;
uint8_t channels;
} qmfs_info;
typedef struct {
uint32_t sample_rate;
uint32_t maxAACLine;
uint8_t rate;
uint8_t just_seeked;
uint8_t ret;
uint8_t amp_res[2];
uint8_t k0;
uint8_t kx;
uint8_t M;
uint8_t N_master;
uint8_t N_high;
uint8_t N_low;
uint8_t N_Q;
uint8_t N_L[4];
uint8_t n[2];
uint8_t f_master[64];
uint8_t f_table_res[2][64];
uint8_t f_table_noise[64];
uint8_t f_table_lim[4][64];
uint8_t f_group[5][64];
uint8_t N_G[5];
uint8_t table_map_k_to_g[64];
uint8_t abs_bord_lead[2];
uint8_t abs_bord_trail[2];
uint8_t n_rel_lead[2];
uint8_t n_rel_trail[2];
uint8_t L_E[2];
uint8_t L_E_prev[2];
uint8_t L_Q[2];
uint8_t t_E[2][MAX_L_E + 1];
uint8_t t_Q[2][3];
uint8_t f[2][MAX_L_E + 1];
uint8_t f_prev[2];
real_t* G_temp_prev[2][5];
real_t* Q_temp_prev[2][5];
int8_t GQ_ringbuf_index[2];
int16_t E[2][64][MAX_L_E];
int16_t E_prev[2][64];
real_t E_orig[2][64][MAX_L_E];
real_t E_curr[2][64][MAX_L_E];
int32_t Q[2][64][2];
real_t Q_div[2][64][2];
real_t Q_div2[2][64][2];
int32_t Q_prev[2][64];
int8_t l_A[2];
int8_t l_A_prev[2];
uint8_t bs_invf_mode[2][MAX_L_E];
uint8_t bs_invf_mode_prev[2][MAX_L_E];
real_t bwArray[2][64];
real_t bwArray_prev[2][64];
uint8_t noPatches;
uint8_t patchNoSubbands[64];
uint8_t patchStartSubband[64];
uint8_t bs_add_harmonic[2][64];
uint8_t bs_add_harmonic_prev[2][64];
uint16_t index_noise_prev[2];
uint8_t psi_is_prev[2];
uint8_t bs_start_freq_prev;
uint8_t bs_stop_freq_prev;
uint8_t bs_xover_band_prev;
uint8_t bs_freq_scale_prev;
uint8_t bs_alter_scale_prev;
uint8_t bs_noise_bands_prev;
int8_t prevEnvIsShort[2];
int8_t kx_prev;
uint8_t bsco;
uint8_t bsco_prev;
uint8_t M_prev;
uint16_t frame_len;
uint8_t Reset;
uint32_t frame;
uint32_t header_count;
uint8_t id_aac;
qmfa_info* qmfa[2];
qmfs_info* qmfs[2];
qmf_t Xsbr[2][MAX_NTSRHFG][64];
uint8_t Is_DRM_SBR;
drm_ps_info* drm_ps;
uint8_t numTimeSlotsRate;
uint8_t numTimeSlots;
uint8_t tHFGen;
uint8_t tHFAdj;
ps_info* ps;
uint8_t ps_used;
uint8_t psResetFlag;
/* to get it compiling */
/* we'll see during the coding of all the tools, whether
these are all used or not.
*/
uint8_t bs_header_flag;
uint8_t bs_crc_flag;
uint16_t bs_sbr_crc_bits;
uint8_t bs_protocol_version;
uint8_t bs_amp_res;
uint8_t bs_start_freq;
uint8_t bs_stop_freq;
uint8_t bs_xover_band;
uint8_t bs_freq_scale;
uint8_t bs_alter_scale;
uint8_t bs_noise_bands;
uint8_t bs_limiter_bands;
uint8_t bs_limiter_gains;
uint8_t bs_interpol_freq;
uint8_t bs_smoothing_mode;
uint8_t bs_samplerate_mode;
uint8_t bs_add_harmonic_flag[2];
uint8_t bs_add_harmonic_flag_prev[2];
uint8_t bs_extended_data;
uint8_t bs_extension_id;
uint8_t bs_extension_data;
uint8_t bs_coupling;
uint8_t bs_frame_class[2];
uint8_t bs_rel_bord[2][9];
uint8_t bs_rel_bord_0[2][9];
uint8_t bs_rel_bord_1[2][9];
uint8_t bs_pointer[2];
uint8_t bs_abs_bord_0[2];
uint8_t bs_abs_bord_1[2];
uint8_t bs_num_rel_0[2];
uint8_t bs_num_rel_1[2];
uint8_t bs_df_env[2][9];
uint8_t bs_df_noise[2][3];
} sbr_info;
typedef struct {
uint8_t adts_header_present;
uint8_t adif_header_present;
uint8_t latm_header_present;
uint8_t sf_index;
uint8_t object_type;
uint8_t channelConfiguration;
uint8_t aacSectionDataResilienceFlag;
uint8_t aacScalefactorDataResilienceFlag;
uint8_t aacSpectralDataResilienceFlag;
uint16_t frameLength;
uint8_t postSeekResetFlag;
uint32_t frame;
uint8_t downMatrix;
uint8_t upMatrix;
uint8_t first_syn_ele;
uint8_t has_lfe;
uint8_t fr_channels; /* number of channels in current frame */
uint8_t fr_ch_ele; /* number of elements in current frame */
uint8_t element_output_channels[MAX_SYNTAX_ELEMENTS]; /* element_output_channels: determines the number of channels the element will output */
uint8_t element_alloced[MAX_SYNTAX_ELEMENTS]; /* element_alloced:determines whether the data needed for the element is allocated or not*/
uint8_t alloced_channels; /* alloced_channels: determines the number of channels where output data is allocated for*/
void* sample_buffer; /* output data buffer */
uint8_t window_shape_prev[MAX_CHANNELS];
uint16_t ltp_lag[MAX_CHANNELS];
fb_info* fb;
drc_info* drc;
real_t* time_out[MAX_CHANNELS];
real_t* fb_intermed[MAX_CHANNELS];
int8_t sbr_present_flag;
int8_t forceUpSampling;
int8_t downSampledSBR;
uint8_t sbr_alloced[MAX_SYNTAX_ELEMENTS]; /* determines whether SBR data is allocated for the gives element */
sbr_info* sbr[MAX_SYNTAX_ELEMENTS];
uint8_t ps_used[MAX_SYNTAX_ELEMENTS];
uint8_t ps_used_global;
real_t* ssr_overlap[MAX_CHANNELS];
real_t* prev_fmd[MAX_CHANNELS];
real_t ipqf_buffer[MAX_CHANNELS][4][96 / 4];
pred_state* pred_stat[MAX_CHANNELS];
int16_t* lt_pred_stat[MAX_CHANNELS];
uint8_t error_state;
uint32_t __r1; /* RNG states */
uint32_t __r2;
uint8_t pce_set; /* Program Config Element */
program_config pce;
uint8_t element_id[MAX_CHANNELS];
uint8_t internal_channel[MAX_CHANNELS];
NeAACDecConfiguration config; /* Configuration data */
int64_t cycles;
int64_t spectral_cycles;
int64_t output_cycles;
int64_t scalefac_cycles;
int64_t requant_cycles;
latm_header latm_config;
const uint8_t* cmes;
uint8_t isPS;
} NeAACDecStruct;
/* 1st step table */
typedef struct {
uint8_t offset;
uint8_t extra_bits;
} hcb;
/* 2nd step table with quadruple data */
typedef struct {
uint8_t bits;
int8_t x;
int8_t y;
} hcb_2_pair;
typedef struct {
uint8_t bits;
int8_t x;
int8_t y;
int8_t v;
int8_t w;
} hcb_2_quad;
/* binary search table */
typedef struct {
uint8_t is_leaf;
int8_t data[4];
} hcb_bin_quad;
typedef struct {
uint8_t is_leaf;
int8_t data[2];
} hcb_bin_pair;
typedef struct _bitfile {
/* bit input */
uint32_t bufa;
uint32_t bufb;
uint32_t bits_left;
uint32_t buffer_size; /* size of the buffer in bytes */
uint32_t bytes_left;
uint8_t error;
uint32_t* tail;
uint32_t* start;
const void* buffer;
} bitfile;
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
typedef struct {
/* bit input */
uint32_t bufa;
uint32_t bufb;
int8_t len;
} bits_t;
typedef struct {
uint8_t cb;
uint8_t decoded;
uint16_t sp_offset;
bits_t bits;
} codeword_t;
typedef struct {
int8_t index;
uint8_t len;
uint32_t cw;
} rvlc_huff_table;
// ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/* type definitions */
typedef struct {
uint8_t frame_len;
uint8_t resolution20[3];
uint8_t resolution34[5];
qmf_t* work;
qmf_t** buffer;
qmf_t** temp;
} hyb_info;
typedef struct {
real_t G_lim_boost[MAX_L_E][MAX_M];
real_t Q_M_lim_boost[MAX_L_E][MAX_M];
real_t S_M_boost[MAX_L_E][MAX_M];
} sbr_hfadj_info;
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
typedef struct {
complex_t r01;
complex_t r02;
complex_t r11;
complex_t r12;
complex_t r22;
real_t det;
} acorr_coef;
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
typedef const int8_t (*ps_huff_tab)[2];

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,425 @@
/*
** FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR decoding
** Copyright (C) 2003-2005 M. Bakker, Nero AG, http://www.nero.com
**
** This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
**
** This program 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 General Public License for more details.
**
** You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
** Any non-GPL usage of this software or parts of this software is strictly forbidden.
**
** The "appropriate copyright message" mentioned in section 2c of the GPLv2 must read: "Code from FAAD2 is copyright (c) Nero AG, www.nero.com"
**
** Commercial non-GPL licensing of this software is possible.
** For more info contact Nero AG through Mpeg4AAClicense@nero.com.
**/
// ESP32 Version 29.07.2024
// updated: 18.06.2026
#pragma once
#include "aac_structs.h"
#include "aac_tables.h"
#include "aac_defines.h"
#include <math.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
class NeaacDecoder {
public:
NeaacDecoder() { m_initFlag = 0; }
~NeaacDecoder() = default;
NeAACDecHandle NeAACDecOpen(void);
NeAACDecConfigurationPtr NeAACDecGetCurrentConfiguration(NeAACDecHandle hpDecoder);
void NeAACDecClose(NeAACDecHandle hpDecoder);
uint8_t NeAACDecSetConfiguration(NeAACDecHandle hpDecoder, NeAACDecConfigurationPtr config);
char NeAACDecInit2(NeAACDecHandle hpDecoder, uint8_t* pBuffer, uint32_t SizeOfDecoderSpecificInfo, uint32_t* samplerate, uint8_t* channels);
long NeAACDecInit(NeAACDecHandle hpDecoder, uint8_t* buffer, uint32_t buffer_size, uint32_t* samplerate, uint8_t* channels);
void* NeAACDecDecode2(NeAACDecHandle hpDecoder, NeAACDecFrameInfo* hInfo, uint8_t* buffer, uint32_t buffer_size, void** sample_buffer, uint32_t sample_buffer_size);
error_info_t NeAACDecGetErrorMessage(const uint8_t errcode);
uint8_t get_sr_index(const uint32_t samplerate);
private:
uint32_t __r1 __attribute__((unused)) = 1;
uint32_t __r2 __attribute__((unused)) = 1;
ps_ptr<mdct_info> m_mdct256;
ps_ptr<mdct_info> m_mdct1024;
ps_ptr<mdct_info> m_mdct2048;
ps_ptr<cfft_info> m_ccft256;
ps_ptr<cfft_info> m_ccft1024;
ps_ptr<cfft_info> m_ccft2048;
ps_ptr<complex_t> m_work256;
ps_ptr<complex_t> m_work1024;
ps_ptr<complex_t> m_work2048;
ps_ptr<real_t> m_G_temp_prev[48][2][5];
ps_ptr<real_t> m_Q_temp_prev[48][2][5];
ps_ptr<adif_header> m_adif;
ps_ptr<adts_header> m_adts;
ps_ptr<bitfile> m_ld;
ps_ptr<uint8_t> m_sample_buffer;
uint32_t ne_rng(uint32_t* __r1, uint32_t* __r2);
uint32_t wl_min_lzc(uint32_t x);
uint8_t m_initFlag = 0;
#ifdef FIXED_POINT
int32_t log2_int(uint32_t val);
int32_t log2_fix(uint32_t val);
int32_t pow2_int(real_t val);
real_t pow2_fix(real_t val);
#endif
template <typename freeType> void faad_free(freeType** b);
void* faad_calloc(size_t len, size_t size);
uint32_t ones32(uint32_t x);
uint32_t floor_log2(uint32_t x);
int NeAACDecGetVersion(const char** faad_id_string, const char** faad_copyright_string);
uint32_t NeAACDecGetCapabilities(void);
void NeAACDecPostSeekReset(NeAACDecHandle hpDecoder, long frame);
void* NeAACDecDecode(NeAACDecHandle hpDecoder, NeAACDecFrameInfo* hInfo, uint8_t* buffer, uint32_t buffer_size);
void cfftf1pos(uint16_t n, complex_t* c, complex_t* ch, const uint16_t* ifac, const complex_t* wa, const int8_t isign);
void cfftf1neg(uint16_t n, complex_t* c, complex_t* ch, const uint16_t* ifac, const complex_t* wa, const int8_t isign);
#ifdef FIXED_POINT
real_t get_sample(real_t** input, uint8_t channel, uint16_t sample, uint8_t down_matrix, uint8_t up_matrix, uint8_t* internal_channel);
#endif
#ifndef FIXED_POINT
real_t get_sample(real_t** input, uint8_t channel, uint16_t sample, uint8_t down_matrix, uint8_t* internal_channel);
void to_PCM_16bit(NeAACDecStruct* hDecoder, real_t** input, uint8_t channels, uint16_t frame_len, int16_t** sample_buffer);
void to_PCM_24bit(NeAACDecStruct* hDecoder, real_t** input, uint8_t channels, uint16_t frame_len, int32_t** sample_buffer);
void to_PCM_32bit(NeAACDecStruct* hDecoder, real_t** input, uint8_t channels, uint16_t frame_len, int32_t** sample_buffer);
void to_PCM_float(NeAACDecStruct* hDecoder, real_t** input, uint8_t channels, uint16_t frame_len, float** sample_buffer);
void to_PCM_double(NeAACDecStruct* hDecoder, real_t** input, uint8_t channels, uint16_t frame_len, double** sample_buffer);
#endif
void imdct_ssr(fb_info* fb, real_t* in_data, real_t* out_data, uint16_t len);
void gc_setcoef_eff_pqfsyn(int mm, int kk, real_t* p_proto, real_t*** ppp_q0, real_t*** ppp_t0, real_t*** ppp_t1);
real_t calc_Q_div(sbr_info* sbr, uint8_t ch, uint8_t m, uint8_t l);
real_t calc_Q_div2(sbr_info* sbr, uint8_t ch, uint8_t m, uint8_t l);
#ifdef MAIN_DEC
void flt_round(float* pf);
int16_t quant_pred(float x);
float inv_quant_pred(int16_t q);
void ic_predict(pred_state* state, real_t input, real_t* output, uint8_t pred);
void reset_pred_state(pred_state* state);
#endif
void imdct_long(fb_info* fb, real_t* in_data, real_t* out_data, uint16_t len);
void mdct_init(fb_info* fb, real_t* in_data, real_t* out_data, uint16_t len);
uint32_t rewrev_word(uint32_t v, const uint8_t len);
void rewrev_lword(uint32_t* hi, uint32_t* lo, const uint8_t len);
void rewrev_bits(bits_t* bits);
void concat_bits(bits_t* b, bits_t* a);
uint8_t is_good_cb(uint8_t this_CB, uint8_t this_sec_CB);
void read_segment(bits_t* segment, uint8_t segwidth, bitfile* ld);
void fill_in_codeword(codeword_t* codeword, uint16_t index, uint16_t sp, uint8_t cb);
void fft_dif(real_t* Real, real_t* Imag);
real_t iquant(int16_t q, const real_t* tab, uint8_t* error);
uint8_t allocate_single_channel(NeAACDecStruct* hDecoder, uint8_t channel, uint8_t output_channels);
uint8_t allocate_channel_pair(NeAACDecStruct* hDecoder, uint8_t channel, uint8_t paired_channel);
uint8_t decode_scale_factors(ic_stream* ics, bitfile* ld);
uint32_t latm_get_value(bitfile* ld);
uint32_t latmParsePayload(latm_header* latm, bitfile* ld);
uint32_t latmAudioMuxElement(latm_header* latm, bitfile* ld);
char NeAACDecAudioSpecificConfig(uint8_t* pBuffer, uint32_t buffer_size, mp4AudioSpecificConfig* mp4ASC);
void hybrid_free(hyb_info* hyb);
void channel_filter4(hyb_info* hyb, uint8_t frame_len, const real_t* filter, qmf_t* buffer, qmf_t** X_hybrid);
void DCT3_6_unscaled(real_t* y, real_t* x);
void channel_filter12(hyb_info* hyb, uint8_t frame_len, const real_t* filter, qmf_t* buffer, qmf_t** X_hybrid);
real_t magnitude_c(complex_t c);
uint8_t sbr_process_channel(sbr_info* sbr, real_t* channel_buf, qmf_t X[MAX_NTSR][64], uint8_t ch, uint8_t dont_process, const uint8_t downSampledSBR);
real_t find_initial_power(uint8_t bands, uint8_t a0, uint8_t a1);
void sbr_reset(sbr_info* sbr);
int8_t sbr_log2(const int8_t val);
real_t find_log2_E(sbr_info* sbr, uint8_t k, uint8_t l, uint8_t ch);
real_t find_log2_Q(sbr_info* sbr, uint8_t k, uint8_t l, uint8_t ch);
real_t find_log2_Qplus1(sbr_info* sbr, uint8_t k, uint8_t l, uint8_t ch);
void auto_correlation(sbr_info* sbr, acorr_coef* ac, qmf_t buffer[MAX_NTSRHFG][64], uint8_t bd, uint8_t len);
real_t mapNewBw(uint8_t invf_mode, uint8_t invf_mode_prev);
uint8_t max_pred_sfb(const uint8_t sr_index);
uint8_t max_tns_sfb(const uint8_t sr_index, const uint8_t object_type, const uint8_t is_short);
uint32_t get_sample_rate(const uint8_t sr_index);
int8_t can_decode_ot(const uint8_t object_type);
void* faad_malloc(size_t size);
drc_info* drc_init(real_t cut, real_t boost);
void drc_end(drc_info* drc);
void drc_decode(drc_info* drc, real_t* spec);
sbr_info* sbrDecodeInit(uint16_t framelength, uint8_t id_aac, uint32_t sample_rate, uint8_t downSampledSBR, uint8_t IsDRM);
void sbrDecodeEnd(sbr_info* sbr, uint8_t i);
void sbrReset(sbr_info* sbr, uint8_t i);
uint8_t sbrDecodeCoupleFrame(sbr_info* sbr, real_t* left_chan, real_t* right_chan, const uint8_t just_seeked, const uint8_t downSampledSBR);
uint8_t sbrDecodeSingleFrame(sbr_info* sbr, real_t* channel, const uint8_t just_seeked, const uint8_t downSampledSBR);
uint16_t ps_data(ps_info* ps, bitfile* ld, uint8_t* header);
ps_info* ps_init(uint8_t sr_index, uint8_t numTimeSlotsRate);
void ps_free(ps_info* ps);
uint8_t ps_decode(ps_info* ps, qmf_t X_left[38][64], qmf_t X_right[38][64]);
void faad_initbits(bitfile* ld, const void* buffer, const uint32_t buffer_size);
void faad_endbits(bitfile* ld);
void faad_initbits_rev(bitfile* ld, void* buffer, uint32_t bits_in_buffer);
uint8_t faad_byte_align(bitfile* ld);
uint32_t faad_get_processed_bits(bitfile* ld);
void faad_flushbits_ex(bitfile* ld, uint32_t bits);
void faad_rewindbits(bitfile* ld);
void faad_resetbits(bitfile* ld, int bits);
uint8_t* faad_getbitbuffer(bitfile* ld, uint32_t bits);
void* faad_origbitbuffer(bitfile* ld);
uint32_t faad_origbitbuffer_size(bitfile* ld);
uint8_t faad_get1bit(bitfile* ld);
uint32_t faad_getbits(bitfile* ld, uint32_t n);
uint32_t faad_showbits_rev(bitfile* ld, uint32_t bits);
void faad_flushbits_rev(bitfile* ld, uint32_t bits);
uint32_t getdword(void* mem);
uint32_t getdword_n(void* mem, int n);
void faad_flushbits(bitfile* ld, uint32_t bits);
uint32_t faad_showbits(bitfile* ld, uint32_t bits);
uint32_t showbits_hcr(bits_t* ld, uint8_t bits);
uint32_t faad_getbits_rev(bitfile* ld, uint32_t n);
int8_t get1bit_hcr(bits_t* ld, uint8_t* result);
int8_t flushbits_hcr(bits_t* ld, uint8_t bits);
int8_t getbits_hcr(bits_t* ld, uint8_t n, uint32_t* result);
void cfftf(uint16_t mdct_len, complex_t* c);
void cfftb(uint16_t mdct_len, complex_t* c);
void cffti(uint16_t mdct_len, uint16_t n);
void* aac_frame_decode(NeAACDecStruct* hDecoder, NeAACDecFrameInfo* hInfo, uint8_t* buffer, uint32_t buffer_size, void** sample_buffer2, uint32_t sample_buffer_size);
void create_channel_config(NeAACDecStruct* hDecoder, NeAACDecFrameInfo* hInfo);
void passf2pos(const uint16_t ido, const uint16_t l1, const complex_t* cc, complex_t* ch, const complex_t* wa);
void passf2neg(const uint16_t ido, const uint16_t l1, const complex_t* cc, complex_t* ch, const complex_t* wa);
void passf3(const uint16_t ido, const uint16_t l1, const complex_t* cc, complex_t* ch, const complex_t* wa1, const complex_t* wa2, const int8_t isign);
void passf4pos(const uint16_t ido, const uint16_t l1, const complex_t* cc, complex_t* ch, const complex_t* wa1, const complex_t* wa2, const complex_t* wa3);
void passf4neg(const uint16_t ido, const uint16_t l1, const complex_t* cc, complex_t* ch, const complex_t* wa1, const complex_t* wa2, const complex_t* wa3);
void passf5(const uint16_t ido, const uint16_t l1, const complex_t* cc, complex_t* ch, const complex_t* wa1, const complex_t* wa2, const complex_t* wa3, const complex_t* wa4, const int8_t isign);
void cffti1(uint16_t n, complex_t* wa, uint16_t* ifac);
fb_info* filter_bank_init(uint16_t frame_len);
void filter_bank_end(fb_info* fb);
void filter_bank_ltp(fb_info* fb, uint8_t window_sequence, uint8_t window_shape, uint8_t window_shape_prev, real_t* in_data, real_t* out_mdct, uint8_t object_type, uint16_t frame_len);
void ifilter_bank(fb_info* fb, uint8_t window_sequence, uint8_t window_shape, uint8_t window_shape_prev, real_t* freq_in, real_t* time_out, real_t* overlap, uint8_t object_type,
uint16_t frame_len);
void ms_decode(ic_stream* ics, ic_stream* icsr, real_t* l_spec, real_t* r_spec, uint16_t frame_len);
void is_decode(ic_stream* ics, ic_stream* icsr, real_t* l_spec, real_t* r_spec, uint16_t frame_len);
int8_t is_intensity(ic_stream* ics, uint8_t group, uint8_t sfb);
uint8_t is_noise(ic_stream* ics, uint8_t group, uint8_t sfb);
real_t fp_sqrt(real_t value);
void pns_decode(ic_stream* ics_left, ic_stream* ics_right, real_t* spec_left, real_t* spec_right, uint16_t frame_len, uint8_t channel_pair, uint8_t object_type,
/* RNG states */ uint32_t* __r1, uint32_t* __r2);
int8_t invert_intensity(ic_stream* ics, uint8_t group, uint8_t sfb);
void* output_to_PCM(NeAACDecStruct* hDecoder, real_t** input, void* samplebuffer, uint8_t channels, uint16_t frame_len, uint8_t format);
uint8_t pulse_decode(ic_stream* ics, int16_t* spec_coef, uint16_t framelen);
void gen_rand_vector(real_t* spec, int16_t scale_factor, uint16_t size, uint8_t sub, uint32_t* __r1, uint32_t* __r2);
void huffman_sign_bits(bitfile* ld, int16_t* sp, uint8_t len);
uint8_t huffman_getescape(bitfile* ld, int16_t* sp);
uint8_t huffman_2step_quad(uint8_t cb, bitfile* ld, int16_t* sp);
uint8_t huffman_2step_quad_sign(uint8_t cb, bitfile* ld, int16_t* sp);
uint8_t huffman_2step_pair(uint8_t cb, bitfile* ld, int16_t* sp);
uint8_t huffman_2step_pair_sign(uint8_t cb, bitfile* ld, int16_t* sp);
uint8_t huffman_binary_quad(uint8_t cb, bitfile* ld, int16_t* sp);
uint8_t huffman_binary_quad_sign(uint8_t cb, bitfile* ld, int16_t* sp);
uint8_t huffman_binary_pair(uint8_t cb, bitfile* ld, int16_t* sp);
uint8_t huffman_binary_pair_sign(uint8_t cb, bitfile* ld, int16_t* sp);
int16_t huffman_codebook(uint8_t i);
void vcb11_check_LAV(uint8_t cb, int16_t* sp);
uint16_t drm_ps_data(drm_ps_info* ps, bitfile* ld);
drm_ps_info* drm_ps_init(void);
void drm_ps_free(drm_ps_info* ps);
uint8_t drm_ps_decode(drm_ps_info* ps, uint8_t guess, qmf_t X_left[38][64], qmf_t X_right[38][64]);
int8_t huffman_scale_factor(bitfile* ld);
uint8_t huffman_spectral_data(uint8_t cb, bitfile* ld, int16_t* sp);
int8_t huffman_spectral_data_2(uint8_t cb, bits_t* ld, int16_t* sp);
int8_t AudioSpecificConfig2(uint8_t* pBuffer, uint32_t buffer_size, mp4AudioSpecificConfig* mp4ASC, program_config* pce, uint8_t short_form);
int8_t AudioSpecificConfigFromBitfile(bitfile* ld, mp4AudioSpecificConfig* mp4ASC, program_config* pce, uint32_t bsize, uint8_t short_form);
void pns_reset_pred_state(ic_stream* ics, pred_state* state);
void reset_all_predictors(pred_state* state, uint16_t frame_len);
void ic_prediction(ic_stream* ics, real_t* spec, pred_state* state, uint16_t frame_len, uint8_t sf_index);
uint8_t quant_to_spec(NeAACDecStruct* hDecoder, ic_stream* ics, int16_t* quant_data, real_t* spec_data, uint16_t frame_len);
uint8_t window_grouping_info(NeAACDecStruct* hDecoder, ic_stream* ics);
uint8_t reconstruct_channel_pair(NeAACDecStruct* hDecoder, ic_stream* ics1, ic_stream* ics2, element* cpe, int16_t* spec_data1, int16_t* spec_data2);
uint8_t reconstruct_single_channel(NeAACDecStruct* hDecoder, ic_stream* ics, element* sce, int16_t* spec_data);
void tns_decode_frame(ic_stream* ics, tns_info* tns, uint8_t sr_index, uint8_t object_type, real_t* spec, uint16_t frame_len);
void tns_encode_frame(ic_stream* ics, tns_info* tns, uint8_t sr_index, uint8_t object_type, real_t* spec, uint16_t frame_len);
uint8_t is_ltp_ot(uint8_t object_type);
void lt_prediction(ic_stream* ics, ltp_info* ltp, real_t* spec, int16_t* lt_pred_stat, fb_info* fb, uint8_t win_shape, uint8_t win_shape_prev, uint8_t sr_index, uint8_t object_type,
uint16_t frame_len);
void lt_update_state(int16_t* lt_pred_stat, real_t* time, real_t* overlap, uint16_t frame_len, uint8_t object_type);
void tns_decode_coef(uint8_t order, uint8_t coef_res_bits, uint8_t coef_compress, uint8_t* coef, real_t* a);
void tns_ar_filter(real_t* spectrum, uint16_t size, int8_t inc, real_t* lpc, uint8_t order);
void tns_ma_filter(real_t* spectrum, uint16_t size, int8_t inc, real_t* lpc, uint8_t order);
uint8_t faad_check_CRC(bitfile* ld, uint16_t len);
/* static function declarations */
void decode_sce_lfe(NeAACDecStruct* hDecoder, NeAACDecFrameInfo* hInfo, bitfile* ld, uint8_t id_syn_ele);
void decode_cpe(NeAACDecStruct* hDecoder, NeAACDecFrameInfo* hInfo, bitfile* ld, uint8_t id_syn_ele);
uint8_t single_lfe_channel_element(NeAACDecStruct* hDecoder, bitfile* ld, uint8_t channel, uint8_t* tag);
uint8_t channel_pair_element(NeAACDecStruct* hDecoder, bitfile* ld, uint8_t channel, uint8_t* tag);
#ifdef COUPLING_DEC
uint8_t coupling_channel_element(NeAACDecStruct* hDecoder, bitfile* ld);
#endif
uint16_t data_stream_element(NeAACDecStruct* hDecoder, bitfile* ld);
uint8_t program_config_element(program_config* pce, bitfile* ld);
uint8_t fill_element(NeAACDecStruct* hDecoder, bitfile* ld, drc_info* drc, uint8_t sbr_ele);
uint8_t individual_channel_stream(NeAACDecStruct* hDecoder, element* ele, bitfile* ld, ic_stream* ics, uint8_t scal_flag, int16_t* spec_data);
uint8_t ics_info(NeAACDecStruct* hDecoder, ic_stream* ics, bitfile* ld, uint8_t common_window);
uint8_t section_data(NeAACDecStruct* hDecoder, ic_stream* ics, bitfile* ld);
uint8_t scale_factor_data(NeAACDecStruct* hDecoder, ic_stream* ics, bitfile* ld);
#ifdef SSR_DEC
void gain_control_data(bitfile* ld, ic_stream* ics);
#endif
uint8_t spectral_data(NeAACDecStruct* hDecoder, ic_stream* ics, bitfile* ld, int16_t* spectral_data);
uint16_t extension_payload(bitfile* ld, drc_info* drc, uint16_t count);
uint8_t pulse_data(ic_stream* ics, pulse_info* pul, bitfile* ld);
void tns_data(ic_stream* ics, tns_info* tns, bitfile* ld);
#ifdef LTP_DEC
uint8_t ltp_data(NeAACDecStruct* hDecoder, ic_stream* ics, ltp_info* ltp, bitfile* ld);
#endif
uint8_t adts_fixed_header(adts_header* adts, bitfile* ld);
void adts_variable_header(adts_header* adts, bitfile* ld);
void adts_error_check(adts_header* adts, bitfile* ld);
uint8_t dynamic_range_info(bitfile* ld, drc_info* drc);
uint8_t excluded_channels(bitfile* ld, drc_info* drc);
uint8_t side_info(NeAACDecStruct* hDecoder, element* ele, bitfile* ld, ic_stream* ics, uint8_t scal_flag);
int8_t GASpecificConfig(bitfile* ld, mp4AudioSpecificConfig* mp4ASC, program_config* pce);
uint8_t adts_frame(adts_header* adts, bitfile* ld);
void get_adif_header(adif_header* adif, bitfile* ld);
void raw_data_block(NeAACDecStruct* hDecoder, NeAACDecFrameInfo* hInfo, bitfile* ld, program_config* pce, drc_info* drc);
uint8_t reordered_spectral_data(NeAACDecStruct* hDecoder, ic_stream* ics, bitfile* ld, int16_t* spectral_data);
#ifdef DRM
int8_t DRM_aac_scalable_main_header(NeAACDecStruct* hDecoder, ic_stream* ics1, ic_stream* ics2, bitfile* ld, uint8_t this_layer_stereo);
#endif
void dct4_kernel(real_t* in_real, real_t* in_imag, real_t* out_real, real_t* out_imag);
void DCT3_32_unscaled(real_t* y, real_t* x);
void DCT4_32(real_t* y, real_t* x);
void DST4_32(real_t* y, real_t* x);
void DCT2_32_unscaled(real_t* y, real_t* x);
void DCT4_16(real_t* y, real_t* x);
void DCT2_16_unscaled(real_t* y, real_t* x);
uint8_t rvlc_scale_factor_data(ic_stream* ics, bitfile* ld);
uint8_t rvlc_decode_scale_factors(ic_stream* ics, bitfile* ld);
uint8_t sbr_extension_data(bitfile* ld, sbr_info* sbr, uint16_t cnt, uint8_t resetFlag);
int8_t rvlc_huffman_sf(bitfile* ld_sf, bitfile* ld_esc, int8_t direction);
int8_t rvlc_huffman_esc(bitfile* ld_esc, int8_t direction);
uint8_t rvlc_decode_sf_forward(ic_stream* ics, bitfile* ld_sf, bitfile* ld_esc, uint8_t* intensity_used);
#ifdef DRM
void DRM_aac_scalable_main_element(NeAACDecStruct* hDecoder, NeAACDecFrameInfo* hInfo, bitfile* ld, program_config* pce, drc_info* drc);
#endif
uint32_t faad_latm_frame(latm_header* latm, bitfile* ld);
#ifdef SSR_DEC
void ssr_decode(ssr_info* ssr, fb_info* fb, uint8_t window_sequence, uint8_t window_shape, uint8_t window_shape_prev, real_t* freq_in, real_t* time_out, real_t* overlap,
real_t ipqf_buffer[SSR_BANDS][96 / 4], real_t* prev_fmd, uint16_t frame_len);
void ssr_gain_control(ssr_info* ssr, real_t* data, real_t* output, real_t* overlap, real_t* prev_fmd, uint8_t band, uint8_t window_sequence, uint16_t frame_len);
void ssr_gc_function(ssr_info* ssr, real_t* prev_fmd, real_t* gc_function, uint8_t window_sequence, uint16_t frame_len);
#endif
void extract_envelope_data(sbr_info* sbr, uint8_t ch);
void extract_noise_floor_data(sbr_info* sbr, uint8_t ch);
#ifndef FIXED_POINT
void envelope_noise_dequantisation(sbr_info* sbr, uint8_t ch);
void unmap_envelope_noise(sbr_info* sbr);
#endif
void ssr_ipqf(ssr_info* ssr, real_t* in_data, real_t* out_data, real_t buffer[SSR_BANDS][96 / 4], uint16_t frame_len, uint8_t bands);
void faad_mdct_init(uint16_t mdct_len, uint16_t N);
void faad_mdct_end(uint16_t mdct_len);
void faad_imdct(uint16_t mdct_idx, real_t* X_in, real_t* X_out);
void faad_mdct(uint16_t mdct_len, real_t* X_in, real_t* X_out);
#if (defined(PS_DEC) || defined(DRM_PS))
uint8_t sbrDecodeSingleFramePS(sbr_info* sbr, real_t* left_channel, real_t* right_channel, const uint8_t just_seeked, const uint8_t downSampledSBR);
#endif
// void unmap_envelope_noise(sbr_info* sbr);
int16_t real_to_int16(real_t sig_in);
uint8_t sbr_save_prev_data(sbr_info* sbr, uint8_t ch);
void sbr_save_matrix(sbr_info* sbr, uint8_t ch);
fb_info* ssr_filter_bank_init(uint16_t frame_len);
void ssr_filter_bank_end(fb_info* fb);
void ssr_ifilter_bank(fb_info* fb, uint8_t window_sequence, uint8_t window_shape, uint8_t window_shape_prev, real_t* freq_in, real_t* time_out, uint16_t frame_len);
int32_t find_bands(uint8_t warp, uint8_t bands, uint8_t a0, uint8_t a1);
void sbr_header(bitfile* ld, sbr_info* sbr);
uint8_t calc_sbr_tables(sbr_info* sbr, uint8_t start_freq, uint8_t stop_freq, uint8_t samplerate_mode, uint8_t freq_scale, uint8_t alter_scale, uint8_t xover_band);
uint8_t sbr_data(bitfile* ld, sbr_info* sbr);
uint16_t sbr_extension(bitfile* ld, sbr_info* sbr, uint8_t bs_extension_id, uint16_t num_bits_left);
uint8_t sbr_single_channel_element(bitfile* ld, sbr_info* sbr);
uint8_t sbr_channel_pair_element(bitfile* ld, sbr_info* sbr);
uint8_t sbr_grid(bitfile* ld, sbr_info* sbr, uint8_t ch);
void sbr_dtdf(bitfile* ld, sbr_info* sbr, uint8_t ch);
void invf_mode(bitfile* ld, sbr_info* sbr, uint8_t ch);
void sinusoidal_coding(bitfile* ld, sbr_info* sbr, uint8_t ch);
uint8_t hf_adjustment(sbr_info* sbr, qmf_t Xsbr[MAX_NTSRHFG][64], real_t* deg, uint8_t ch);
uint8_t qmf_start_channel(uint8_t bs_start_freq, uint8_t bs_samplerate_mode, uint32_t sample_rate);
uint8_t qmf_stop_channel(uint8_t bs_stop_freq, uint32_t sample_rate, uint8_t k0);
uint8_t master_frequency_table_fs0(sbr_info* sbr, uint8_t k0, uint8_t k2, uint8_t bs_alter_scale);
uint8_t master_frequency_table(sbr_info* sbr, uint8_t k0, uint8_t k2, uint8_t bs_freq_scale, uint8_t bs_alter_scale);
uint8_t derived_frequency_table(sbr_info* sbr, uint8_t bs_xover_band, uint8_t k2);
void limiter_frequency_table(sbr_info* sbr);
#ifdef SBR_DEC
#ifdef SBR_LOW_POWER
void calc_prediction_coef_lp(sbr_info* sbr, qmf_t Xlow[MAX_NTSRHFG][64], complex_t* alpha_0, complex_t* alpha_1, real_t* rxx);
void calc_aliasing_degree(sbr_info* sbr, real_t* rxx, real_t* deg);
#else // SBR_LOW_POWER
void calc_prediction_coef(sbr_info* sbr, qmf_t Xlow[MAX_NTSRHFG][64], complex_t* alpha_0, complex_t* alpha_1, uint8_t k);
#endif // SBR_LOW_POWER
void calc_chirp_factors(sbr_info* sbr, uint8_t ch);
void patch_construction(sbr_info* sbr);
#endif // SBR_DEC
#ifdef SBR_DEC
uint8_t estimate_current_envelope(sbr_info* sbr, sbr_hfadj_info* adj, qmf_t Xsbr[MAX_NTSRHFG][64], uint8_t ch);
void calculate_gain(sbr_info* sbr, sbr_hfadj_info* adj, uint8_t ch);
#ifdef SBR_LOW_POWER
void calc_gain_groups(sbr_info* sbr, sbr_hfadj_info* adj, real_t* deg, uint8_t ch);
void aliasing_reduction(sbr_info* sbr, sbr_hfadj_info* adj, real_t* deg, uint8_t ch);
#endif // SBR_LOW_POWER
void hf_assembly(sbr_info* sbr, sbr_hfadj_info* adj, qmf_t Xsbr[MAX_NTSRHFG][64], uint8_t ch);
#endif // SBR_DEC
uint8_t get_S_mapped(sbr_info* sbr, uint8_t ch, uint8_t l, uint8_t current_band);
qmfa_info* qmfa_init(uint8_t channels);
void qmfa_end(qmfa_info* qmfa);
qmfs_info* qmfs_init(uint8_t channels);
void qmfs_end(qmfs_info* qmfs);
void sbr_qmf_analysis_32(sbr_info* sbr, qmfa_info* qmfa, const real_t* input, qmf_t X[MAX_NTSRHFG][64], uint8_t offset, uint8_t kx);
void sbr_qmf_synthesis_32(sbr_info* sbr, qmfs_info* qmfs, qmf_t X[MAX_NTSRHFG][64], real_t* output);
void sbr_qmf_synthesis_64(sbr_info* sbr, qmfs_info* qmfs, qmf_t X[MAX_NTSRHFG][64], real_t* output);
uint8_t envelope_time_border_vector(sbr_info* sbr, uint8_t ch);
void noise_floor_time_border_vector(sbr_info* sbr, uint8_t ch);
void hf_generation(sbr_info* sbr, qmf_t Xlow[MAX_NTSRHFG][64], qmf_t Xhigh[MAX_NTSRHFG][64], real_t* deg, uint8_t ch);
void sbr_envelope(bitfile* ld, sbr_info* sbr, uint8_t ch);
void sbr_noise(bitfile* ld, sbr_info* sbr, uint8_t ch);
uint8_t middleBorder(sbr_info* sbr, uint8_t ch);
#ifdef SSR_DEC
// void ssr_ipqf(ssr_info* ssr, real_t* in_data, real_t* out_data, real_t buffer[SSR_BANDS][96 / 4], uint16_t frame_len, uint8_t bands);
void gc_set_protopqf(real_t* p_proto);
#endif
#ifdef PS_DEC
hyb_info* hybrid_init(uint8_t numTimeSlotsRate);
void channel_filter2(hyb_info* hyb, uint8_t frame_len, const real_t* filter, qmf_t* buffer, qmf_t** X_hybrid);
void inline DCT3_4_unscaled(real_t* y, real_t* x);
void channel_filter8(hyb_info* hyb, uint8_t frame_len, const real_t* filter, qmf_t* buffer, qmf_t** X_hybrid);
void hybrid_analysis(hyb_info* hyb, qmf_t X[32][64], qmf_t X_hybrid[32][32], uint8_t use34, uint8_t numTimeSlotsRate);
void hybrid_synthesis(hyb_info* hyb, qmf_t X[32][64], qmf_t X_hybrid[32][32], uint8_t use34, uint8_t numTimeSlotsRate);
int8_t delta_clip(int8_t i, int8_t min, int8_t max);
void delta_decode(uint8_t enable, int8_t* index, int8_t* index_prev, uint8_t dt_flag, uint8_t nr_par, uint8_t stride, int8_t min_index, int8_t max_index);
void delta_modulo_decode(uint8_t enable, int8_t* index, int8_t* index_prev, uint8_t dt_flag, uint8_t nr_par, uint8_t stride, int8_t and_modulo);
void map20indexto34(int8_t* index, uint8_t bins);
#ifdef PS_LOW_POWER
void map34indexto20(int8_t* index, uint8_t bins);
#endif
void ps_data_decode(ps_info* ps);
void ps_decorrelate(ps_info* ps, qmf_t X_left[38][64], qmf_t X_right[38][64], qmf_t X_hybrid_left[32][32], qmf_t X_hybrid_right[32][32]);
void ps_mix_phase(ps_info* ps, qmf_t X_left[38][64], qmf_t X_right[38][64], qmf_t X_hybrid_left[32][32], qmf_t X_hybrid_right[32][32]);
#endif // PS_DEC
#ifdef PS_DEC
uint16_t ps_extension(ps_info* ps, bitfile* ld, const uint8_t ps_extension_id, const uint16_t num_bits_left);
void huff_data(bitfile* ld, const uint8_t dt, const uint8_t nr_par, ps_huff_tab t_huff, ps_huff_tab f_huff, int8_t* par);
int8_t ps_huff_dec(bitfile* ld, ps_huff_tab t_huff);
#endif // PS_DEC
typedef const int8_t (*sbr_huff_tab)[2];
int16_t sbr_huff_dec(bitfile* ld, sbr_huff_tab t_huff);
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// Macro for comfortable calls
// #define AAC_LOG_ERROR(fmt, ...) Audio::AUDIO_LOG_IMPL(1, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
// #define AAC_LOG_WARN(fmt, ...) Audio::AUDIO_LOG_IMPL(2, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
// #define AAC_LOG_INFO(fmt, ...) Audio::AUDIO_LOG_IMPL(3, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
// #define AAC_LOG_DEBUG(fmt, ...) Audio::AUDIO_LOG_IMPL(4, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
// #define AAC_LOG_VERBOSE(fmt, ...) Audio::AUDIO_LOG_IMPL(5, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
};

View File

@@ -0,0 +1,446 @@
#pragma once
#include "psram_unique_ptr.hpp"
#include <cstdint>
#include <deque>
#include <stddef.h>
// this file contains definitions of various structs used in Audio lib
namespace audiolib {
struct sylt_t {
size_t size;
uint32_t pos;
char lang[5];
uint8_t text_encoding;
uint8_t time_stamp_format;
uint8_t content_type;
};
struct ID3Hdr_t { // used only in readID3header()
size_t retvalue = {};
size_t headerSize = {};
size_t tagSize = {};
size_t cnt = {};
size_t id3Size = {};
size_t totalId3Size = {}; // if we have more header, id3_1_size + id3_2_size + ....
size_t remainingHeaderBytes = {};
size_t v22_tag_length = {};
uint8_t ID3version = {};
uint8_t ID3revision = {};
uint8_t flags = {};
bool unsync = {};
bool extended_header = {};
bool experimental_indicator = {};
bool footer_present = {};
size_t offset = {};
size_t currentPosition = {};
int ehsz = {};
char tag[5] = {};
char frameid[5] = {};
char lang[5] = {};
size_t framesize = {};
bool compressed = {};
std::vector<uint32_t> APIC_vec = {};
sylt_t SYLT = {};
uint8_t numID3Header = {};
uint16_t iBuffSize = {};
uint8_t contentDescriptorTerminator_0 = {};
uint8_t contentDescriptorTerminator_1 = {};
uint8_t textStringTerminator_0 = {};
uint8_t textStringTerminator_1 = {};
bool byteOrderMark = {};
ps_ptr<char> iBuff;
void reset() { *this = ID3Hdr_t{}; }
};
struct pwsHLS_t { // used in processWebStreamHLS()
uint16_t maxFrameSize;
uint16_t ID3BuffSize;
uint32_t availableBytes;
bool firstBytes;
bool f_chunkFinished;
uint32_t byteCounter;
int32_t chunkSize;
uint16_t ID3WritePtr;
uint16_t ID3ReadPtr;
ps_ptr<uint8_t> ID3Buff;
};
struct pplM3u8_t { // used in parsePlaylist_M3U8
uint64_t xMedSeq;
bool f_mediaSeq_found;
bool firstCall;
};
struct m4aHdr_t { // used in read_M4A_Header
size_t headerSize;
size_t retvalue;
size_t atomsize;
size_t sizeof_ftyp;
size_t sizeof_moov;
size_t sizeof_free;
size_t sizeof_mdat;
size_t sizeof_trak;
size_t sizeof_ilst;
size_t sizeof_esds;
size_t sizeof_mdia;
size_t sizeof_minf;
size_t sizeof_mdhd;
size_t sizeof_stbl;
size_t sizeof_stsd;
size_t sizeof_stsz;
size_t sizeof_mp4a;
size_t sizeof_udta;
size_t sizeof_meta;
size_t sizeof_chpl;
size_t audioDataPos;
size_t cnt;
size_t offset;
uint32_t mdat_startPos;
uint32_t picPos;
uint32_t picLen;
uint32_t ilst_pos;
uint8_t channel_count;
uint8_t sample_size; // bps
uint8_t objectTypeIndicator; // esds
uint8_t streamType; // esds
uint32_t bufferSizeDB; // esds
uint32_t maxBitrate; // esds
uint32_t nomBitrate; // esds
uint32_t timescale; // mdhd
uint32_t duration; // mdhd
uint16_t sample_rate;
uint8_t aac_profile;
uint32_t stsz_num_entries;
uint32_t stsz_table_pos;
uint32_t ilst_already_consumed;
bool progressive; // Progressive (moov before mdat)
bool version_flags;
bool mdat_seen;
};
struct plCh_t { // used in playChunk
uint32_t count = 0;
size_t i2s_bytesConsumed;
uint16_t samples;
int16_t* sample[2];
esp_err_t err;
};
struct lVar_t { // used in loop
uint8_t no_host_cnt;
uint32_t no_host_timer;
uint8_t count;
};
struct hwoe_t { // used in dismantle_host
bool ssl;
ps_ptr<char> hwoe; // host without extension
ps_ptr<char> rqh_host; // host in request header
uint16_t port;
ps_ptr<char> extension;
ps_ptr<char> query_string;
};
struct prlf_t { // used in processLocalFile
uint32_t ctime;
int32_t newFilePos;
bool audioHeaderFound;
uint32_t timeout;
uint32_t maxFrameSize;
uint32_t availableBytes;
int32_t bytesAddedToBuffer;
};
typedef struct _cat { // used in calculateAudioTime
uint64_t sumBytesIn{};
uint64_t sum_samples{};
uint32_t counter{};
uint32_t timeStamp{};
uint32_t deltaBytesIn{};
uint32_t nominalBitRate{};
uint32_t tota_samples{};
uint32_t avrBitRate{};
uint16_t syltIdx{};
uint32_t avrBitrateStable{};
uint32_t oldAvrBitrate{};
uint32_t brCounter{};
bool firstCall{};
void reset() { *this = _cat{}; }
} cat_t;
struct ifCh_t { // used in IIR_filterChain0, 1, 2
// s16
float inSample0_16[2];
float outSample0_16[2];
int16_t iir_out0_16[2];
float inSample1_16[2];
float outSample1_16[2];
int16_t iir_out1_16[2];
float inSample2_16[2];
float outSample2_16[2];
int16_t iir_out2_16[2];
// s32
float inSample0_32[2];
float outSample0_32[2];
int32_t iir_out0_32[2];
float inSample1_32[2];
float outSample1_32[2];
int32_t iir_out1_32[2];
float inSample2_32[2];
float outSample2_32[2];
int32_t iir_out2_32[2];
};
typedef struct _tspp { // used in ts_parsePacket
int pidNumber{};
int pids[4]{}; // PID_ARRAY_LEN
int PES_DataLength{};
int pidOfAAC{};
uint8_t fillData{};
void reset() {
*this = _tspp{}; // Default-initialize all new (inclusive Array)
}
} tspp_t;
struct pwst_t { // used in processWebStream
uint16_t maxFrameSize;
uint32_t chunkSize = 0;
bool f_skipCRLF = false;
uint32_t availableBytes;
bool f_clientIsConnected;
uint32_t writeSpace = 0;
uint16_t readedBytes;
};
struct gchs_t { // used in getChunkSize
int32_t chunkSize = -1;
uint32_t timeStamp = {};
ps_ptr<char> chunkLine = {};
ps_ptr<char> extension = {};
ps_ptr<char> trailer = {};
uint16_t position = 0;
void reset() { *this = gchs_t{}; }
};
struct pwf_t { // used in processWebFile
uint32_t maxFrameSize;
int32_t newFilePos;
bool audioHeaderFound;
uint32_t chunkSize;
size_t audioDataCount;
uint32_t byteCounter;
uint32_t nextChunkCount;
bool f_waitingForPayload = false;
bool f_clientIsConnected;
uint32_t ctime;
uint32_t timeout;
uint32_t availableBytes;
int32_t bytesAddedToBuffer;
};
struct pad_t { // used in playAudioData
uint8_t count = 0;
size_t oldAudioDataSize = 0;
bool lastFrames = false;
int32_t bytesToDecode;
int32_t bytesDecoded;
};
struct sbyt_t { // used in sendBytes
int32_t bytesLeft;
bool f_setDecodeParamsOnce = true;
uint8_t channels = 0;
int nextSync = 0;
uint8_t isPS = 0;
const char* opus_mode = nullptr;
};
struct rmet_t { // used in readMetadata
uint32_t pos_ml = 0; // determines the current position in metaline
uint32_t metaDataSize = 0;
uint16_t res = 0;
};
struct pwsts_t { // used in processWebStreamTS
uint32_t availableBytes; // available bytes in stream
bool f_firstPacket;
bool f_chunkFinished;
bool f_nextRound;
uint32_t byteCounter; // count received data
uint8_t ts_packetStart = 0;
uint8_t ts_packetLength = 0;
uint8_t ts_packetPtr = 0;
const uint8_t ts_packetsize = 188;
ps_ptr<uint8_t> ts_packet;
size_t chunkSize = 0;
};
struct rwh_t { // used in read_WAV_Header
size_t headerSize;
uint32_t cs = 0;
uint8_t bts = 0;
};
typedef struct _rflh { // used in read_FLAC_Header
std::vector<uint32_t> picVec{};
size_t headerSize{};
size_t retvalue{};
bool f_lastMetaBlock{};
uint32_t picPos{};
uint32_t picLen{};
uint32_t duration{};
uint32_t nominalBitrate{};
uint8_t numChannels{};
uint8_t bitsPerSample{};
uint32_t sampleRate{};
uint32_t maxFrameSize{};
uint32_t maxBlockSize{};
uint32_t totalSamplesInStream{};
void reset() {
// Default-initialize alles neu (inklusive Array)
*this = _rflh{};
}
} rflh_t;
typedef struct _phreh { // used in parseHttpResponseHeader
uint32_t ctime{};
uint32_t timeout{};
uint32_t stime{};
uint32_t bitrate{};
bool f_time{};
bool f_icy_data{};
void reset() {
// Default-initialize alles neu (inklusive Array)
*this = _phreh{};
}
} phreh_t;
struct phrah_t { // used in parseHttpRangeHeader
uint32_t ctime;
uint32_t timeout;
uint32_t stime;
bool f_time = false;
};
struct sdet_t { // used in streamDetection
uint32_t tmr_slow = 0;
uint32_t tmr_lost = 0;
uint32_t cnt_slow = 0;
uint8_t cnt_lost = 0;
};
struct fnsy_t { // used in findNextSync
int nextSync = 0;
uint32_t swnf = 0;
};
struct audioItems_t {
float gain_ls_db = 0.0; // lowshelf
float gain_peq_db = 0.0; // peakingEQ
float gain_hs_db = 0.0; // highshelf
float pre_gain = 0.0; // correction factor for level adjustment
float coeffs[3][5] = {0};
float state_biquad[3][4] = {0};
uint8_t volume = 0;
uint8_t volume_steps = 21;
float cur_volume = 0.0f;
float limiter[2] = {0};
float balance = 0.0f; // -16.0 dB left ... 0 ... -16 db right
bool mute = false;
};
struct i2s_items_t {
int32_t i2s_num = 0;
uint32_t sampleRate = 48000;
bool commFMT = false;
};
struct vu_items_t {
ps_ptr<int32_t> delay_l;
ps_ptr<int32_t> delay_r;
uint16_t delay_line_index = 0;
float left = 0; // average value of samples, left channel
float right = 0; // average value of samples, right channel
uint8_t left_peak = 0;
uint8_t right_peak = 0;
uint16_t left_hold = 0;
uint16_t right_hold = 0;
};
#define FFT_BANDS 6
#define FFT_SIZE 256
struct fft_items_t {
const uint16_t SIZE = FFT_SIZE;
const uint16_t BANDS = FFT_BANDS;
ps_ptr<float> buffer; // FFT input (real)
ps_ptr<float> window; // FFT window
uint16_t buffer_index = 0;
uint16_t pos = 0;
bool initialized = false; // FFT state
float spec_smooth[FFT_BANDS] = {0}; // smoothing
uint32_t last_ms = 0; // timing (10 Hz)
float gain = 1.0f; // AGC in process()
bool lr_switch = false; // start/stop
ps_ptr<float> work; // FFT work buffer (complex interleaved)
uint8_t spectrum[FFT_BANDS] = {0}; // output
};
struct Biquad {
int64_t z1 = 0;
int64_t z2 = 0;
};
struct BiquadCoeffs {
int64_t b0;
int64_t b1;
int64_t b2;
int64_t a1;
int64_t a2;
};
struct resampler_t {
static constexpr size_t MAX_IN_FRAMES = 4608;
static constexpr size_t MAX_OUT_FRAMES = 10500;
uint64_t phase = 0;
uint64_t phaseStep = 0;
Biquad lpLeft;
Biquad lpRight;
uint32_t outFrames = 0;
BiquadCoeffs g_lpCoeffs;
// Condition for continuous interpolation between frames
int32_t lastL = 0; // Last left sample from previous frame
int32_t lastR = 0; // Last right sample from previous frame
bool hasLast = false; // First frame has no “last”
};
struct info_queue_t {
std::deque<ps_ptr<char>> msg = {};
std::deque<ps_ptr<char>> s = {};
std::deque<uint8_t> e = {}; // event type
std::deque<int32_t> arg1 = {};
std::deque<int32_t> arg2 = {};
std::deque<std::vector<uint32_t>> vec = {}; // apic [pos, len, pos, len, pos, len, ....]
void reset() { *this = info_queue_t{}; }
};
struct icy_items_t {
ps_ptr<char> icy_genre = {};
ps_ptr<char> icy_logo = {};
ps_ptr<char> icy_name = {};
ps_ptr<char> icy_description = {};
ps_ptr<char> icy_url = {};
ps_ptr<char> icy_metaint = {};
ps_ptr<char> icy_br = {};
void reset() { *this = icy_items_t{}; }
};
} // namespace audiolib

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,258 @@
/*
* flac_decoder.h
*
* Created on: Jul 03,2020
* Updated on: Apr 25,2025
*
* Author: wolle
*
* Restrictions:
* blocksize must not exceed 24576 bytes
* bits per sample must be 8, 16, 24 or 32
* num Channels must be 1 or 2
*
*
*/
#pragma once
#pragma GCC optimize("Ofast")
#include "../Audio.h"
#define ANSI_ESC_RESET "\033[0m"
#define ANSI_ESC_BLACK "\033[30m"
#define ANSI_ESC_RED "\033[31m"
#define ANSI_ESC_GREEN "\033[32m"
#define ANSI_ESC_YELLOW "\033[33m"
#define ANSI_ESC_BLUE "\033[34m"
#define ANSI_ESC_MAGENTA "\033[35m"
#define ANSI_ESC_CYAN "\033[36m"
#define ANSI_ESC_WHITE "\033[37m"
class FlacDecoder : public Decoder {
public:
FlacDecoder(Audio& audioRef) : Decoder(audioRef), audio(audioRef) {}
~FlacDecoder() { reset(); }
bool init() override;
void clear() override;
void reset() override;
bool isValid() override;
int32_t findSyncWord(uint8_t* buf, int32_t nBytes) override;
uint8_t getChannels() override;
uint32_t getSampleRate() override;
uint32_t getOutputSamples();
uint8_t getBitsPerSample() override;
uint32_t getBitRate() override;
uint32_t getAudioDataStart() override;
uint32_t getAudioFileDuration() override;
const char* getStreamTitle() override;
const char* whoIsIt() override;
int32_t decode(uint8_t* inbuf, int32_t* bytesLeft, int32_t* outbuf) override;
void setRawBlockParams(uint8_t channels, uint32_t sampleRate, uint8_t BPS, uint32_t tsis, uint32_t AuDaLength) override;
std::vector<uint32_t> getMetadataBlockPicture() override;
const char* arg1() override;
const char* arg2() override;
virtual int32_t val1() override;
virtual int32_t val2() override;
enum : int8_t {
FLAC_PARSE_OGG_DONE = 100,
FLAC_DECODE_FRAMES_LOOP = 100,
FLAC_OGG_SYNC_FOUND = +2,
GIVE_NEXT_LOOP = +1,
FLAC_NONE = 0,
FLAC_ERR = -1,
FLAC_STOP = -100,
};
private:
Audio& audio;
#define FLAC_MAX_CHANNELS 2
#define FLAC_MAX_BLOCKSIZE 24576 // 24 * 1024
#define FLAC_MAX_OUTBUFFSIZE 4096 * 2
enum : uint8_t { FLACDECODER_INIT, FLACDECODER_READ_IN, FLACDECODER_WRITE_OUT };
enum : uint8_t { DECODE_FRAME, DECODE_SUBFRAMES, OUT_SAMPLES };
typedef struct FLACMetadataBlock_t {
// METADATA_BLOCK_STREAMINFO
uint16_t minblocksize; // The minimum block size (in samples) used in the stream.
//----------------------------------------------------------------------------------------
// The maximum block size (in samples) used in the stream.
uint16_t maxblocksize; // (Minimum blocksize == maximum blocksize) implies a fixed-blocksize stream.
//----------------------------------------------------------------------------------------
// The minimum frame size (in bytes) used in the stream.
uint32_t minframesize; // May be 0 to imply the value is not known.
//----------------------------------------------------------------------------------------
// The maximum frame size (in bytes) used in the stream.
uint32_t maxframesize; // May be 0 to imply the value is not known.
//----------------------------------------------------------------------------------------
// Sample rate in Hz. Though 20 bits are available,
// the maximum sample rate is limited by the structure of frame headers to 655350Hz.
uint32_t sampleRate; // Also, a value of 0 is invalid.
//----------------------------------------------------------------------------------------
// Number of channels FLAC supports from 1 to 8 channels
uint8_t numChannels; // 000 : 1 channel .... 111 : 8 channels
//----------------------------------------------------------------------------------------
// Sample size in bits:
// 000 : get from STREAMINFO metadata block
// 001 : 8 bits per sample
// 010 : 12 bits per sample
// 011 : reserved
// 100 : 16 bits per sample
// 101 : 20 bits per sample
// 110 : 24 bits per sample
uint8_t bitsPerSample; // 111 : reserved
//----------------------------------------------------------------------------------------
// Total samples in stream. 'Samples' means inter-channel sample,
// i.e. one second of 44.1Khz audio will have 44100 samples regardless of the number
uint64_t totalSamples; // of channels. A value of zero here means the number of total samples is unknown.
//----------------------------------------------------------------------------------------
uint32_t audioDataLength; // is not the filelength, is only the length of the audio datablock in bytes
} FLACMetadataBlock_t;
typedef struct FLACFrameHeader_t {
// 0 : fixed-blocksize stream; frame header encodes the frame number
uint8_t blockingStrategy; // 1 : variable-blocksize stream; frame header encodes the sample number
//----------------------------------------------------------------------------------------
// Block size in inter-channel samples:
// 0000 : reserved
// 0001 : 192 samples
// 0010-0101 : 576 * (2^(n-2)) samples, i.e. 576/1152/2304/4608
// 0110 : get 8 bit (blocksize-1) from end of header
// 0111 : get 16 bit (blocksize-1) from end of header
uint8_t blockSizeCode; // 1000-1111 : 256 * (2^(n-8)) samples, i.e. 256/512/1024/2048/4096/8192/16384/32768
//----------------------------------------------------------------------------------------
// 0000 : get from STREAMINFO metadata block
// 0001 : 88.2kHz
// 0010 : 176.4kHz
// 0011 : 192kHz
// 0100 : 8kHz
// 0101 : 16kHz
// 0110 : 22.05kHz
// 0111 : 24kHz
// 1000 : 32kHz
// 1001 : 44.1kHz
// 1010 : 48kHz
// 1011 : 96kHz
// 1100 : get 8 bit sample rate (in kHz) from end of header
// 1101 : get 16 bit sample rate (in Hz) from end of header
// 1110 : get 16 bit sample rate (in tens of Hz) from end of header
uint8_t sampleRateCode; // 1111 : invalid, to prevent sync-fooling string of 1s
//----------------------------------------------------------------------------------------
// Channel assignment
// 0000 1 channel: mono
// 0001 2 channels: left, right
// 0010 3 channels
// 0011 4 channels
// 0100 5 channels
// 0101 6 channels
// 0110 7 channels
// 0111 8 channels
// 1000 : left/side stereo: channel 0 is the left channel, channel 1 is the side(difference) channel
// 1001 : right/side stereo: channel 0 is the side(difference) channel, channel 1 is the right channel
// 1010 : mid/side stereo: channel 0 is the mid(average) channel, channel 1 is the side(difference) channel
uint8_t chanAsgn; // 1011-1111 : reserved
//----------------------------------------------------------------------------------------
// Sample size in bits:
// 000 : get from STREAMINFO metadata block
// 001 : 8 bits per sample
// 010 : 12 bits per sample
// 011 : reserved
// 100 : 16 bits per sample
// 101 : 20 bits per sample
// 110 : 24 bits per sample
uint8_t sampleSizeCode; // 111 : reserved
//----------------------------------------------------------------------------------------
uint32_t totalSamples; // totalSamplesInStream
//----------------------------------------------------------------------------------------
uint32_t bitrate; // bitrate
} FLACFrameHeader_t;
const std::deque<std::deque<int>> FIXED_PREDICTION_COEFFICIENTS = {
{}, // {}
{1}, // {1}
{2, -1}, // {2, -1}
{3, -3, 1}, // {3, -3, 1}
{4, -6, 4, -1} // {4, -6, 4, -1}
};
// std::deque<int> coefs;
ps_ptr<FLACFrameHeader_t> FLACFrameHeader;
ps_ptr<FLACMetadataBlock_t> FLACMetadataBlock;
std::vector<uint32_t> m_flacSegmTableVec;
std::vector<int32_t> coefs;
std::vector<uint32_t> m_flacBlockPicItem;
uint64_t m_flac_bitBuffer = 0;
uint32_t m_flacBitrate = 0;
uint32_t m_flacBlockPicLenUntilFrameEnd = 0;
uint32_t m_flacCurrentFilePos = 0;
uint32_t m_flacBlockPicPos = 0;
uint32_t m_flacBlockPicLen = 0;
uint32_t m_segmLength = 0;
uint32_t m_flacAudioDataStart = 0;
int32_t m_flacRemainBlockPicLen = 0;
uint32_t m_segmLenTmp = 0;
uint16_t m_numOfOutSamples = 0;
uint16_t m_flacValidSamples = 0;
uint16_t m_rIndex = 0;
uint16_t m_offset = 0;
uint8_t m_flacStatus = 0;
uint8_t* m_flacInptr;
float m_flacCompressionRatio = 0;
uint8_t m_flacBitBufferLen = 0;
bool m_f_flacParseOgg = false;
bool m_f_bitReaderError = false;
uint8_t m_flac_pageSegments = 0;
ps_ptr<char> m_flacStreamTitle = {};
ps_ptr<char> m_flacVendorString = {};
bool m_f_flacNewStreamtitle = false;
bool m_f_flacFirstCall = true;
bool m_f_oggWrapper = false;
bool m_f_lastMetaDataBlock = false;
bool m_f_flacNewMetadataBlockPicture = false;
bool m_valid = false;
bool m_continued_page = false;
bool m_f_first_flac_frame = false;
uint8_t m_flacPageNr = 0;
ps_ptr<int64_t> m_samplesBuffer[2];
uint16_t m_maxBlocksize = FLAC_MAX_BLOCKSIZE;
int32_t m_nBytes = 0;
boolean FLACFindMagicWord(unsigned char* buf, int32_t nBytes);
int32_t parseOGG(uint8_t* inbuf, int32_t* bytesLeft);
int32_t parseFlacFirstPacket(uint8_t* inbuf, int16_t nBytes);
int32_t parseMetaDataBlockHeader(uint8_t* inbuf, int16_t nBytes);
void setDefaults();
void decoderReset();
int8_t decodeNative(uint8_t* inbuf, int32_t* bytesLeft, int32_t* outbuf);
int8_t decodeFrame(uint8_t* inbuf, int32_t* bytesLeft);
uint64_t getTotoalSamplesInStream();
uint32_t readUint(uint8_t nBits, int32_t* bytesLeft);
void alignToByte();
int8_t decodeSubframes(int32_t* bytesLeft);
int8_t decodeSubframe(uint8_t sampleDepth, uint8_t ch, int32_t* bytesLeft);
int8_t decodeFixedPredictionSubframe(uint8_t predOrder, uint8_t sampleDepth, uint8_t ch, int32_t* bytesLeft);
int8_t decodeLinearPredictiveCodingSubframe(int32_t lpcOrder, int32_t sampleDepth, uint8_t ch, int32_t* bytesLeft);
int8_t decodeResiduals(uint8_t warmup, uint8_t ch, int32_t* bytesLeft);
void restoreLinearPrediction(uint8_t ch, uint8_t shift);
int32_t specialIndexOf(uint8_t* base, const char* str, int32_t baselen, bool exact = false);
inline int32_t readSignedInt(int32_t nBits, int32_t* bytesLeft) {
int32_t temp = readUint(nBits, bytesLeft) << (32 - nBits);
temp = temp >> (32 - nBits); // The C++ compiler uses the sign bit to fill vacated bit positions
return temp;
}
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// Macro for comfortable calls
#define FLAC_LOG_ERROR(fmt, ...) Audio::AUDIO_LOG_IMPL(1, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define FLAC_LOG_WARN(fmt, ...) Audio::AUDIO_LOG_IMPL(2, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define FLAC_LOG_INFO(fmt, ...) Audio::AUDIO_LOG_IMPL(3, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define FLAC_LOG_DEBUG(fmt, ...) Audio::AUDIO_LOG_IMPL(4, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define FLAC_LOG_VERBOSE(fmt, ...) Audio::AUDIO_LOG_IMPL(5, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
};
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,123 @@
// based om helix mp3 decoder
#pragma once
#include "../Audio.h"
#include "structs.h"
#include "tables.h"
class MP3Decoder : public Decoder {
public:
MP3Decoder(Audio& audioRef) : Decoder(audioRef), audio(audioRef) {}
~MP3Decoder() { reset(); }
bool init() override;
void clear() override;
void reset() override;
bool isValid() override;
int32_t findSyncWord(uint8_t* buf, int32_t nBytes) override;
uint8_t getChannels() override;
uint32_t getSampleRate() override;
uint32_t getOutputSamples();
uint8_t getBitsPerSample() override;
uint32_t getBitRate() override;
uint32_t getAudioDataStart() override;
uint32_t getAudioFileDuration() override;
const char* getStreamTitle() override;
const char* whoIsIt() override;
int32_t decode(uint8_t* inbuf, int32_t* bytesLeft, int32_t* outbuf) override;
void setRawBlockParams(uint8_t channels, uint32_t sampleRate, uint8_t BPS, uint32_t tsis, uint32_t AuDaLength) override;
std::vector<uint32_t> getMetadataBlockPicture() override;
const char* arg1() override; // MPEG Version and Layer
const char* arg2() override;
virtual int32_t val1() override;
virtual int32_t val2() override;
enum {
MP3_NONE = 0,
MP3_ERR = -1,
MP3_MAIN_DATA_UNDERFLOW = -2,
MP3_NEED_RESTART = -3,
MP3_STOP = -100,
MP3_NEXT_FRAME = 100,
};
private:
Audio& audio;
SFBandTable_t m_SFBandTable;
StereoMode_t m_sMode; /* mono/stereo mode */
MPEGVersion_t m_MPEGVersion; /* version ID */
SideInfoSub_t m_SideInfoSub[MAX_NGRAN][MAX_NCHAN];
CriticalBandInfo_t m_CriticalBandInfo[MAX_NCHAN]; /* filled in dequantizer, used in joint stereo reconstruction */
ScaleFactorInfoSub_t m_ScaleFactorInfoSub[MAX_NGRAN][MAX_NCHAN];
ps_ptr<MP3DecInfo_t> m_MP3DecInfo;
ps_ptr<FrameHeader_t> m_FrameHeader;
ps_ptr<SideInfo_t> m_SideInfo;
ps_ptr<ScaleFactorJS_t> m_ScaleFactorJS;
ps_ptr<HuffmanInfo_t> m_HuffmanInfo;
ps_ptr<DequantInfo_t> m_DequantInfo;
ps_ptr<IMDCTInfo_t> m_IMDCTInfo;
ps_ptr<SubbandInfo_t> m_SubbandInfo;
ps_ptr<MP3FrameInfo_t> m_MP3FrameInfo;
ps_ptr<char> m_mpeg_version_str;
ps_ptr<int16_t> m_out16;
invalid_frame m_invalid_frame;
// internally used
int32_t IsLikelyRealFrame(const uint8_t* p, int32_t bytesLeft);
void MP3GetLastFrameInfo();
int32_t MP3GetNextFrameInfo(uint8_t* buf);
int MP3_AnalyzeFrame(const uint8_t* frame_data, size_t frame_len);
void PolyphaseMono(int16_t* pcm, int32_t* vbuf, const uint32_t* coefBase);
void PolyphaseStereo(int16_t* pcm, int32_t* vbuf, const uint32_t* coefBase);
void SetBitstreamPointer(BitStreamInfo_t* bsi, int32_t nBytes, uint8_t* buf);
uint32_t GetBits(BitStreamInfo_t* bsi, int32_t nBits);
int32_t CalcBitsUsed(BitStreamInfo_t* bsi, uint8_t* startBuf, int32_t startOffset);
int32_t DequantChannel(int32_t* sampleBuf, int32_t* workBuf, int32_t* nonZeroBound, SideInfoSub_t* sis, ScaleFactorInfoSub_t* sfis, CriticalBandInfo_t* cbi);
void MidSideProc(int32_t x[MAX_NCHAN][MAX_NSAMP], int32_t nSamps, int32_t mOut[2]);
void IntensityProcMPEG1(int32_t x[MAX_NCHAN][MAX_NSAMP], int32_t nSamps, ScaleFactorInfoSub_t* sfis, CriticalBandInfo_t* cbi, int32_t midSideFlag, int32_t mixFlag, int32_t mOut[2]);
void IntensityProcMPEG2(int32_t x[MAX_NCHAN][MAX_NSAMP], int32_t nSamps, ScaleFactorInfoSub_t* sfis, CriticalBandInfo_t* cbi, ScaleFactorJS_t* sfjs, int32_t midSideFlag, int32_t mixFlag,
int32_t mOut[2]);
void FDCT32(int32_t* x, int32_t* d, int32_t offset, int32_t oddBlock, int32_t gb); // __attribute__ ((section (".data")));
int32_t CheckPadBit();
int32_t UnpackFrameHeader(uint8_t* buf);
int32_t UnpackSideInfo(uint8_t* buf);
int32_t DecodeHuffman(uint8_t* buf, int32_t* bitOffset, int32_t huffBlockBits, int32_t gr, int32_t ch);
int32_t MP3Dequantize(int32_t gr);
int32_t IMDCT(int32_t gr, int32_t ch);
int32_t UnpackScaleFactors(uint8_t* buf, int32_t* bitOffset, int32_t bitsAvail, int32_t gr, int32_t ch);
int32_t Subband(int16_t* pcmBuf);
int16_t ClipToShort(int32_t x, int32_t fracBits);
void RefillBitstreamCache(BitStreamInfo_t* bsi);
void UnpackSFMPEG1(BitStreamInfo_t* bsi, SideInfoSub_t* sis, ScaleFactorInfoSub_t* sfis, int32_t* scfsi, int32_t gr, ScaleFactorInfoSub_t* sfisGr0);
void UnpackSFMPEG2(BitStreamInfo_t* bsi, SideInfoSub_t* sis, ScaleFactorInfoSub_t* sfis, int32_t gr, int32_t ch, int32_t modeExt, ScaleFactorJS_t* sfjs);
int32_t MP3FindFreeSync(uint8_t* buf, uint8_t firstFH[4], int32_t nBytes);
void MP3ClearBadFrame(int16_t* outbuf);
int32_t DecodeHuffmanPairs(int32_t* xy, int32_t nVals, int32_t tabIdx, int32_t bitsLeft, uint8_t* buf, int32_t bitOffset);
int32_t DecodeHuffmanQuads(int32_t* vwxy, int32_t nVals, int32_t tabIdx, int32_t bitsLeft, uint8_t* buf, int32_t bitOffset);
int32_t DequantBlock(int32_t* inbuf, int32_t* outbuf, int32_t num, int32_t scale);
void AntiAlias(int32_t* x, int32_t nBfly);
void WinPrevious(int32_t* xPrev, int32_t* xPrevWin, int32_t btPrev);
int32_t FreqInvertRescale(int32_t* y, int32_t* xPrev, int32_t blockIdx, int32_t es);
void idct9(int32_t* x);
int32_t IMDCT36(int32_t* xCurr, int32_t* xPrev, int32_t* y, int32_t btCurr, int32_t btPrev, int32_t blockIdx, int32_t gb);
void imdct12(int32_t* x, int32_t* out);
int32_t IMDCT12x3(int32_t* xCurr, int32_t* xPrev, int32_t* y, int32_t btPrev, int32_t blockIdx, int32_t gb);
int32_t HybridTransform(int32_t* xCurr, int32_t* xPrev, int32_t y[BLOCK_SIZE][NBANDS], SideInfoSub_t* sis, BlockCount_t* bc);
uint64_t SAR64(uint64_t x, int32_t n);
int32_t MULSHIFT32(int32_t x, int32_t y);
uint64_t MADD64(uint64_t sum64, int32_t x, int32_t y); /* returns 64-bit value in [edx:eax] */
uint64_t xSAR64(uint64_t x, int32_t n);
int32_t FASTABS(int32_t x); // xtensa has a fast abs instruction //fb
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// Macro for comfortable calls
#define MP3_LOG_ERROR(fmt, ...) Audio::AUDIO_LOG_IMPL(1, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define MP3_LOG_WARN(fmt, ...) Audio::AUDIO_LOG_IMPL(2, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define MP3_LOG_INFO(fmt, ...) Audio::AUDIO_LOG_IMPL(3, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define MP3_LOG_DEBUG(fmt, ...) Audio::AUDIO_LOG_IMPL(4, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define MP3_LOG_VERBOSE(fmt, ...) Audio::AUDIO_LOG_IMPL(5, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
};

View File

@@ -0,0 +1,233 @@
#pragma once
#include "stdint-gcc.h"
#define SYNCWORDH 0xFF
#define SYNCWORDL 0xE0
#define DQ_FRACBITS_OUT 25 // number of fraction bits in output of dequant
#define CSHIFT 12 // coefficients have 12 leading sign bits for early-terminating mulitplies
#define SIBYTES_MPEG1_MONO 17
#define SIBYTES_MPEG1_STEREO 32
#define SIBYTES_MPEG2_MONO 9
#define SIBYTES_MPEG2_STEREO 17
#define IMDCT_SCALE 2 // additional scaling (by sqrt(2)) for fast IMDCT36
#define NGRANS_MPEG1 2
#define NGRANS_MPEG2 1
#define SQRTHALF 0x5a82799a // sqrt(0.5) in Q31 format
#define MAX_NGRAN 2 /* max granules */
#define MAX_NCHAN 2 /* max channels */
#define MAX_NSAMP 576 /* max samples per channel, per granule */
#define MAX_SCFBD 4 /* max scalefactor bands per channel */
#define NGRANS_MPEG1 2
#define NGRANS_MPEG2 1
#define HUFF_PAIRTABS 32
#define BLOCK_SIZE 18
#define NBANDS 32
#define MAX_REORDER_SAMPS (192 - 126) * 3 // largest critical band for short blocks (see sfBandTable)
#define VBUF_LENGTH 17 * 2 * NBANDS // for double-sized vbuf FIFO
#define MAX_SCFBD 4 // max scalefactor bands per channel
#define MAINBUF_SIZE 1940
#define MAX_NGRAN 2 // max granules
#define MAX_NCHAN 2 // max channels
#define MAX_NSAMP 576 // max samples per channel, per granule
#define CLZ(x) __builtin_clz(x) // fb
#define CLIP_2N(y, n) \
{ \
int32_t x = 1 << n; \
if (y < -x) y = -x; \
x--; \
if (y > x) y = x; \
}
#define D32FP(i, s1, s2) \
{ \
a0 = buf[i]; \
a3 = buf[31 - i]; \
a1 = buf[15 - i]; \
a2 = buf[16 + i]; \
b0 = a0 + a3; \
b3 = MULSHIFT32(*cptr++, a0 - a3) << 1; \
b1 = a1 + a2; \
b2 = MULSHIFT32(*cptr++, a1 - a2) << (s1); \
buf[i] = b0 + b1; \
buf[15 - i] = MULSHIFT32(*cptr, b0 - b1) << (s2); \
buf[16 + i] = b2 + b3; \
buf[31 - i] = MULSHIFT32(*cptr++, b3 - b2) << (s2); \
}
typedef struct MP3FrameInfo {
int32_t bitrate;
int32_t nChans;
int32_t samprate;
int32_t bitsPerSample;
int32_t outputSamps;
int32_t layer;
int32_t version;
} MP3FrameInfo_t;
typedef struct SFBandTable {
int32_t l[23];
int32_t s[14];
} SFBandTable_t;
typedef struct BitStreamInfo {
uint8_t* bytePtr;
uint32_t iCache;
int32_t cachedBits;
int32_t nBytes;
} BitStreamInfo_t;
typedef enum { /* map these to the corresponding 2-bit values in the frame header */
Stereo = 0x00, /* two independent channels, but L and R frames might have different # of bits */
Joint = 0x01, /* coupled channels - layer III: mix of M-S and intensity, Layers I/II: intensity and direct coding only */
Dual = 0x02, /* two independent channels, L and R always have exactly 1/2 the total bitrate */
Mono = 0x03 /* one channel */
} StereoMode_t;
typedef enum { /* map to 0,1,2 to make table indexing easier */
MPEG1 = 0,
MPEG2 = 1,
MPEG25 = 2
} MPEGVersion_t;
typedef struct FrameHeader {
int32_t layer; /* layer index (1, 2, or 3) */
int32_t crc; /* CRC flag: 0 = disabled, 1 = enabled */
int32_t brIdx; /* bitrate index (0 - 15) */
int32_t srIdx; /* sample rate index (0 - 2) */
int32_t paddingBit; /* padding flag: 0 = no padding, 1 = single pad byte */
int32_t privateBit; /* unused */
int32_t modeExt; /* used to decipher joint stereo mode */
int32_t copyFlag; /* copyright flag: 0 = no, 1 = yes */
int32_t origFlag; /* original flag: 0 = copy, 1 = original */
int32_t emphasis; /* deemphasis mode */
int32_t CRCWord; /* CRC word (16 bits, 0 if crc not enabled) */
} FrameHeader_t;
typedef struct SideInfoSub {
int32_t part23Length; /* number of bits in main data */
int32_t nBigvals; /* 2x this = first set of Huffman cw's (maximum amplitude can be > 1) */
int32_t globalGain; /* overall gain for dequantizer */
int32_t sfCompress; /* unpacked to figure out number of bits in scale factors */
int32_t winSwitchFlag; /* window switching flag */
int32_t blockType; /* block type */
int32_t mixedBlock; /* 0 = regular block (all short or long), 1 = mixed block */
int32_t tableSelect[3]; /* index of Huffman tables for the big values regions */
int32_t subBlockGain[3]; /* subblock gain offset, relative to global gain */
int32_t region0Count; /* 1+region0Count = num scale factor bands in first region of bigvals */
int32_t region1Count; /* 1+region1Count = num scale factor bands in second region of bigvals */
int32_t preFlag; /* for optional high frequency boost */
int32_t sfactScale; /* scaling of the scalefactors */
int32_t count1TableSelect; /* index of Huffman table for quad codewords */
} SideInfoSub_t;
typedef struct SideInfo {
int32_t mainDataBegin;
int32_t privateBits;
int32_t scfsi[MAX_NCHAN][MAX_SCFBD]; /* 4 scalefactor bands per channel */
} SideInfo_t;
typedef struct {
int32_t cbType; /* pure long = 0, pure short = 1, mixed = 2 */
int32_t cbEndS[3]; /* number nonzero short cb's, per subbblock */
int32_t cbEndSMax; /* max of cbEndS[] */
int32_t cbEndL; /* number nonzero long cb's */
} CriticalBandInfo_t;
typedef struct DequantInfo {
int32_t workBuf[MAX_REORDER_SAMPS]; /* workbuf for reordering short blocks */
} DequantInfo_t;
typedef struct HuffmanInfo {
int32_t huffDecBuf[MAX_NCHAN][MAX_NSAMP]; /* used both for decoded Huffman values and dequantized coefficients */
int32_t nonZeroBound[MAX_NCHAN]; /* number of coeffs in huffDecBuf[ch] which can be > 0 */
int32_t gb[MAX_NCHAN]; /* minimum number of guard bits in huffDecBuf[ch] */
} HuffmanInfo_t;
typedef enum HuffTabType { noBits, oneShot, loopNoLinbits, loopLinbits, quadA, quadB, invalidTab } HuffTabType_t;
typedef struct HuffTabLookup {
int32_t linBits;
int32_t tabType; /*HuffTabType*/
} HuffTabLookup_t;
typedef struct IMDCTInfo {
int32_t outBuf[MAX_NCHAN][BLOCK_SIZE][NBANDS]; /* output of IMDCT */
int32_t overBuf[MAX_NCHAN][MAX_NSAMP / 2]; /* overlap-add buffer (by symmetry, only need 1/2 size) */
int32_t numPrevIMDCT[MAX_NCHAN]; /* how many IMDCT's calculated in this channel on prev. granule */
int32_t prevType[MAX_NCHAN];
int32_t prevWinSwitch[MAX_NCHAN];
int32_t gb[MAX_NCHAN];
} IMDCTInfo_t;
typedef struct BlockCount {
int32_t nBlocksLong;
int32_t nBlocksTotal;
int32_t nBlocksPrev;
int32_t prevType;
int32_t prevWinSwitch;
int32_t currWinSwitch;
int32_t gbIn;
int32_t gbOut;
} BlockCount_t;
typedef struct ScaleFactorInfoSub { /* max bits in scalefactors = 5, so use char's to save space */
char l[23]; /* [band] */
char s[13][3]; /* [band][window] */
} ScaleFactorInfoSub_t;
typedef struct ScaleFactorJS { /* used in MPEG 2, 2.5 intensity (joint) stereo only */
int32_t intensityScale;
int32_t slen[4];
int32_t nr[4];
} ScaleFactorJS_t;
/* NOTE - could get by with smaller vbuf if memory is more important than speed
* (in Subband, instead of replicating each block in FDCT32 you would do a memmove on the
* last 15 blocks to shift them down one, a hardware style FIFO)
*/
typedef struct SubbandInfo {
int32_t vbuf[MAX_NCHAN * VBUF_LENGTH]; /* vbuf for fast DCT-based synthesis PQMF - double size for speed (no modulo indexing) */
int32_t vindex; /* internal index for tracking position in vbuf */
} SubbandInfo_t;
typedef struct MP3DecInfo {
/* buffer which must be large enough to hold largest possible main_data section */
uint8_t mainBuf[MAINBUF_SIZE];
/* special info for "free" bitrate files */
int32_t freeBitrateFlag;
int32_t freeBitrateSlots;
/* user-accessible info */
int32_t bitrate;
int32_t nChans;
int32_t samprate;
int32_t nGrans; /* granules per frame */
int32_t nGranSamps; /* samples per granule */
int32_t nSlots;
int32_t layer;
int32_t mainDataBegin;
int32_t mainDataBytes;
int32_t part23Length[MAX_NGRAN][MAX_NCHAN];
} MP3DecInfo_t;
typedef struct {
uint8_t mpeg_version; // 0=MPEG2.5, 1=reserved, 2=MPEG2, 3=MPEG1
uint8_t layer; // 0=reserved, 1=Layer III, 2=Layer II, 3=Layer I
bool crc_protected;
uint8_t bitrate_idx;
uint8_t sample_rate_idx;
bool padding;
uint8_t channel_mode;
uint32_t frame_length; // In Bytes
} Mp3FrameHeader;
struct invalid_frame {
uint32_t timer = 0;
bool start = true;
uint32_t count1 = 0;
uint32_t count2 = 0;
};

View File

@@ -0,0 +1,662 @@
#pragma once
#include "stdint-gcc.h"
#include "structs.h"
static const uint16_t huffTable[4242] = {
0xf003, 0x3112, 0x3101, 0x2011, 0x2011, 0x1000, 0x1000, 0x1000, 0x1000, 0xf006, 0x6222, 0x6201, 0x5212, 0x5212, 0x5122, 0x5122, 0x5021, 0x5021, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112,
0x3112, 0x3112, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0xf006, 0x6222, 0x6201, 0x5212, 0x5212, 0x5122, 0x5122, 0x5021, 0x5021, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112,
0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2101, 0x2101, 0x2101, 0x2101, 0x2101, 0x2101, 0x2101, 0x2101, 0x2101, 0x2101, 0x2101, 0x2101, 0x2101,
0x2101, 0x2101, 0x2101, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0xf008, 0x8332, 0x8322, 0x7232, 0x7232,
0x6132, 0x6132, 0x6132, 0x6132, 0x7312, 0x7312, 0x7301, 0x7301, 0x7031, 0x7031, 0x7222, 0x7222, 0x6212, 0x6212, 0x6212, 0x6212, 0x6122, 0x6122, 0x6122, 0x6122, 0x6201, 0x6201, 0x6201, 0x6201,
0x6021, 0x6021, 0x6021, 0x6021, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112,
0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101,
0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3011, 0x3011, 0x3011, 0x3011,
0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011,
0x3011, 0x3011, 0x3011, 0x3011, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0xf007, 0x7332, 0x7301, 0x6322, 0x6322, 0x6232, 0x6232, 0x6031, 0x6031, 0x5312, 0x5312, 0x5312,
0x5312, 0x5132, 0x5132, 0x5132, 0x5132, 0x5222, 0x5222, 0x5222, 0x5222, 0x5201, 0x5201, 0x5201, 0x5201, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4122, 0x4122, 0x4122,
0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4021, 0x4021, 0x4021, 0x4021, 0x4021, 0x4021, 0x4021, 0x4021, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101,
0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112,
0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011,
0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0xf006, 0x0041, 0x0052,
0x005b, 0x0060, 0x0063, 0x0068, 0x006b, 0x6212, 0x5122, 0x5122, 0x6201, 0x6021, 0x4112, 0x4112, 0x4112, 0x4112, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3011, 0x3011,
0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0xf004, 0x4552, 0x4542, 0x4452, 0x4352, 0x3532, 0x3532, 0x3442, 0x3442, 0x3522,
0x3522, 0x3252, 0x3252, 0x2512, 0x2512, 0x2512, 0x2512, 0xf003, 0x2152, 0x2152, 0x3501, 0x3432, 0x2051, 0x2051, 0x3342, 0x3332, 0xf002, 0x2422, 0x2242, 0x1412, 0x1412, 0xf001, 0x1142, 0x1041,
0xf002, 0x2401, 0x2322, 0x2232, 0x2301, 0xf001, 0x1312, 0x1132, 0xf001, 0x1031, 0x1222, 0xf008, 0x0101, 0x010a, 0x010f, 0x8512, 0x8152, 0x0112, 0x0115, 0x8422, 0x8242, 0x8412, 0x7142, 0x7142,
0x8401, 0x8041, 0x8322, 0x8232, 0x8312, 0x8132, 0x8301, 0x8031, 0x6222, 0x6222, 0x6222, 0x6222, 0x6201, 0x6201, 0x6201, 0x6201, 0x6021, 0x6021, 0x6021, 0x6021, 0x4212, 0x4212, 0x4212, 0x4212,
0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122,
0x4122, 0x4122, 0x4122, 0x4122, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112,
0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112,
0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x2112, 0x3101, 0x3101, 0x3101, 0x3101,
0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101,
0x3101, 0x3101, 0x3101, 0x3101, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011,
0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000,
0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000,
0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000,
0x2000, 0x2000, 0x2000, 0x2000, 0xf003, 0x3552, 0x3452, 0x2542, 0x2542, 0x1352, 0x1352, 0x1352, 0x1352, 0xf002, 0x2532, 0x2442, 0x1522, 0x1522, 0xf001, 0x1252, 0x1501, 0xf001, 0x1432, 0x1342,
0xf001, 0x1051, 0x1332, 0xf006, 0x0041, 0x004a, 0x004f, 0x0052, 0x0057, 0x005a, 0x6412, 0x6142, 0x6322, 0x6232, 0x5312, 0x5312, 0x5132, 0x5132, 0x6301, 0x6031, 0x5222, 0x5222, 0x5201, 0x5201,
0x4212, 0x4212, 0x4212, 0x4212, 0x4122, 0x4122, 0x4122, 0x4122, 0x4021, 0x4021, 0x4021, 0x4021, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3101, 0x3101, 0x3101, 0x3101,
0x3101, 0x3101, 0x3101, 0x3101, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0xf003, 0x3552, 0x3542, 0x2532,
0x2532, 0x2352, 0x2352, 0x3452, 0x3501, 0xf002, 0x2442, 0x2522, 0x2252, 0x2512, 0xf001, 0x1152, 0x1432, 0xf002, 0x1342, 0x1342, 0x2051, 0x2401, 0xf001, 0x1422, 0x1242, 0xf001, 0x1332, 0x1041,
0xf008, 0x0101, 0x010a, 0x010f, 0x0118, 0x011b, 0x0120, 0x0125, 0x8712, 0x8172, 0x012a, 0x012d, 0x0132, 0x8612, 0x8162, 0x8061, 0x0137, 0x013a, 0x013d, 0x8412, 0x8142, 0x8041, 0x8322, 0x8232,
0x8301, 0x7312, 0x7312, 0x7132, 0x7132, 0x7031, 0x7031, 0x7222, 0x7222, 0x6212, 0x6212, 0x6212, 0x6212, 0x6122, 0x6122, 0x6122, 0x6122, 0x6201, 0x6201, 0x6201, 0x6201, 0x6021, 0x6021, 0x6021,
0x6021, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101,
0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101,
0x3101, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011,
0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0xf003, 0x3772, 0x3762, 0x3672, 0x3752, 0x3572, 0x3662,
0x2742, 0x2742, 0xf002, 0x2472, 0x2652, 0x2562, 0x2732, 0xf003, 0x2372, 0x2372, 0x2642, 0x2642, 0x3552, 0x3452, 0x2362, 0x2362, 0xf001, 0x1722, 0x1272, 0xf002, 0x2462, 0x2701, 0x1071, 0x1071,
0xf002, 0x1262, 0x1262, 0x2542, 0x2532, 0xf002, 0x1601, 0x1601, 0x2352, 0x2442, 0xf001, 0x1632, 0x1622, 0xf002, 0x2522, 0x2252, 0x1512, 0x1512, 0xf002, 0x1152, 0x1152, 0x2432, 0x2342, 0xf001,
0x1501, 0x1051, 0xf001, 0x1422, 0x1242, 0xf001, 0x1332, 0x1401, 0xf008, 0x0101, 0x0106, 0x010f, 0x0114, 0x0117, 0x8722, 0x8272, 0x011c, 0x7172, 0x7172, 0x8712, 0x8071, 0x8632, 0x8362, 0x8061,
0x011f, 0x0122, 0x8512, 0x7262, 0x7262, 0x8622, 0x8601, 0x7612, 0x7612, 0x7162, 0x7162, 0x8152, 0x8432, 0x8051, 0x0125, 0x8422, 0x8242, 0x8412, 0x8142, 0x8401, 0x8041, 0x7322, 0x7322, 0x7232,
0x7232, 0x6312, 0x6312, 0x6312, 0x6312, 0x6132, 0x6132, 0x6132, 0x6132, 0x7301, 0x7301, 0x7031, 0x7031, 0x6222, 0x6222, 0x6222, 0x6222, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122,
0x5122, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x5201, 0x5201, 0x5201, 0x5201, 0x5201, 0x5201, 0x5201,
0x5201, 0x5021, 0x5021, 0x5021, 0x5021, 0x5021, 0x5021, 0x5021, 0x5021, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112,
0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101,
0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101,
0x3101, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011,
0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000,
0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000,
0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000, 0x2000,
0x2000, 0xf002, 0x2772, 0x2762, 0x2672, 0x2572, 0xf003, 0x2662, 0x2662, 0x2742, 0x2742, 0x2472, 0x2472, 0x3752, 0x3552, 0xf002, 0x2652, 0x2562, 0x1732, 0x1732, 0xf001, 0x1372, 0x1642, 0xf002,
0x2542, 0x2452, 0x2532, 0x2352, 0xf001, 0x1462, 0x1701, 0xf001, 0x1442, 0x1522, 0xf001, 0x1252, 0x1501, 0xf001, 0x1342, 0x1332, 0xf007, 0x0081, 0x008a, 0x008f, 0x0092, 0x0097, 0x009a, 0x009d,
0x00a2, 0x00a5, 0x00a8, 0x7622, 0x7262, 0x7162, 0x00ad, 0x00b0, 0x00b3, 0x7512, 0x7152, 0x7432, 0x7342, 0x00b6, 0x7422, 0x7242, 0x7412, 0x6332, 0x6332, 0x6142, 0x6142, 0x6322, 0x6322, 0x6232,
0x6232, 0x7041, 0x7301, 0x6031, 0x6031, 0x5312, 0x5312, 0x5312, 0x5312, 0x5132, 0x5132, 0x5132, 0x5132, 0x5222, 0x5222, 0x5222, 0x5222, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212, 0x4212,
0x4212, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x4122, 0x5201, 0x5201, 0x5201, 0x5201, 0x5021, 0x5021, 0x5021, 0x5021, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000,
0x4000, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101,
0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3101, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011,
0x3011, 0xf003, 0x3772, 0x3762, 0x2672, 0x2672, 0x2752, 0x2752, 0x2572, 0x2572, 0xf002, 0x2662, 0x2742, 0x2472, 0x2562, 0xf001, 0x1652, 0x1732, 0xf002, 0x2372, 0x2552, 0x1722, 0x1722, 0xf001,
0x1272, 0x1642, 0xf001, 0x1462, 0x1712, 0xf002, 0x1172, 0x1172, 0x2701, 0x2071, 0xf001, 0x1632, 0x1362, 0xf001, 0x1542, 0x1452, 0xf002, 0x1442, 0x1442, 0x2601, 0x2501, 0xf001, 0x1612, 0x1061,
0xf001, 0x1532, 0x1352, 0xf001, 0x1522, 0x1252, 0xf001, 0x1051, 0x1401, 0xf006, 0x0041, 0x0082, 0x00c3, 0x00e4, 0x0105, 0x0116, 0x011f, 0x0130, 0x0139, 0x013e, 0x0143, 0x0146, 0x6212, 0x6122,
0x6201, 0x6021, 0x4112, 0x4112, 0x4112, 0x4112, 0x4101, 0x4101, 0x4101, 0x4101, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0xf006, 0x0108, 0x0111, 0x011a, 0x0123, 0x012c, 0x0131, 0x0136, 0x013f, 0x0144, 0x0147, 0x014c, 0x0151, 0x0156, 0x015b, 0x6f12, 0x61f2, 0x60f1, 0x0160, 0x0163, 0x0166, 0x62e2,
0x0169, 0x6e12, 0x61e2, 0x016c, 0x016f, 0x0172, 0x0175, 0x0178, 0x017b, 0x66c2, 0x6d32, 0x017e, 0x6d22, 0x62d2, 0x6d12, 0x67b2, 0x0181, 0x0184, 0x63c2, 0x0187, 0x6b42, 0x51d2, 0x51d2, 0x6d01,
0x60d1, 0x6a82, 0x68a2, 0x6c42, 0x64c2, 0x6b62, 0x66b2, 0x5c32, 0x5c32, 0x5c22, 0x5c22, 0x52c2, 0x52c2, 0x5b52, 0x5b52, 0x65b2, 0x6982, 0x5c12, 0x5c12, 0xf006, 0x51c2, 0x51c2, 0x6892, 0x6c01,
0x50c1, 0x50c1, 0x64b2, 0x6a62, 0x66a2, 0x6972, 0x5b32, 0x5b32, 0x53b2, 0x53b2, 0x6882, 0x6a52, 0x5b22, 0x5b22, 0x65a2, 0x6962, 0x54a2, 0x54a2, 0x6872, 0x6782, 0x5492, 0x5492, 0x6772, 0x6672,
0x42b2, 0x42b2, 0x42b2, 0x42b2, 0x4b12, 0x4b12, 0x4b12, 0x4b12, 0x41b2, 0x41b2, 0x41b2, 0x41b2, 0x5b01, 0x5b01, 0x50b1, 0x50b1, 0x5692, 0x5692, 0x5a42, 0x5a42, 0x5a32, 0x5a32, 0x53a2, 0x53a2,
0x5952, 0x5952, 0x5592, 0x5592, 0x4a22, 0x4a22, 0x4a22, 0x4a22, 0x42a2, 0x42a2, 0x42a2, 0x42a2, 0xf005, 0x4a12, 0x4a12, 0x41a2, 0x41a2, 0x5a01, 0x5862, 0x40a1, 0x40a1, 0x5682, 0x5942, 0x4392,
0x4392, 0x5932, 0x5852, 0x5582, 0x5762, 0x4922, 0x4922, 0x4292, 0x4292, 0x5752, 0x5572, 0x4832, 0x4832, 0x4382, 0x4382, 0x5662, 0x5742, 0x5472, 0x5652, 0x5562, 0x5372, 0xf005, 0x3912, 0x3912,
0x3912, 0x3912, 0x3192, 0x3192, 0x3192, 0x3192, 0x4901, 0x4901, 0x4091, 0x4091, 0x4842, 0x4842, 0x4482, 0x4482, 0x4272, 0x4272, 0x5642, 0x5462, 0x3822, 0x3822, 0x3822, 0x3822, 0x3282, 0x3282,
0x3282, 0x3282, 0x3812, 0x3812, 0x3812, 0x3812, 0xf004, 0x4732, 0x4722, 0x3712, 0x3712, 0x3172, 0x3172, 0x4552, 0x4701, 0x4071, 0x4632, 0x4362, 0x4542, 0x4452, 0x4622, 0x4262, 0x4532, 0xf003,
0x2182, 0x2182, 0x3801, 0x3081, 0x3612, 0x3162, 0x3601, 0x3061, 0xf004, 0x4352, 0x4442, 0x3522, 0x3522, 0x3252, 0x3252, 0x3501, 0x3501, 0x2512, 0x2512, 0x2512, 0x2512, 0x2152, 0x2152, 0x2152,
0x2152, 0xf003, 0x3432, 0x3342, 0x3051, 0x3422, 0x3242, 0x3332, 0x2412, 0x2412, 0xf002, 0x1142, 0x1142, 0x2401, 0x2041, 0xf002, 0x2322, 0x2232, 0x1312, 0x1312, 0xf001, 0x1132, 0x1301, 0xf001,
0x1031, 0x1222, 0xf003, 0x0082, 0x008b, 0x008e, 0x0091, 0x0094, 0x0097, 0x3ce2, 0x3dd2, 0xf003, 0x0093, 0x3eb2, 0x3be2, 0x3f92, 0x39f2, 0x3ae2, 0x3db2, 0x3bd2, 0xf003, 0x3f82, 0x38f2, 0x3cc2,
0x008d, 0x3e82, 0x0090, 0x27f2, 0x27f2, 0xf003, 0x2ad2, 0x2ad2, 0x3da2, 0x3cb2, 0x3bc2, 0x36f2, 0x2f62, 0x2f62, 0xf002, 0x28e2, 0x2f52, 0x2d92, 0x29d2, 0xf002, 0x25f2, 0x27e2, 0x2ca2, 0x2bb2,
0xf003, 0x2f42, 0x2f42, 0x24f2, 0x24f2, 0x3ac2, 0x36e2, 0x23f2, 0x23f2, 0xf002, 0x1f32, 0x1f32, 0x2d82, 0x28d2, 0xf001, 0x1f22, 0x12f2, 0xf002, 0x2e62, 0x2c92, 0x1f01, 0x1f01, 0xf002, 0x29c2,
0x2e52, 0x1ba2, 0x1ba2, 0xf002, 0x2d72, 0x27d2, 0x1e42, 0x1e42, 0xf002, 0x28c2, 0x26d2, 0x1e32, 0x1e32, 0xf002, 0x19b2, 0x19b2, 0x2b92, 0x2aa2, 0xf001, 0x1ab2, 0x15e2, 0xf001, 0x14e2, 0x1c82,
0xf001, 0x1d62, 0x13e2, 0xf001, 0x1e22, 0x1e01, 0xf001, 0x10e1, 0x1d52, 0xf001, 0x15d2, 0x1c72, 0xf001, 0x17c2, 0x1d42, 0xf001, 0x1b82, 0x18b2, 0xf001, 0x14d2, 0x1a92, 0xf001, 0x19a2, 0x1c62,
0xf001, 0x13d2, 0x1b72, 0xf001, 0x1c52, 0x15c2, 0xf001, 0x1992, 0x1a72, 0xf001, 0x17a2, 0x1792, 0xf003, 0x0023, 0x3df2, 0x2de2, 0x2de2, 0x1ff2, 0x1ff2, 0x1ff2, 0x1ff2, 0xf001, 0x1fe2, 0x1fd2,
0xf001, 0x1ee2, 0x1fc2, 0xf001, 0x1ed2, 0x1fb2, 0xf001, 0x1bf2, 0x1ec2, 0xf002, 0x1cd2, 0x1cd2, 0x2fa2, 0x29e2, 0xf001, 0x1af2, 0x1dc2, 0xf001, 0x1ea2, 0x1e92, 0xf001, 0x1f72, 0x1e72, 0xf001,
0x1ef2, 0x1cf2, 0xf008, 0x0101, 0x0122, 0x0143, 0x0154, 0x0165, 0x0176, 0x017f, 0x0188, 0x0199, 0x01a2, 0x01ab, 0x01b4, 0x01bd, 0x01c2, 0x01cb, 0x01d4, 0x01d9, 0x01de, 0x01e3, 0x01e8, 0x01ed,
0x01f2, 0x01f7, 0x01fc, 0x0201, 0x0204, 0x0207, 0x020a, 0x020f, 0x0212, 0x0215, 0x021a, 0x021d, 0x0220, 0x8192, 0x0223, 0x0226, 0x0229, 0x022c, 0x022f, 0x8822, 0x8282, 0x8812, 0x8182, 0x0232,
0x0235, 0x0238, 0x023b, 0x8722, 0x8272, 0x8462, 0x8712, 0x8552, 0x8172, 0x023e, 0x8632, 0x8362, 0x8542, 0x8452, 0x8622, 0x8262, 0x8612, 0x0241, 0x8532, 0x7162, 0x7162, 0x8352, 0x8442, 0x7522,
0x7522, 0x7252, 0x7252, 0x7512, 0x7512, 0x7152, 0x7152, 0x8501, 0x8051, 0x7432, 0x7432, 0x7342, 0x7342, 0x7422, 0x7422, 0x7242, 0x7242, 0x7332, 0x7332, 0x6142, 0x6142, 0x6142, 0x6142, 0x7412,
0x7412, 0x7401, 0x7401, 0x6322, 0x6322, 0x6322, 0x6322, 0x6232, 0x6232, 0x6232, 0x6232, 0x7041, 0x7041, 0x7301, 0x7301, 0x6312, 0x6312, 0x6312, 0x6312, 0x6132, 0x6132, 0x6132, 0x6132, 0x6031,
0x6031, 0x6031, 0x6031, 0x5222, 0x5222, 0x5222, 0x5222, 0x5222, 0x5222, 0x5222, 0x5222, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122,
0x5122, 0x5122, 0x5122, 0x5201, 0x5201, 0x5201, 0x5201, 0x5201, 0x5201, 0x5201, 0x5201, 0x5021, 0x5021, 0x5021, 0x5021, 0x5021, 0x5021, 0x5021, 0x5021, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112,
0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112, 0x3112,
0x3112, 0x3112, 0x3112, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011,
0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000,
0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0x3000, 0xf005, 0x5ff2, 0x5fe2, 0x5ef2, 0x5fd2,
0x4ee2, 0x4ee2, 0x5df2, 0x5fc2, 0x5cf2, 0x5ed2, 0x5de2, 0x5fb2, 0x4bf2, 0x4bf2, 0x5ec2, 0x5ce2, 0x4dd2, 0x4dd2, 0x4fa2, 0x4fa2, 0x4af2, 0x4af2, 0x4eb2, 0x4eb2, 0x4be2, 0x4be2, 0x4dc2, 0x4dc2,
0x4cd2, 0x4cd2, 0x4f92, 0x4f92, 0xf005, 0x49f2, 0x49f2, 0x4ae2, 0x4ae2, 0x4db2, 0x4db2, 0x4bd2, 0x4bd2, 0x4f82, 0x4f82, 0x48f2, 0x48f2, 0x4cc2, 0x4cc2, 0x4e92, 0x4e92, 0x49e2, 0x49e2, 0x4f72,
0x4f72, 0x47f2, 0x47f2, 0x4da2, 0x4da2, 0x4ad2, 0x4ad2, 0x4cb2, 0x4cb2, 0x4f62, 0x4f62, 0x5ea2, 0x5f01, 0xf004, 0x3bc2, 0x3bc2, 0x36f2, 0x36f2, 0x4e82, 0x48e2, 0x4f52, 0x4d92, 0x35f2, 0x35f2,
0x3e72, 0x3e72, 0x37e2, 0x37e2, 0x3ca2, 0x3ca2, 0xf004, 0x3ac2, 0x3ac2, 0x3bb2, 0x3bb2, 0x49d2, 0x4d82, 0x3f42, 0x3f42, 0x34f2, 0x34f2, 0x3f32, 0x3f32, 0x33f2, 0x33f2, 0x38d2, 0x38d2, 0xf004,
0x36e2, 0x36e2, 0x3f22, 0x3f22, 0x32f2, 0x32f2, 0x4e62, 0x40f1, 0x3f12, 0x3f12, 0x31f2, 0x31f2, 0x3c92, 0x3c92, 0x39c2, 0x39c2, 0xf003, 0x3e52, 0x3ba2, 0x3ab2, 0x35e2, 0x3d72, 0x37d2, 0x3e42,
0x34e2, 0xf003, 0x3c82, 0x38c2, 0x3e32, 0x3d62, 0x36d2, 0x33e2, 0x3b92, 0x39b2, 0xf004, 0x3e22, 0x3e22, 0x3aa2, 0x3aa2, 0x32e2, 0x32e2, 0x3e12, 0x3e12, 0x31e2, 0x31e2, 0x4e01, 0x40e1, 0x3d52,
0x3d52, 0x35d2, 0x35d2, 0xf003, 0x3c72, 0x37c2, 0x3d42, 0x3b82, 0x24d2, 0x24d2, 0x38b2, 0x3a92, 0xf003, 0x39a2, 0x3c62, 0x36c2, 0x3d32, 0x23d2, 0x23d2, 0x22d2, 0x22d2, 0xf003, 0x3d22, 0x3d01,
0x2d12, 0x2d12, 0x2b72, 0x2b72, 0x27b2, 0x27b2, 0xf003, 0x21d2, 0x21d2, 0x3c52, 0x30d1, 0x25c2, 0x25c2, 0x2a82, 0x2a82, 0xf002, 0x28a2, 0x2c42, 0x24c2, 0x2b62, 0xf003, 0x26b2, 0x26b2, 0x3992,
0x3c01, 0x2c32, 0x2c32, 0x23c2, 0x23c2, 0xf003, 0x2a72, 0x2a72, 0x27a2, 0x27a2, 0x26a2, 0x26a2, 0x30c1, 0x3b01, 0xf002, 0x12c2, 0x12c2, 0x2c22, 0x2b52, 0xf002, 0x25b2, 0x2c12, 0x2982, 0x2892,
0xf002, 0x21c2, 0x2b42, 0x24b2, 0x2a62, 0xf002, 0x2b32, 0x2972, 0x13b2, 0x13b2, 0xf002, 0x2792, 0x2882, 0x2b22, 0x2a52, 0xf002, 0x12b2, 0x12b2, 0x25a2, 0x2b12, 0xf002, 0x11b2, 0x11b2, 0x20b1,
0x2962, 0xf002, 0x2692, 0x2a42, 0x24a2, 0x2872, 0xf002, 0x2782, 0x2a32, 0x13a2, 0x13a2, 0xf001, 0x1952, 0x1592, 0xf001, 0x1a22, 0x12a2, 0xf001, 0x1a12, 0x11a2, 0xf002, 0x2a01, 0x20a1, 0x1862,
0x1862, 0xf001, 0x1682, 0x1942, 0xf001, 0x1492, 0x1932, 0xf002, 0x1392, 0x1392, 0x2772, 0x2901, 0xf001, 0x1852, 0x1582, 0xf001, 0x1922, 0x1762, 0xf001, 0x1672, 0x1292, 0xf001, 0x1912, 0x1091,
0xf001, 0x1842, 0x1482, 0xf001, 0x1752, 0x1572, 0xf001, 0x1832, 0x1382, 0xf001, 0x1662, 0x1742, 0xf001, 0x1472, 0x1801, 0xf001, 0x1081, 0x1652, 0xf001, 0x1562, 0x1732, 0xf001, 0x1372, 0x1642,
0xf001, 0x1701, 0x1071, 0xf001, 0x1601, 0x1061, 0xf008, 0x0101, 0x010a, 0x0113, 0x8ff2, 0x0118, 0x011d, 0x0120, 0x82f2, 0x0131, 0x8f12, 0x81f2, 0x0134, 0x0145, 0x0156, 0x0167, 0x0178, 0x0189,
0x019a, 0x01a3, 0x01ac, 0x01b5, 0x01be, 0x01c7, 0x01d0, 0x01d9, 0x01de, 0x01e3, 0x01e6, 0x01eb, 0x01f0, 0x8152, 0x01f3, 0x01f6, 0x01f9, 0x01fc, 0x8412, 0x8142, 0x01ff, 0x8322, 0x8232, 0x7312,
0x7312, 0x7132, 0x7132, 0x8301, 0x8031, 0x7222, 0x7222, 0x6212, 0x6212, 0x6212, 0x6212, 0x6122, 0x6122, 0x6122, 0x6122, 0x6201, 0x6201, 0x6201, 0x6201, 0x6021, 0x6021, 0x6021, 0x6021, 0x4112,
0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101,
0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011,
0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x3011, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000,
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0xf003,
0x3fe2, 0x3ef2, 0x3fd2, 0x3df2, 0x3fc2, 0x3cf2, 0x3fb2, 0x3bf2, 0xf003, 0x2fa2, 0x2fa2, 0x3af2, 0x3f92, 0x39f2, 0x38f2, 0x2f82, 0x2f82, 0xf002, 0x2f72, 0x27f2, 0x2f62, 0x26f2, 0xf002, 0x2f52,
0x25f2, 0x1f42, 0x1f42, 0xf001, 0x14f2, 0x13f2, 0xf004, 0x10f1, 0x10f1, 0x10f1, 0x10f1, 0x10f1, 0x10f1, 0x10f1, 0x10f1, 0x2f32, 0x2f32, 0x2f32, 0x2f32, 0x00e2, 0x00f3, 0x00fc, 0x0105, 0xf001,
0x1f22, 0x1f01, 0xf004, 0x00fa, 0x00ff, 0x0104, 0x0109, 0x010c, 0x0111, 0x0116, 0x0119, 0x011e, 0x0123, 0x0128, 0x43e2, 0x012d, 0x0130, 0x0133, 0x0136, 0xf004, 0x0128, 0x012b, 0x012e, 0x4d01,
0x0131, 0x0134, 0x0137, 0x4c32, 0x013a, 0x4c12, 0x40c1, 0x013d, 0x32e2, 0x32e2, 0x4e22, 0x4e12, 0xf004, 0x43d2, 0x4d22, 0x42d2, 0x41d2, 0x4b32, 0x012f, 0x3d12, 0x3d12, 0x44c2, 0x4b62, 0x43c2,
0x47a2, 0x3c22, 0x3c22, 0x42c2, 0x45b2, 0xf004, 0x41c2, 0x4c01, 0x4b42, 0x44b2, 0x4a62, 0x46a2, 0x33b2, 0x33b2, 0x4a52, 0x45a2, 0x3b22, 0x3b22, 0x32b2, 0x32b2, 0x3b12, 0x3b12, 0xf004, 0x31b2,
0x31b2, 0x4b01, 0x40b1, 0x4962, 0x4692, 0x4a42, 0x44a2, 0x4872, 0x4782, 0x33a2, 0x33a2, 0x4a32, 0x4952, 0x3a22, 0x3a22, 0xf004, 0x4592, 0x4862, 0x31a2, 0x31a2, 0x4682, 0x4772, 0x3492, 0x3492,
0x4942, 0x4752, 0x3762, 0x3762, 0x22a2, 0x22a2, 0x22a2, 0x22a2, 0xf003, 0x2a12, 0x2a12, 0x3a01, 0x30a1, 0x3932, 0x3392, 0x3852, 0x3582, 0xf003, 0x2922, 0x2922, 0x2292, 0x2292, 0x3672, 0x3901,
0x2912, 0x2912, 0xf003, 0x2192, 0x2192, 0x3091, 0x3842, 0x3482, 0x3572, 0x3832, 0x3382, 0xf003, 0x3662, 0x3822, 0x2282, 0x2282, 0x3742, 0x3472, 0x2812, 0x2812, 0xf003, 0x2182, 0x2182, 0x2081,
0x2081, 0x3801, 0x3652, 0x2732, 0x2732, 0xf003, 0x2372, 0x2372, 0x3562, 0x3642, 0x2722, 0x2722, 0x2272, 0x2272, 0xf003, 0x3462, 0x3552, 0x2701, 0x2701, 0x1712, 0x1712, 0x1712, 0x1712, 0xf002,
0x1172, 0x1172, 0x2071, 0x2632, 0xf002, 0x2362, 0x2542, 0x2452, 0x2622, 0xf001, 0x1262, 0x1612, 0xf002, 0x1162, 0x1162, 0x2601, 0x2061, 0xf002, 0x1352, 0x1352, 0x2532, 0x2442, 0xf001, 0x1522,
0x1252, 0xf001, 0x1512, 0x1501, 0xf001, 0x1432, 0x1342, 0xf001, 0x1051, 0x1422, 0xf001, 0x1242, 0x1332, 0xf001, 0x1401, 0x1041, 0xf004, 0x4ec2, 0x0086, 0x3ed2, 0x3ed2, 0x39e2, 0x39e2, 0x4ae2,
0x49d2, 0x2ee2, 0x2ee2, 0x2ee2, 0x2ee2, 0x3de2, 0x3de2, 0x3be2, 0x3be2, 0xf003, 0x2eb2, 0x2eb2, 0x2dc2, 0x2dc2, 0x3cd2, 0x3bd2, 0x2ea2, 0x2ea2, 0xf003, 0x2cc2, 0x2cc2, 0x3da2, 0x3ad2, 0x3e72,
0x3ca2, 0x2ac2, 0x2ac2, 0xf003, 0x39c2, 0x3d72, 0x2e52, 0x2e52, 0x1db2, 0x1db2, 0x1db2, 0x1db2, 0xf002, 0x1e92, 0x1e92, 0x2cb2, 0x2bc2, 0xf002, 0x2e82, 0x28e2, 0x2d92, 0x27e2, 0xf002, 0x2bb2,
0x2d82, 0x28d2, 0x2e62, 0xf001, 0x16e2, 0x1c92, 0xf002, 0x2ba2, 0x2ab2, 0x25e2, 0x27d2, 0xf002, 0x1e42, 0x1e42, 0x24e2, 0x2c82, 0xf001, 0x18c2, 0x1e32, 0xf002, 0x1d62, 0x1d62, 0x26d2, 0x2b92,
0xf002, 0x29b2, 0x2aa2, 0x11e2, 0x11e2, 0xf002, 0x14d2, 0x14d2, 0x28b2, 0x29a2, 0xf002, 0x1b72, 0x1b72, 0x27b2, 0x20d1, 0xf001, 0x1e01, 0x10e1, 0xf001, 0x1d52, 0x15d2, 0xf001, 0x1c72, 0x17c2,
0xf001, 0x1d42, 0x1b82, 0xf001, 0x1a92, 0x1c62, 0xf001, 0x16c2, 0x1d32, 0xf001, 0x1c52, 0x15c2, 0xf001, 0x1a82, 0x18a2, 0xf001, 0x1992, 0x1c42, 0xf001, 0x16b2, 0x1a72, 0xf001, 0x1b52, 0x1982,
0xf001, 0x1892, 0x1972, 0xf001, 0x1792, 0x1882, 0xf001, 0x1ce2, 0x1dd2, 0xf009, 0x8fe2, 0x8fe2, 0x8ef2, 0x8ef2, 0x8fd2, 0x8fd2, 0x8df2, 0x8df2, 0x8fc2, 0x8fc2, 0x8cf2, 0x8cf2, 0x8fb2, 0x8fb2,
0x8bf2, 0x8bf2, 0x7af2, 0x7af2, 0x7af2, 0x7af2, 0x8fa2, 0x8fa2, 0x8f92, 0x8f92, 0x79f2, 0x79f2, 0x79f2, 0x79f2, 0x78f2, 0x78f2, 0x78f2, 0x78f2, 0x8f82, 0x8f82, 0x8f72, 0x8f72, 0x77f2, 0x77f2,
0x77f2, 0x77f2, 0x7f62, 0x7f62, 0x7f62, 0x7f62, 0x76f2, 0x76f2, 0x76f2, 0x76f2, 0x7f52, 0x7f52, 0x7f52, 0x7f52, 0x75f2, 0x75f2, 0x75f2, 0x75f2, 0x7f42, 0x7f42, 0x7f42, 0x7f42, 0x74f2, 0x74f2,
0x74f2, 0x74f2, 0x7f32, 0x7f32, 0x7f32, 0x7f32, 0x73f2, 0x73f2, 0x73f2, 0x73f2, 0x7f22, 0x7f22, 0x7f22, 0x7f22, 0x72f2, 0x72f2, 0x72f2, 0x72f2, 0x71f2, 0x71f2, 0x71f2, 0x71f2, 0x8f12, 0x8f12,
0x80f1, 0x80f1, 0x9f01, 0x0201, 0x0206, 0x020b, 0x0210, 0x0215, 0x021a, 0x021f, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2,
0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x4ff2, 0x0224, 0x0229, 0x0232, 0x0237, 0x023a, 0x023f,
0x0242, 0x0245, 0x024a, 0x024d, 0x0250, 0x0253, 0x0256, 0x0259, 0x025c, 0x025f, 0x0262, 0x0265, 0x0268, 0x026b, 0x026e, 0x0271, 0x0274, 0x0277, 0x027a, 0x027d, 0x0280, 0x0283, 0x0288, 0x028b,
0x028e, 0x0291, 0x0294, 0x0297, 0x029a, 0x029f, 0x94b2, 0x02a4, 0x02a7, 0x02aa, 0x93b2, 0x9882, 0x02af, 0x92b2, 0x02b2, 0x02b5, 0x9692, 0x94a2, 0x02b8, 0x9782, 0x9a32, 0x93a2, 0x9952, 0x9592,
0x9a22, 0x92a2, 0x91a2, 0x9862, 0x9682, 0x9772, 0x9942, 0x9492, 0x9932, 0x9392, 0x9852, 0x9582, 0x9922, 0x9762, 0x9672, 0x9292, 0x9912, 0x9192, 0x9842, 0x9482, 0x9752, 0x9572, 0x9832, 0x9382,
0x9662, 0x9822, 0x9282, 0x9812, 0x9742, 0x9472, 0x9182, 0x02bb, 0x9652, 0x9562, 0x9712, 0x02be, 0x8372, 0x8372, 0x9732, 0x9722, 0x8272, 0x8272, 0x8642, 0x8642, 0x8462, 0x8462, 0x8552, 0x8552,
0x8172, 0x8172, 0x8632, 0x8632, 0x8362, 0x8362, 0x8542, 0x8542, 0x8452, 0x8452, 0x8622, 0x8622, 0x8262, 0x8262, 0x8612, 0x8612, 0x8162, 0x8162, 0x9601, 0x9061, 0x8532, 0x8532, 0x8352, 0x8352,
0x8442, 0x8442, 0x8522, 0x8522, 0x8252, 0x8252, 0x8512, 0x8512, 0x9501, 0x9051, 0x7152, 0x7152, 0x7152, 0x7152, 0x8432, 0x8432, 0x8342, 0x8342, 0x7422, 0x7422, 0x7422, 0x7422, 0x7242, 0x7242,
0x7242, 0x7242, 0x7332, 0x7332, 0x7332, 0x7332, 0x7412, 0x7412, 0x7412, 0x7412, 0x7142, 0x7142, 0x7142, 0x7142, 0x8401, 0x8401, 0x8041, 0x8041, 0x7322, 0x7322, 0x7322, 0x7322, 0x7232, 0x7232,
0x7232, 0x7232, 0x6312, 0x6312, 0x6312, 0x6312, 0x6312, 0x6312, 0x6312, 0x6312, 0x6132, 0x6132, 0x6132, 0x6132, 0x6132, 0x6132, 0x6132, 0x6132, 0x7301, 0x7301, 0x7301, 0x7301, 0x7031, 0x7031,
0x7031, 0x7031, 0x6222, 0x6222, 0x6222, 0x6222, 0x6222, 0x6222, 0x6222, 0x6222, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212, 0x5212,
0x5212, 0x5212, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x5122, 0x6201, 0x6201, 0x6201, 0x6201, 0x6201, 0x6201,
0x6201, 0x6201, 0x6021, 0x6021, 0x6021, 0x6021, 0x6021, 0x6021, 0x6021, 0x6021, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112,
0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4112, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101,
0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101, 0x4101,
0x4101, 0x4101, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011,
0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4011, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000,
0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0x4000, 0xf002, 0x2ee2, 0x2ed2, 0x2de2, 0x2ec2, 0xf002,
0x2ce2, 0x2dd2, 0x2eb2, 0x2be2, 0xf002, 0x2dc2, 0x2cd2, 0x2ea2, 0x2ae2, 0xf002, 0x2db2, 0x2bd2, 0x2cc2, 0x2e92, 0xf002, 0x29e2, 0x2da2, 0x2ad2, 0x2cb2, 0xf002, 0x2bc2, 0x2e82, 0x28e2, 0x2d92,
0xf002, 0x29d2, 0x2e72, 0x27e2, 0x2ca2, 0xf002, 0x2ac2, 0x2bb2, 0x2d82, 0x28d2, 0xf003, 0x3e01, 0x30e1, 0x2d01, 0x2d01, 0x16e2, 0x16e2, 0x16e2, 0x16e2, 0xf002, 0x2e62, 0x2c92, 0x19c2, 0x19c2,
0xf001, 0x1e52, 0x1ab2, 0xf002, 0x15e2, 0x15e2, 0x2ba2, 0x2d72, 0xf001, 0x17d2, 0x14e2, 0xf001, 0x1c82, 0x18c2, 0xf002, 0x2e42, 0x2e22, 0x1e32, 0x1e32, 0xf001, 0x1d62, 0x16d2, 0xf001, 0x13e2,
0x1b92, 0xf001, 0x19b2, 0x1aa2, 0xf001, 0x12e2, 0x1e12, 0xf001, 0x11e2, 0x1d52, 0xf001, 0x15d2, 0x1c72, 0xf001, 0x17c2, 0x1d42, 0xf001, 0x1b82, 0x18b2, 0xf001, 0x14d2, 0x1a92, 0xf001, 0x19a2,
0x1c62, 0xf001, 0x16c2, 0x1d32, 0xf001, 0x13d2, 0x1d22, 0xf001, 0x12d2, 0x1d12, 0xf001, 0x1b72, 0x17b2, 0xf001, 0x11d2, 0x1c52, 0xf001, 0x15c2, 0x1a82, 0xf001, 0x18a2, 0x1992, 0xf001, 0x1c42,
0x14c2, 0xf001, 0x1b62, 0x16b2, 0xf002, 0x20d1, 0x2c01, 0x1c32, 0x1c32, 0xf001, 0x13c2, 0x1a72, 0xf001, 0x17a2, 0x1c22, 0xf001, 0x12c2, 0x1b52, 0xf001, 0x15b2, 0x1c12, 0xf001, 0x1982, 0x1892,
0xf001, 0x11c2, 0x1b42, 0xf002, 0x20c1, 0x2b01, 0x1b32, 0x1b32, 0xf002, 0x20b1, 0x2a01, 0x1a12, 0x1a12, 0xf001, 0x1a62, 0x16a2, 0xf001, 0x1972, 0x1792, 0xf002, 0x20a1, 0x2901, 0x1091, 0x1091,
0xf001, 0x1b22, 0x1a52, 0xf001, 0x15a2, 0x1b12, 0xf001, 0x11b2, 0x1962, 0xf001, 0x1a42, 0x1872, 0xf001, 0x1801, 0x1081, 0xf001, 0x1701, 0x1071,
};
/* pow(2,-i/4) * pow(j,4/3) for i=0..3 j=0..15, Q25 format */
static const int32_t pow43_14[4][16] = {
{0x00000000, 0x10000000, 0x285145f3, 0x453a5cdb, 0x0cb2ff53, 0x111989d6, 0x15ce31c8, 0x1ac7f203, 0x20000000, 0x257106b9, 0x2b16b4a3, 0x30ed74b4, 0x36f23fa5, 0x3d227bd3, 0x437be656, 0x49fc823c},
{0x00000000, 0x0d744fcd, 0x21e71f26, 0x3a36abd9, 0x0aadc084, 0x0e610e6e, 0x12560c1d, 0x168523cf, 0x1ae89f99, 0x1f7c03a4, 0x243bae49, 0x29249c67, 0x2e34420f, 0x33686f85, 0x38bf3dff, 0x3e370182},
{0x00000000, 0x0b504f33, 0x1c823e07, 0x30f39a55, 0x08facd62, 0x0c176319, 0x0f6b3522, 0x12efe2ad, 0x16a09e66, 0x1a79a317, 0x1e77e301, 0x2298d5b4, 0x26da56fc, 0x2b3a902a, 0x2fb7e7e7, 0x3450f650},
{0x00000000, 0x09837f05, 0x17f910d7, 0x2929c7a9, 0x078d0dfa, 0x0a2ae661, 0x0cf73154, 0x0fec91cb, 0x1306fe0a, 0x16434a6c, 0x199ee595, 0x1d17ae3d, 0x20abd76a, 0x2459d551, 0x28204fbb, 0x2bfe1808},
};
/* pow(j,4/3) for j=16..63, Q23 format */
static const int32_t pow43[48] = {
0x1428a2fa, 0x15db1bd6, 0x1796302c, 0x19598d85, 0x1b24e8bb, 0x1cf7fcfa, 0x1ed28af2, 0x20b4582a, 0x229d2e6e, 0x248cdb55, 0x26832fda, 0x28800000, 0x2a832287, 0x2c8c70a8, 0x2e9bc5d8, 0x30b0ff99,
0x32cbfd4a, 0x34eca001, 0x3712ca62, 0x393e6088, 0x3b6f47e0, 0x3da56717, 0x3fe0a5fc, 0x4220ed72, 0x44662758, 0x46b03e7c, 0x48ff1e87, 0x4b52b3f3, 0x4daaebfd, 0x5007b497, 0x5268fc62, 0x54ceb29c,
0x5738c721, 0x59a72a59, 0x5c19cd35, 0x5e90a129, 0x610b9821, 0x638aa47f, 0x660db90f, 0x6894c90b, 0x6b1fc80c, 0x6daeaa0d, 0x70416360, 0x72d7e8b0, 0x75722ef9, 0x78102b85, 0x7ab1d3ec, 0x7d571e09,
};
static const uint32_t polyCoef[264] = {
/* shuffled vs. original from 0, 1, ... 15 to 0, 15, 2, 13, ... 14, 1 */
0x00000000, 0x00000074, 0x00000354, 0x0000072c, 0x00001fd4, 0x00005084, 0x000066b8, 0x000249c4, 0x00049478, 0xfffdb63c, 0x000066b8, 0xffffaf7c, 0x00001fd4, 0xfffff8d4, 0x00000354, 0xffffff8c,
0xfffffffc, 0x00000068, 0x00000368, 0x00000644, 0x00001f40, 0x00004ad0, 0x00005d1c, 0x00022ce0, 0x000493c0, 0xfffd9960, 0x00006f78, 0xffffa9cc, 0x0000203c, 0xfffff7e4, 0x00000340, 0xffffff84,
0xfffffffc, 0x00000060, 0x00000378, 0x0000056c, 0x00001e80, 0x00004524, 0x000052a0, 0x00020ffc, 0x000491a0, 0xfffd7ca0, 0x00007760, 0xffffa424, 0x00002080, 0xfffff6ec, 0x00000328, 0xffffff74,
0xfffffffc, 0x00000054, 0x00000384, 0x00000498, 0x00001d94, 0x00003f7c, 0x00004744, 0x0001f32c, 0x00048e18, 0xfffd6008, 0x00007e70, 0xffff9e8c, 0x0000209c, 0xfffff5ec, 0x00000310, 0xffffff68,
0xfffffffc, 0x0000004c, 0x0000038c, 0x000003d0, 0x00001c78, 0x000039e4, 0x00003b00, 0x0001d680, 0x00048924, 0xfffd43ac, 0x000084b0, 0xffff990c, 0x00002094, 0xfffff4e4, 0x000002f8, 0xffffff5c,
0xfffffffc, 0x00000044, 0x00000390, 0x00000314, 0x00001b2c, 0x0000345c, 0x00002ddc, 0x0001ba04, 0x000482d0, 0xfffd279c, 0x00008a20, 0xffff93a4, 0x0000206c, 0xfffff3d4, 0x000002dc, 0xffffff4c,
0xfffffffc, 0x00000040, 0x00000390, 0x00000264, 0x000019b0, 0x00002ef0, 0x00001fd4, 0x00019dc8, 0x00047b1c, 0xfffd0be8, 0x00008ecc, 0xffff8e64, 0x00002024, 0xfffff2c0, 0x000002c0, 0xffffff3c,
0xfffffff8, 0x00000038, 0x0000038c, 0x000001bc, 0x000017fc, 0x0000299c, 0x000010e8, 0x000181d8, 0x0004720c, 0xfffcf09c, 0x000092b4, 0xffff894c, 0x00001fc0, 0xfffff1a4, 0x000002a4, 0xffffff2c,
0xfffffff8, 0x00000034, 0x00000380, 0x00000120, 0x00001618, 0x00002468, 0x00000118, 0x00016644, 0x000467a4, 0xfffcd5cc, 0x000095e0, 0xffff8468, 0x00001f44, 0xfffff084, 0x00000284, 0xffffff18,
0xfffffff8, 0x0000002c, 0x00000374, 0x00000090, 0x00001400, 0x00001f58, 0xfffff068, 0x00014b14, 0x00045bf0, 0xfffcbb88, 0x00009858, 0xffff7fbc, 0x00001ea8, 0xffffef60, 0x00000268, 0xffffff04,
0xfffffff8, 0x00000028, 0x0000035c, 0x00000008, 0x000011ac, 0x00001a70, 0xffffded8, 0x00013058, 0x00044ef8, 0xfffca1d8, 0x00009a1c, 0xffff7b54, 0x00001dfc, 0xffffee3c, 0x0000024c, 0xfffffef0,
0xfffffff4, 0x00000024, 0x00000340, 0xffffff8c, 0x00000f28, 0x000015b0, 0xffffcc70, 0x0001161c, 0x000440bc, 0xfffc88d8, 0x00009b3c, 0xffff7734, 0x00001d38, 0xffffed18, 0x0000022c, 0xfffffedc,
0xfffffff4, 0x00000020, 0x00000320, 0xffffff1c, 0x00000c68, 0x0000111c, 0xffffb92c, 0x0000fc6c, 0x00043150, 0xfffc708c, 0x00009bb8, 0xffff7368, 0x00001c64, 0xffffebf4, 0x00000210, 0xfffffec4,
0xfffffff0, 0x0000001c, 0x000002f4, 0xfffffeb4, 0x00000974, 0x00000cb8, 0xffffa518, 0x0000e350, 0x000420b4, 0xfffc5908, 0x00009b9c, 0xffff6ff4, 0x00001b7c, 0xffffead0, 0x000001f4, 0xfffffeac,
0xfffffff0, 0x0000001c, 0x000002c4, 0xfffffe58, 0x00000648, 0x00000884, 0xffff9038, 0x0000cad0, 0x00040ef8, 0xfffc425c, 0x00009af0, 0xffff6ce0, 0x00001a88, 0xffffe9b0, 0x000001d4, 0xfffffe94,
0xffffffec, 0x00000018, 0x0000028c, 0xfffffe04, 0x000002e4, 0x00000480, 0xffff7a90, 0x0000b2fc, 0x0003fc28, 0xfffc2c90, 0x000099b8, 0xffff6a3c, 0x00001988, 0xffffe898, 0x000001bc, 0xfffffe7c,
0x000001a0, 0x0000187c, 0x000097fc, 0x0003e84c, 0xffff6424, 0xffffff4c, 0x00000248, 0xffffffec,
};
/* format = Q30, range = [0.0981, 1.9976]
*
* n = 16;
* k = 0;
* for(i=0; i<5; i++, n=n/2) {
* for(p=0; p<n; p++, k++) {
* t = (PI / (4*n)) * (2*p + 1);
* coef32[k] = 2.0 * cos(t);
* }
* }
* coef32[30] *= 0.5; / *** for initial back butterfly (i.e. two-point DCT) *** /
*/
static const int32_t coef32[31] = {
0x7fd8878d, 0x7e9d55fc, 0x7c29fbee, 0x78848413, 0x73b5ebd0, 0x6dca0d14, 0x66cf811f, 0x5ed77c89, 0x55f5a4d2, 0x4c3fdff3, 0x41ce1e64, 0x36ba2013, 0x2b1f34eb, 0x1f19f97b, 0x12c8106e, 0x0647d97c,
0x7f62368f, 0x7a7d055b, 0x70e2cbc6, 0x62f201ac, 0x5133cc94, 0x3c56ba70, 0x25280c5d, 0x0c8bd35e, 0x7d8a5f3f, 0x6a6d98a4, 0x471cece6, 0x18f8b83c, 0x7641af3c, 0x30fbc54d, 0x2d413ccc,
};
/* let c(j) = cos(M_PI/36 * ((j)+0.5)), s(j) = sin(M_PI/36 * ((j)+0.5))
* then fastWin[2*j+0] = c(j)*(s(j) + c(j)), j = [0, 8]
* fastWin[2*j+1] = c(j)*(s(j) - c(j))
* format = Q30
*/
static const uint32_t fastWin36[18] = {0x42aace8b, 0xc2e92724, 0x47311c28, 0xc95f619a, 0x4a868feb, 0xd0859d8c, 0x4c913b51, 0xd8243ea0, 0x4d413ccc,
0xe0000000, 0x4c913b51, 0xe7dbc161, 0x4a868feb, 0xef7a6275, 0x47311c28, 0xf6a09e67, 0x42aace8b, 0xfd16d8dd};
/* tables for quadruples
* format 0xAB
* A = length of codeword
* B = codeword
*/
static const uint8_t quadTable[64 + 16] = {
/* table A */
0x6b, 0x6f, 0x6d, 0x6e, 0x67, 0x65, 0x59, 0x59, 0x56, 0x56, 0x53, 0x53, 0x5a, 0x5a, 0x5c, 0x5c, 0x42, 0x42, 0x42, 0x42, 0x41, 0x41, 0x41, 0x41, 0x44, 0x44, 0x44,
0x44, 0x48, 0x48, 0x48, 0x48, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40};
/* indexing = [version][layer][bitrate index]
* bitrate (kbps) of frame
* - bitrate index == 0 is "free" mode (bitrate determined on the fly by
* counting bits between successive sync words)
*/
static const int16_t bitrateTab[3][3][15] = {
{
/* MPEG-1 */
{0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448}, /* Layer 1 */
{0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384}, /* Layer 2 */
{0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320}, /* Layer 3 */
},
{
/* MPEG-2 */
{0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256}, /* Layer 1 */
{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}, /* Layer 2 */
{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}, /* Layer 3 */
},
{
/* MPEG-2.5 */
{0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256}, /* Layer 1 */
{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}, /* Layer 2 */
{0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}, /* Layer 3 */
},
};
/* indexing = [version][sampleRate][bitRate]
* for layer3, nSlots = floor(samps/frame * bitRate / sampleRate / 8)
* - add one pad slot if necessary
*/
static const int16_t slotTab[3][3][15] = {
{
/* MPEG-1 */
{0, 104, 130, 156, 182, 208, 261, 313, 365, 417, 522, 626, 731, 835, 1044}, /* 44 kHz */
{0, 96, 120, 144, 168, 192, 240, 288, 336, 384, 480, 576, 672, 768, 960}, /* 48 kHz */
{0, 144, 180, 216, 252, 288, 360, 432, 504, 576, 720, 864, 1008, 1152, 1440}, /* 32 kHz */
},
{
/* MPEG-2 */
{0, 26, 52, 78, 104, 130, 156, 182, 208, 261, 313, 365, 417, 470, 522}, /* 22 kHz */
{0, 24, 48, 72, 96, 120, 144, 168, 192, 240, 288, 336, 384, 432, 480}, /* 24 kHz */
{0, 36, 72, 108, 144, 180, 216, 252, 288, 360, 432, 504, 576, 648, 720}, /* 16 kHz */
},
{
/* MPEG-2.5 */
{0, 52, 104, 156, 208, 261, 313, 365, 417, 522, 626, 731, 835, 940, 1044}, /* 11 kHz */
{0, 48, 96, 144, 192, 240, 288, 336, 384, 480, 576, 672, 768, 864, 960}, /* 12 kHz */
{0, 72, 144, 216, 288, 360, 432, 504, 576, 720, 864, 1008, 1152, 1296, 1440}, /* 8 kHz */
},
};
static const uint32_t imdctWin[4][36] = {
{0x02aace8b, 0x07311c28, 0x0a868fec, 0x0c913b52, 0x0d413ccd, 0x0c913b52, 0x0a868fec, 0x07311c28, 0x02aace8b, 0xfd16d8dd, 0xf6a09e66, 0xef7a6275,
0xe7dbc161, 0xe0000000, 0xd8243e9f, 0xd0859d8b, 0xc95f619a, 0xc2e92723, 0xbd553175, 0xb8cee3d8, 0xb5797014, 0xb36ec4ae, 0xb2bec333, 0xb36ec4ae,
0xb5797014, 0xb8cee3d8, 0xbd553175, 0xc2e92723, 0xc95f619a, 0xd0859d8b, 0xd8243e9f, 0xe0000000, 0xe7dbc161, 0xef7a6275, 0xf6a09e66, 0xfd16d8dd},
{0x02aace8b, 0x07311c28, 0x0a868fec, 0x0c913b52, 0x0d413ccd, 0x0c913b52, 0x0a868fec, 0x07311c28, 0x02aace8b, 0xfd16d8dd, 0xf6a09e66, 0xef7a6275,
0xe7dbc161, 0xe0000000, 0xd8243e9f, 0xd0859d8b, 0xc95f619a, 0xc2e92723, 0xbd44ef14, 0xb831a052, 0xb3aa3837, 0xafb789a4, 0xac6145bb, 0xa9adecdc,
0xa864491f, 0xad1868f0, 0xb8431f49, 0xc8f42236, 0xdda8e6b1, 0xf47755dc, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000},
{0x07311c28, 0x0d413ccd, 0x07311c28, 0xf6a09e66, 0xe0000000, 0xc95f619a, 0xb8cee3d8, 0xb2bec333, 0xb8cee3d8, 0xc95f619a, 0xe0000000, 0xf6a09e66,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000},
{0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x028e9709, 0x04855ec0, 0x026743a1, 0xfcde2c10, 0xf515dc82, 0xec93e53b,
0xe4c880f8, 0xdd5d0b08, 0xd63510b7, 0xcf5e834a, 0xc8e6b562, 0xc2da4105, 0xbd553175, 0xb8cee3d8, 0xb5797014, 0xb36ec4ae, 0xb2bec333, 0xb36ec4ae,
0xb5797014, 0xb8cee3d8, 0xbd553175, 0xc2e92723, 0xc95f619a, 0xd0859d8b, 0xd8243e9f, 0xe0000000, 0xe7dbc161, 0xef7a6275, 0xf6a09e66, 0xfd16d8dd},
};
static const int32_t ISFMpeg1[2][7] = {{0x00000000, 0x0d8658ba, 0x176cf5d0, 0x20000000, 0x28930a2f, 0x3279a745, 0x40000000},
{0x00000000, 0x13207f5c, 0x2120fb83, 0x2d413ccc, 0x39617e16, 0x4761fa3d, 0x5a827999}};
static const int32_t ISFMpeg2[2][2][16] = {
{
{/* intensityScale off, mid-side off */
0x40000000, 0x35d13f32, 0x2d413ccc, 0x260dfc14, 0x1fffffff, 0x1ae89f99, 0x16a09e66, 0x1306fe0a, 0x0fffffff, 0x0d744fcc, 0x0b504f33, 0x09837f05, 0x07ffffff, 0x06ba27e6, 0x05a82799,
0x04c1bf82},
{/* intensityScale off, mid-side on */
0x5a827999, 0x4c1bf827, 0x3fffffff, 0x35d13f32, 0x2d413ccc, 0x260dfc13, 0x1fffffff, 0x1ae89f99, 0x16a09e66, 0x1306fe09, 0x0fffffff, 0x0d744fcc, 0x0b504f33, 0x09837f04, 0x07ffffff,
0x06ba27e6},
},
{{/* intensityScale on, mid-side off */
0x40000000, 0x2d413ccc, 0x20000000, 0x16a09e66, 0x10000000, 0x0b504f33, 0x08000000, 0x05a82799, 0x04000000, 0x02d413cc, 0x02000000, 0x016a09e6, 0x01000000, 0x00b504f3, 0x00800000, 0x005a8279},
{/* intensityScale on, mid-side on */
0x5a827999, 0x3fffffff, 0x2d413ccc, 0x1fffffff, 0x16a09e66, 0x0fffffff, 0x0b504f33, 0x07ffffff, 0x05a82799, 0x03ffffff, 0x02d413cc, 0x01ffffff, 0x016a09e6, 0x00ffffff, 0x00b504f3, 0x007fffff}}};
static const uint32_t m_COS0_0 = 0x4013c251; /* Q31 */
static const uint32_t m_COS0_1 = 0x40b345bd; /* Q31 */
static const uint32_t m_COS0_2 = 0x41fa2d6d; /* Q31 */
static const uint32_t m_COS0_3 = 0x43f93421; /* Q31 */
static const uint32_t m_COS0_4 = 0x46cc1bc4; /* Q31 */
static const uint32_t m_COS0_5 = 0x4a9d9cf0; /* Q31 */
static const uint32_t m_COS0_6 = 0x4fae3711; /* Q31 */
static const uint32_t m_COS0_7 = 0x56601ea7; /* Q31 */
static const uint32_t m_COS0_8 = 0x5f4cf6eb; /* Q31 */
static const uint32_t m_COS0_9 = 0x6b6fcf26; /* Q31 */
static const uint32_t m_COS0_10 = 0x7c7d1db3; /* Q31 */
static const uint32_t m_COS0_11 = 0x4ad81a97; /* Q30 */
static const uint32_t m_COS0_12 = 0x5efc8d96; /* Q30 */
static const uint32_t m_COS0_13 = 0x41d95790; /* Q29 */
static const uint32_t m_COS0_14 = 0x6d0b20cf; /* Q29 */
static const uint32_t m_COS0_15 = 0x518522fb; /* Q27 */
static const uint32_t m_COS1_0 = 0x404f4672; /* Q31 */
static const uint32_t m_COS1_1 = 0x42e13c10; /* Q31 */
static const uint32_t m_COS1_2 = 0x48919f44; /* Q31 */
static const uint32_t m_COS1_3 = 0x52cb0e63; /* Q31 */
static const uint32_t m_COS1_4 = 0x64e2402e; /* Q31 */
static const uint32_t m_COS1_5 = 0x43e224a9; /* Q30 */
static const uint32_t m_COS1_6 = 0x6e3c92c1; /* Q30 */
static const uint32_t m_COS1_7 = 0x519e4e04; /* Q28 */
static const uint32_t m_COS2_0 = 0x4140fb46; /* Q31 */
static const uint32_t m_COS2_1 = 0x4cf8de88; /* Q31 */
static const uint32_t m_COS2_2 = 0x73326bbf; /* Q31 */
static const uint32_t m_COS2_3 = 0x52036742; /* Q29 */
static const uint32_t m_COS3_0 = 0x4545e9ef; /* Q31 */
static const uint32_t m_COS3_1 = 0x539eba45; /* Q30 */
static const uint32_t m_COS4_0 = 0x5a82799a; /* Q31 */
static const uint32_t m_dcttab[48] = {
// faster in ROM
/* first pass */
m_COS0_0, m_COS0_15, m_COS1_0, /* 31, 27, 31 */
m_COS0_1, m_COS0_14, m_COS1_1, /* 31, 29, 31 */
m_COS0_2, m_COS0_13, m_COS1_2, /* 31, 29, 31 */
m_COS0_3, m_COS0_12, m_COS1_3, /* 31, 30, 31 */
m_COS0_4, m_COS0_11, m_COS1_4, /* 31, 30, 31 */
m_COS0_5, m_COS0_10, m_COS1_5, /* 31, 31, 30 */
m_COS0_6, m_COS0_9, m_COS1_6, /* 31, 31, 30 */
m_COS0_7, m_COS0_8, m_COS1_7, /* 31, 31, 28 */
/* second pass */
m_COS2_0, m_COS2_3, m_COS3_0, /* 31, 29, 31 */
m_COS2_1, m_COS2_2, m_COS3_1, /* 31, 31, 30 */
-m_COS2_0, -m_COS2_3, m_COS3_0, /* 31, 29, 31 */
-m_COS2_1, -m_COS2_2, m_COS3_1, /* 31, 31, 30 */
m_COS2_0, m_COS2_3, m_COS3_0, /* 31, 29, 31 */
m_COS2_1, m_COS2_2, m_COS3_1, /* 31, 31, 30 */
-m_COS2_0, -m_COS2_3, m_COS3_0, /* 31, 29, 31 */
-m_COS2_1, -m_COS2_2, m_COS3_1, /* 31, 31, 30 */
};
static const uint16_t mpeg1_layer3_bitrates[16] = { // Bitraten-Lookup tables (example for MPEG1 Layer III)
0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0 // Attention: These tables must be complete and correct!
}; // Index 0 is invalid, index 15 is invalid.
// SamplingFrequenz-Lookup tables(Beispiel für MPEG1, MPEG2, MPEG2.5)
static const uint16_t sampling_rates[3][4] = {
{44100, 48000, 32000, 0}, // MPEG1
{22050, 24000, 16000, 0}, // MPEG2
{11025, 12000, 8000, 0} // MPEG2.5
};
static const int32_t c9_0 = 0x6ed9eba1;
static const int32_t c9_1 = 0x620dbe8b;
static const int32_t c9_2 = 0x163a1a7e;
static const int32_t c9_3 = 0x5246dd49;
static const int32_t c9_4 = 0x7e0e2e32;
static const int32_t c3_0 = 0x6ed9eba1; /* format = Q31, cos(pi/6) */
static const int32_t c6[3] = { 0x7ba3751d, 0x5a82799a, 0x2120fb83 }; /* format = Q31, cos(((0:2) + 0.5) * (pi/6)) */
/* format = Q31
* cos(((0:8) + 0.5) * (pi/18))
*/
static const uint32_t c18[9] = { 0x7f834ed0, 0x7ba3751d, 0x7401e4c1, 0x68d9f964, 0x5a82799a, 0x496af3e2, 0x36185aee, 0x2120fb83, 0x0b27eb5c};
/* scale factor lengths (num bits) */
static const char m_SFLenTab[16][2] = { {0, 0}, {0, 1}, {0, 2}, {0, 3}, {3, 0}, {1, 1}, {1, 2}, {1, 3},
{2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}, {4, 2}, {4, 3}};
/* NRTab[size + 3*is_right][block type][partition]
* block type index: 0 = (bt0,bt1,bt3), 1 = bt2 non-mixed, 2 = bt2 mixed
* partition: scale factor groups (sfb1 through sfb4)
* for block type = 2 (mixed or non-mixed) / by 3 is rolled into this table
* (for 3 short blocks per long block)
* see 2.4.3.2 in MPEG 2 (low sample rate) spec
* stuff rolled into this table:
* NRTab[x][1][y] --> (NRTab[x][1][y]) / 3
* NRTab[x][2][>=1] --> (NRTab[x][2][>=1]) / 3 (first partition is long block)
*/
static const char NRTab[6][3][4] = {
{{ 6, 5, 5, 5}, {3, 3, 3, 3}, {6, 3, 3, 3}},
{{ 6, 5, 7, 3}, {3, 3, 4, 2}, {6, 3, 4, 2}},
{{11, 10, 0, 0}, {6, 6, 0, 0}, {6, 3, 6, 0}},
{{ 7, 7, 7, 0}, {4, 4, 4, 0}, {6, 5, 4, 0}},
{{ 6, 6, 6, 3}, {4, 3, 3, 2}, {6, 4, 3, 2}},
{{ 8, 8, 5, 0}, {5, 4, 3, 0}, {6, 6, 3, 0}}
};
/* optional pre-emphasis for high-frequency scale factor bands */
static const char preTab[22] = { 0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,3,3,3,2,0 };
/* pow(2,-i/4) for i=0..3, Q31 format */
static const int32_t pow14[4] = {
0x7fffffff, 0x6ba27e65, 0x5a82799a, 0x4c1bf829
};
/*
* Minimax polynomial approximation to pow(x, 4/3), over the range
* poly43lo: x = [0.5, 0.7071]
* poly43hi: x = [0.7071, 1.0]
*
* Relative error < 1E-7
* Coefs are scaled by 4, 2, 1, 0.5, 0.25
*/
static const uint32_t poly43lo[5] = { 0x29a0bda9, 0xb02e4828, 0x5957aa1b, 0x236c498d, 0xff581859 };
static const uint32_t poly43hi[5] = { 0x10852163, 0xd333f6a4, 0x46e9408b, 0x27c2cef0, 0xfef577b4 };
/* pow(2, i*4/3) as exp and frac */
static const int32_t pow2exp[8] = { 14, 13, 11, 10, 9, 7, 6, 5 };
static const int32_t pow2frac[8] = {
0x6597fa94, 0x50a28be6, 0x7fffffff, 0x6597fa94,
0x50a28be6, 0x7fffffff, 0x6597fa94, 0x50a28be6
};
static const uint16_t m_HUFF_OFFSET_01= 0;
static const uint16_t m_HUFF_OFFSET_02= 9 + m_HUFF_OFFSET_01;
static const uint16_t m_HUFF_OFFSET_03= 65 + m_HUFF_OFFSET_02;
static const uint16_t m_HUFF_OFFSET_05= 65 + m_HUFF_OFFSET_03;
static const uint16_t m_HUFF_OFFSET_06=257 + m_HUFF_OFFSET_05;
static const uint16_t m_HUFF_OFFSET_07=129 + m_HUFF_OFFSET_06;
static const uint16_t m_HUFF_OFFSET_08=110 + m_HUFF_OFFSET_07;
static const uint16_t m_HUFF_OFFSET_09=280 + m_HUFF_OFFSET_08;
static const uint16_t m_HUFF_OFFSET_10= 93 + m_HUFF_OFFSET_09;
static const uint16_t m_HUFF_OFFSET_11=320 + m_HUFF_OFFSET_10;
static const uint16_t m_HUFF_OFFSET_12=296 + m_HUFF_OFFSET_11;
static const uint16_t m_HUFF_OFFSET_13=185 + m_HUFF_OFFSET_12;
static const uint16_t m_HUFF_OFFSET_15=497 + m_HUFF_OFFSET_13;
static const uint16_t m_HUFF_OFFSET_16=580 + m_HUFF_OFFSET_15;
static const uint16_t m_HUFF_OFFSET_24=651 + m_HUFF_OFFSET_16;
static const int32_t huffTabOffset[HUFF_PAIRTABS] = {
0, m_HUFF_OFFSET_01, m_HUFF_OFFSET_02, m_HUFF_OFFSET_03,
0, m_HUFF_OFFSET_05, m_HUFF_OFFSET_06, m_HUFF_OFFSET_07,
m_HUFF_OFFSET_08, m_HUFF_OFFSET_09, m_HUFF_OFFSET_10, m_HUFF_OFFSET_11,
m_HUFF_OFFSET_12, m_HUFF_OFFSET_13, 0, m_HUFF_OFFSET_15,
m_HUFF_OFFSET_16, m_HUFF_OFFSET_16, m_HUFF_OFFSET_16, m_HUFF_OFFSET_16,
m_HUFF_OFFSET_16, m_HUFF_OFFSET_16, m_HUFF_OFFSET_16, m_HUFF_OFFSET_16,
m_HUFF_OFFSET_24, m_HUFF_OFFSET_24, m_HUFF_OFFSET_24, m_HUFF_OFFSET_24,
m_HUFF_OFFSET_24, m_HUFF_OFFSET_24, m_HUFF_OFFSET_24, m_HUFF_OFFSET_24,};
static const HuffTabLookup_t huffTabLookup[HUFF_PAIRTABS] = {
{ 0, noBits },
{ 0, oneShot },
{ 0, oneShot },
{ 0, oneShot },
{ 0, invalidTab },
{ 0, oneShot },
{ 0, oneShot },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, loopNoLinbits },
{ 0, invalidTab },
{ 0, loopNoLinbits },
{ 1, loopLinbits },
{ 2, loopLinbits },
{ 3, loopLinbits },
{ 4, loopLinbits },
{ 6, loopLinbits },
{ 8, loopLinbits },
{ 10, loopLinbits },
{ 13, loopLinbits },
{ 4, loopLinbits },
{ 5, loopLinbits },
{ 6, loopLinbits },
{ 7, loopLinbits },
{ 8, loopLinbits },
{ 9, loopLinbits },
{ 11, loopLinbits },
{ 13, loopLinbits }
};
static const int32_t quadTabOffset[2] = {0, 64};
static const int32_t quadTabMaxBits[2] = {6, 4};
/* indexing = [version][samplerate index]
* sample rate of frame (Hz)
*/
static const int32_t samplerateTab[3][3] = {
{ 44100, 48000, 32000 }, /* MPEG-1 */
{ 22050, 24000, 16000 }, /* MPEG-2 */
{ 11025, 12000, 8000 }, /* MPEG-2.5 */
};
/* indexing = [version][layer]
* number of samples in one frame (per channel)
*/
static const uint16_t samplesPerFrameTab[3][3] = { { 384, 1152, 1152 }, /* MPEG1 */
{ 384, 1152, 576 }, /* MPEG2 */
{ 384, 1152, 576 }, /* MPEG2.5 */
};
/* layers 1, 2, 3 */
static const uint8_t bitsPerSlotTab[3] = { 32, 8, 8 };
/* indexing = [version][mono/stereo]
* number of bytes in side info section of bitstream
*/
static const uint8_t sideBytesTab[3][2] = { { 17, 32 }, /* MPEG-1: mono, stereo */
{ 9, 17 }, /* MPEG-2: mono, stereo */
{ 9, 17 }, /* MPEG-2.5: mono, stereo */
};
/* indexing = [version][sampleRate][long (.l) or short (.s) block]
* sfBandTable[v][s].l[cb] = index of first bin in critical band cb (long blocks)
* sfBandTable[v][s].s[cb] = index of first bin in critical band cb (short blocks)
*/
static const SFBandTable_t sfBandTable[3][3] = {
{ /* MPEG-1 (44, 48, 32 kHz) */
{ {0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418, 576 },
{0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192} },
{ {0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384, 576 },
{0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192} },
{ {0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550, 576 },
{0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192} } },
{ /* MPEG-2 (22, 24, 16 kHz) */
{ {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 },
{0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192} },
{ {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464, 540, 576 },
{0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192} },
{ {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 },
{0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192} }, },
{ /* MPEG-2.5 (11, 12, 8 kHz) */
{ {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 },
{0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 } },
{ {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464, 522, 576 },
{0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192 } },
{ {0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570, 572, 574, 576 },
{0, 8, 16, 24, 36, 52, 72, 96, 124, 160, 162, 164, 166, 192 } }, },
};
/* indexing = [intensity scale on/off][left/right]
* format = Q30, range = [0.0, 1.414]
*
* illegal intensity position scalefactors (see comments on ISFMpeg1)
*/
static const int32_t ISFIIP[2][2] = {
{0x40000000, 0x00000000}, /* mid-side off */
{0x40000000, 0x40000000}, /* mid-side on */
};
static const uint8_t uniqueIDTab[8] = {0x5f, 0x4b, 0x43, 0x5f, 0x5f, 0x4a, 0x52, 0x5f};
/* anti-alias coefficients - see spec Annex B, table 3-B.9
* csa[0][i] = CSi, csa[1][i] = CAi
* format = Q31
*/
static const uint32_t csa[8][2] = {
{0x6dc253f0, 0xbe2500aa},
{0x70dcebe4, 0xc39e4949},
{0x798d6e73, 0xd7e33f4a},
{0x7ddd40a7, 0xe8b71176},
{0x7f6d20b7, 0xf3e4fe2f},
{0x7fe47e40, 0xfac1a3c7},
{0x7ffcb263, 0xfe2ebdc6},
{0x7fffc694, 0xff86c25d},
};
/* format = Q30, right shifted by 12 (sign bits only in top 12 - undo this when rounding to short)
* this is to enable early-terminating multiplies on ARM
* range = [-1.144287109, 1.144989014]
* max gain of filter (per output sample) ~= 2.731
*
* new (properly sign-flipped) values
* - these actually are correct to 32 bits, (floating-pt coefficients in spec
* chosen such that only ~20 bits are required)
*
* Reordering - see table 3-B.3 in spec (appendix B)
*
* polyCoef[i] =
* D[ 0, 32, 64, ... 480], i = [ 0, 15]
* D[ 1, 33, 65, ... 481], i = [ 16, 31]
* D[ 2, 34, 66, ... 482], i = [ 32, 47]
* ...
* D[15, 47, 79, ... 495], i = [240,255]
*
* also exploits symmetry: D[i] = -D[512 - i], for i = [1, 255]
*
* polyCoef[256, 257, ... 263] are for special case of sample 16 (out of 0)
* see PolyphaseStereo() and PolyphaseMono()
*/
static const char* mpeg_version_table[] = {
"MPEG-1", // 0
"MPEG-2", // 1
"MPEG-2.5", // 2
"MPEG-INVALID" // 3
};
static const char* layer_table[] = {
"Unknown", // 0
"Layer I", // 1
"Layer II", // 2
"Layer III" // 3
};
static const uint8_t FDCT32s1s2[16] = {5, 3, 3, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 4};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,230 @@
/* Copyright (c) 2007-2008 CSIRO
Copyright (c) 2007-2009 Xiph.Org Foundation
Copyright (c) 2008 Gregory Maxwell
Written by Jean-Marc Valin and Gregory Maxwell */
/**
@file celt.h
@brief Contains all the functions for encoding and decoding audio
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "../psram_unique_ptr.hpp"
#include "Arduino.h"
#include "celt_defines.h"
#include "celt_structs.h"
#include "celt_tables.h"
#include "range_decoder.h"
extern const int16_t eband5ms[22];
extern const uint8_t band_allocation[231];
extern const uint32_t CELT_PVQ_U_DATA[];
extern const int16_t mdct_twiddles960[];
extern const int16_t window120[];
extern const int16_t logN400[];
extern const int16_t cache_index50[];
extern const uint8_t cache_bits50[];
extern const uint8_t cache_caps50[];
extern const kiss_twiddle_cpx fft_twiddles48000_960[];
extern const int16_t fft_bitrev480[];
extern const int16_t fft_bitrev240[];
extern const int16_t fft_bitrev12[];
extern const int16_t fft_bitrev60[];
extern const uint8_t LOG2_FRAC_TABLE[];
extern const uint8_t e_prob_mode[];
extern const uint8_t small_energy_icdf[];
extern const int8_t tf_select_table[4][8];
extern const int32_t ordery_table[];
extern const int32_t second_check[];
extern const uint8_t trim_icd[];
extern const uint8_t spread_icd[];
extern const uint8_t tapset_icdf[];
extern const uint32_t row_idx[];
class CeltDecoder {
public:
CeltDecoder(RangeDecoder& rangeDecoder) : rd(rangeDecoder) {}
~CeltDecoder() { reset(); }
bool init();
void clear();
void reset();
int32_t celt_decoder_init(int32_t channels);
int32_t celt_decoder_ctl(int32_t request, ...);
int32_t celt_decode_with_ec(int16_t* pcm, int32_t frame_size);
int16_t SAT16(int32_t x);
private:
RangeDecoder& rd; // Referenz auf RangeDecoder
const kiss_fft_state fft_state48000_960_0 = {
480, /* nfft */
17476, /* scale */
8, /* scale_shift */
-1, /* shift */
{5, 96, 3, 32, 4, 8, 2, 4, 4, 1, 0, 0, 0, 0, 0, 0}, /* factors */
fft_bitrev480, /* bitrev */
fft_twiddles48000_960, /* bitrev */
};
const kiss_fft_state fft_state48000_960_1 = {
240, /* nfft */
17476, /* scale */
7, /* scale_shift */
1, /* shift */
{5, 48, 3, 16, 4, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0}, /* factors */
fft_bitrev240, /* bitrev */
fft_twiddles48000_960, /* bitrev */
};
const kiss_fft_state fft_state48000_960_2 = {
120, /* nfft */
17476, /* scale */
6, /* scale_shift */
2, /* shift */
{5, 24, 3, 8, 2, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0}, /* factors */
fft_bitrev120, /* bitrev */
fft_twiddles48000_960, /* bitrev */
};
const kiss_fft_state fft_state48000_960_3 = {
60, /* nfft */
17476, /* scale */
5, /* scale_shift */
3, /* shift */
{5, 12, 3, 4, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, /* factors */
fft_bitrev60, /* bitrev */
fft_twiddles48000_960, /* bitrev */
};
const CELTMode_t m_CELTMode = {
48000, /* Fs */
120, /* overlap */
21, /* nbEBands */
21, /* effEBands */
{27853, 0, 4096, 8192}, /* preemph */
3, /* maxLM */
8, /* nbShortMdcts */
120, /* shortMdctSize */
11, /* nbAllocVectors */
};
const mdct_lookup_t m_mdct_lookup = {
1920,
3,
{
&fft_state48000_960_0,
&fft_state48000_960_1,
&fft_state48000_960_2,
&fft_state48000_960_3,
},
mdct_twiddles960, /* mdct */
};
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
CELTDecoder_t m_celtDec; // unique pointer
ps_ptr<int32_t> m_decode_mem;
band_ctx_t m_band_ctx;
// ——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
int32_t celt_inner_prod_c(const int16_t* x, const int16_t* y, int32_t N);
int32_t celt_rcp(int32_t x);
uint32_t celt_pvq_u_row(uint32_t row, uint32_t data);
void exp_rotation1(int16_t* X, int32_t len, int32_t stride, int16_t c, int16_t s);
void exp_rotation(int16_t* X, int32_t len, int32_t dir, int32_t stride, int32_t K, int32_t spread);
void normalise_residual(int32_t* iy, int16_t* X, int32_t N, int32_t Ryy, int16_t gain);
uint32_t extract_collapse_mask(int32_t* iy, int32_t N, int32_t B);
uint32_t alg_unquant(int16_t* X, int32_t N, int32_t K, int32_t spread, int32_t B, int16_t gain);
void renormalise_vector(int16_t* X, int32_t N, int16_t gain);
int32_t resampling_factor(int32_t rate);
void comb_filter_const_c(int32_t* y, int32_t* x, int32_t T, int32_t N, int16_t g10, int16_t g11, int16_t g12);
void comb_filter(int32_t* y, int32_t* x, int32_t T0, int32_t T1, int32_t N, int16_t g0, int16_t g1, int32_t tapset0, int32_t tapset1);
void init_caps(int32_t* cap, int32_t LM, int32_t C);
uint32_t celt_lcg_rand(uint32_t seed);
int16_t bitexact_cos(int16_t x);
int32_t bitexact_log2tan(int32_t isin, int32_t icos);
void denormalise_bands(const int16_t* X, int32_t* freq, const int16_t* bandLogE, int32_t start, int32_t end, int32_t M, int32_t downsample, int32_t silence);
void anti_collapse(int16_t* X_, uint8_t* collapse_masks, int32_t LM, int32_t C, int32_t size, int32_t start, int32_t end, const int16_t* logE, const int16_t* prev1logE, const int16_t* prev2logE,
const int32_t* pulses, uint32_t seed);
void compute_channel_weights(int32_t Ex, int32_t Ey, int16_t w[2]);
void stereo_split(int16_t* X, int16_t* Y, int32_t N);
void stereo_merge(int16_t* X, int16_t* Y, int16_t mid, int32_t N);
void deinterleave_hadamard(int16_t* X, int32_t N0, int32_t stride, int32_t hadamard);
void interleave_hadamard(int16_t* X, int32_t N0, int32_t stride, int32_t hadamard);
void haar1(int16_t* X, int32_t N0, int32_t stride);
int32_t compute_qn(int32_t N, int32_t b, int32_t offset, int32_t pulse_cap, int32_t stereo);
void compute_theta(struct split_ctx* sctx, int16_t* X, int16_t* Y, int32_t N, int32_t* b, int32_t B, int32_t __B0, int32_t LM, int32_t stereo, int32_t* fill);
uint32_t quant_band_n1(int16_t* X, int16_t* Y, int32_t b, int16_t* lowband_out);
uint32_t quant_partition(int16_t* X, int32_t N, int32_t b, int32_t B, int16_t* lowband, int32_t LM, int16_t gain, int32_t fill);
uint32_t quant_band(int16_t* X, int32_t N, int32_t b, int32_t B, int16_t* lowband, int32_t LM, int16_t* lowband_out, int16_t gain, int16_t* lowband_scratch, int32_t fill);
uint32_t quant_band_stereo(int16_t* X, int16_t* Y, int32_t N, int32_t b, int32_t B, int16_t* lowband, int32_t LM, int16_t* lowband_out, int16_t* lowband_scratch, int32_t fill);
void special_hybrid_folding(int16_t* norm, int16_t* norm2, int32_t start, int32_t M, int32_t dual_stereo);
void quant_all_bands(int32_t start, int32_t end, int16_t* X_, int16_t* Y_, uint8_t* collapse_masks, const int32_t* bandE, int32_t* pulses, int32_t shortBlocks, int32_t spread, int32_t dual_stereo,
int32_t intensity, int32_t* tf_res, int32_t total_bits, int32_t balance, int32_t LM, int32_t codedBands, uint32_t* seed, int32_t complexity, int32_t disable_inv);
int32_t celt_decoder_get_size(int32_t channels);
void deemphasis_stereo_simple(int32_t* in[], int16_t* pcm, int32_t N, const int16_t coef0, int32_t* mem);
void deemphasis(int32_t* in[], int16_t* pcm, int32_t N, int32_t C, int32_t downsample, const int16_t* coef, int32_t* mem, int32_t accum);
void celt_synthesis(int16_t* X, int32_t* out_syn[], int16_t* oldBandE, int32_t start, int32_t effEnd, int32_t C, int32_t CC, int32_t isTransient, int32_t LM, int32_t downsample, int32_t silence);
void tf_decode(int32_t start, int32_t end, int32_t isTransient, int32_t* tf_res, int32_t LM);
int32_t cwrsi(int32_t _n, int32_t _k, uint32_t _i, int32_t* _y);
int32_t decode_pulses(int32_t* _y, int32_t _n, int32_t _k);
void kf_bfly2(kiss_fft_cpx* Fout, int32_t m, int32_t N);
void kf_bfly4(kiss_fft_cpx* Fout, const size_t fstride, const kiss_fft_state* st, int32_t m, int32_t N, int32_t mm);
void kf_bfly3(kiss_fft_cpx* Fout, const size_t fstride, const kiss_fft_state* st, int32_t m, int32_t N, int32_t mm);
void kf_bfly5(kiss_fft_cpx* Fout, const size_t fstride, const kiss_fft_state* st, int32_t m, int32_t N, int32_t mm);
void opus_fft_impl(const kiss_fft_state* st, kiss_fft_cpx* fout);
uint32_t isqrt32(uint32_t _val);
int16_t celt_rsqrt_norm(int32_t x);
int32_t celt_sqrt(int32_t x);
int16_t celt_cos_norm(int32_t x);
void clt_mdct_backward(int32_t* in, int32_t* out, int32_t overlap, int32_t shift, int32_t stride);
int32_t interp_bits2pulses(int32_t start, int32_t end, int32_t skip_start, const int32_t* bits1, const int32_t* bits2, const int32_t* thresh, const int32_t* cap, int32_t total, int32_t* _balance,
int32_t skip_rsv, int32_t* intensity, int32_t intensity_rsv, int32_t* dual_stereo, int32_t dual_stereo_rsv, int32_t* bits, int32_t* ebits, int32_t* fine_priority,
int32_t C, int32_t LM, int32_t encode, int32_t prev, int32_t signalBandwidth);
int32_t clt_compute_allocation(int32_t start, int32_t end, const int32_t* offsets, const int32_t* cap, int32_t alloc_trim, int32_t* intensity, int32_t* dual_stereo, int32_t total,
int32_t* balance, int32_t* pulses, int32_t* ebits, int32_t* fine_priority, int32_t C, int32_t LM, int32_t encode, int32_t prev, int32_t signalBandwidth);
void unquant_coarse_energy(int32_t start, int32_t end, int16_t* oldEBands, int32_t intra, int32_t C, int32_t LM);
void unquant_fine_energy(int32_t start, int32_t end, int16_t* oldEBands, int32_t* fine_quant, int32_t C);
void unquant_energy_finalise(int32_t start, int32_t end, int16_t* oldEBands, int32_t* fine_quant, int32_t* fine_priority, int32_t bits_left, int32_t C);
uint32_t celt_udiv(uint32_t n, uint32_t d);
int32_t celt_sudiv(int32_t n, int32_t d);
int16_t sig2word16(int32_t x);
int16_t celt_atan01(int16_t x);
int16_t celt_atan2p(int16_t y, int16_t x);
int32_t celt_maxabs16(const int16_t* x, int32_t len);
int32_t celt_maxabs32(const int32_t* x, int32_t len);
int16_t celt_ilog2(int32_t x);
int16_t celt_zlog2(int32_t x);
int32_t celt_exp2_frac(int16_t x);
int32_t celt_exp2(int16_t x);
void dual_inner_prod_c(const int16_t* x, const int16_t* y01, const int16_t* y02, int32_t N, int32_t* xy1, int32_t* xy2);
int32_t get_pulses(int32_t i);
int32_t bits2pulses(int32_t band, int32_t LM, int32_t bits);
int32_t pulses2bits(int32_t band, int32_t LM, int32_t pulses);
int16_t celt_log2(int32_t x);
int16_t _celt_cos_pi_2(int16_t x);
};

View File

@@ -0,0 +1,153 @@
#pragma once
#define OPUS_OK 0
#define OPUS_BAD_ARG -1
#define OPUS_BUFFER_TOO_SMALL -2
#define OPUS_INTERNAL_ERROR -3
#define OPUS_INVALID_PACKET -4
#define OPUS_UNIMPLEMENTED -5
#define OPUS_INVALID_STATE -6
#define OPUS_ALLOC_FAIL -7
#define OPUS_GET_LOOKAHEAD_REQUEST 4027
#define OPUS_RESET_STATE 4028
#define OPUS_GET_PITCH_REQUEST 4033
#define OPUS_GET_FINAL_RANGE_REQUEST 4031
#define OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST 4046
#define OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST 4047
#define LEAK_BANDS 19
#define MAXFACTORS 8
#define CELT_CLZ0s ((int32_t)sizeof(uint32_t) * CHAR_BIT)
#define CELT_CLZ(_x) (__builtin_clz(_x))
#define CELT_ILOG(_x) (CELT_CLZ0s - CELT_CLZ(_x))
#define DECODER_RESET_START rng
#define TOTAL_MODES 1
#define BITRES 3
#define SPREAD_NONE (0)
#define SPREAD_LIGHT (1)
#define SPREAD_NORMAL (2)
#define SPREAD_AGGRESSIVE (3)
#define opus_likely(x) (__builtin_expect(!!(x), 1))
#define opus_unlikely(x) (__builtin_expect(!!(x), 0))
#define assert2(cond, message)
#define TWID_MAX 32767
#define TRIG_UPSCALE 1
#define LPC_ORDER 24
#define S_MUL(a, b) MULT16_32_Q15(b, a)
#define C_MUL(m, a, b) \
do { \
(m).r = SUB32_ovflw(S_MUL((a).r, (b).r), S_MUL((a).i, (b).i)); \
(m).i = ADD32_ovflw(S_MUL((a).r, (b).i), S_MUL((a).i, (b).r)); \
} while (0)
#define C_MULBYSCALAR(c, s) \
do { \
(c).r = S_MUL((c).r, s); \
(c).i = S_MUL((c).i, s); \
} while (0)
#define DIVSCALAR(x, k) (x) = S_MUL(x, (TWID_MAX - ((k) >> 1)) / (k) + 1)
#define C_ADD(res, a, b) \
do { \
(res).r = ADD32_ovflw((a).r, (b).r); \
(res).i = ADD32_ovflw((a).i, (b).i); \
} while (0)
#define C_SUB(res, a, b) \
do { \
(res).r = SUB32_ovflw((a).r, (b).r); \
(res).i = SUB32_ovflw((a).i, (b).i); \
} while (0)
#define C_ADDTO(res, a) \
do { \
(res).r = ADD32_ovflw((res).r, (a).r); \
(res).i = ADD32_ovflw((res).i, (a).i); \
} while (0)
#define HALF_OF(x) ((x) >> 1)
#define COMBFILTER_MINPERIOD 15
#define comb_filter_const(y, x, T, N, g10, g11, g12) (comb_filter_const_c(y, x, T, N, g10, g11, g12))
#define SIG_SAT (300000000)
#define NORM_SCALING 16384
#define DB_SHIFT 10
#define EPSILON 1
#define VERY_SMALL 0
#define VERY_LARGE16 ((int16_t)32767)
#define Q15_ONE ((int16_t)32767)
#define SCALEIN(a) (a)
#define SCALEOUT(a) (a)
#define MULT16_16SU(a, b) ((int32_t)(int16_t)(a) * (int32_t)(uint16_t)(b)) /** Multiply a 16-bit signed value by a 16-bit uint32_t value. The result is a 32-bit signed value */
#define MULT16_32_P16(a, b) ((int32_t)PSHR((int64_t)((int16_t)(a)) * (b), 16)) /** 16x32 multiplication, followed by a 16-bit shift right (round-to-nearest). Results fits in 32 bits */
#define MULT16_32_Q15(a, b) ((int32_t)SHR((int64_t)((int16_t)(a)) * (b), 15)) /** 16x32 multiplication, followed by a 15-bit shift right. Results fits in 32 bits */
#define MULT32_32_Q31(a, b) ((int32_t)SHR((int64_t)(a) * (int64_t)(b), 31)) /** 32x32 multiplication, followed by a 31-bit shift right. Results fits in 32 bits */
#define QCONST16(x, bits) ((int16_t)(0.5L + (x) * (((int32_t)1) << (bits)))) /** Compile-time conversion of float constant to 16-bit value */
#define QCONST32(x, bits) ((int32_t)(0.5L + (x) * (((int32_t)1) << (bits)))) /** Compile-time conversion of float constant to 32-bit value */
#define NEG16(x) (-(x)) /** Negate a 16-bit value */
#define NEG32(x) (-(x)) /** Negate a 32-bit value */
#define EXTRACT16(x) ((int16_t)(x)) /** Change a 32-bit value into a 16-bit value. The value is assumed to fit in 16-bit, otherwise the result is undefined */
#define EXTEND32(x) ((int32_t)(x)) /** Change a 16-bit value into a 32-bit value */
#define SHR16(a, shift) ((a) >> (shift)) /** Arithmetic shift-right of a 16-bit value */
#define SHL16(a, shift) ((int16_t)((uint16_t)(a) << (shift))) /** Arithmetic shift-left of a 16-bit value */
#define SHR32(a, shift) ((a) >> (shift)) /** Arithmetic shift-right of a 32-bit value */
#define SHL32(a, shift) ((int32_t)((uint32_t)(a) << (shift))) /** Arithmetic shift-left of a 32-bit value */
#define PSHR32(a, shift) (SHR32((a) + ((EXTEND32(1) << ((shift)) >> 1)), shift)) /** 32-bit arithmetic shift right with rounding-to-nearest instead of rounding down */
#define VSHR32(a, shift) (((shift) > 0) ? SHR32(a, shift) : SHL32(a, -(shift))) /** 32-bit arithmetic shift right where the argument can be negative */
#define SHR(a, shift) ((a) >> (shift)) /** "RAW" macros, should not be used outside of this header file */
#define SHL(a, shift) SHL32(a, shift)
#define PSHR(a, shift) (SHR((a) + ((EXTEND32(1) << ((shift)) >> 1)), shift))
#define SATURATE(x, a) (((x) > (a) ? (a) : (x) < -(a) ? -(a) : (x)))
#define SATURATE16(x) (EXTRACT16((x) > 32767 ? 32767 : (x) < -32768 ? -32768 : (x)))
#define ROUND16(x, a) (EXTRACT16(PSHR32((x), (a)))) /** Shift by a and round-to-neareast 32-bit value. Result is a 16-bit value */
#define SROUND16(x, a) EXTRACT16(SATURATE(PSHR32(x, a), 32767)); /** Shift by a and round-to-neareast 32-bit value. Result is a saturated 16-bit value */
#define HALF16(x) (SHR16(x, 1)) /** Divide by two */
#define HALF32(x) (SHR32(x, 1))
#define ADD16(a, b) ((int16_t)((int16_t)(a) + (int16_t)(b))) /** Add two 16-bit values */
#define SUB16(a, b) ((int16_t)(a) - (int16_t)(b)) /** Subtract two 16-bit values */
#define ADD32(a, b) ((int32_t)(a) + (int32_t)(b)) /** Add two 32-bit values */
#define SUB32(a, b) ((int32_t)(a) - (int32_t)(b)) /** Subtract two 32-bit values */
#define ADD32_ovflw(a, b) ((int32_t)((uint32_t)(a) + (uint32_t)(b))) /** Add two 32-bit values, ignore any overflows */
#define SUB32_ovflw(a, b) ((int32_t)((uint32_t)(a) - (uint32_t)(b))) /** Subtract two 32-bit values, ignore any overflows */
#define NEG32_ovflw(a) ((int32_t)(0 - (uint32_t)(a))) /* Avoid MSVC warning C4146: unary minus operator applied to uint32_t type, Negate 32-bit value, ignore any overflows */
#define MULT16_16_16(a, b) ((((int16_t)(a)) * ((int16_t)(b))))
#define MULT16_16(a, b) (((int32_t)(int16_t)(a)) * ((int32_t)(int16_t)(b))) /** 16x16 multiplication where the result fits in 32 bits */
#define MAC16_16(c, a, b) (ADD32((c), MULT16_16((a), (b)))) /** 16x16 multiply-add where the result fits in 32 bits */
#define MULT16_16_Q11_32(a, b) (SHR(MULT16_16((a), (b)), 11))
#define MULT16_16_Q11(a, b) (SHR(MULT16_16((a), (b)), 11))
#define MULT16_16_Q13(a, b) (SHR(MULT16_16((a), (b)), 13))
#define MULT16_16_Q14(a, b) (SHR(MULT16_16((a), (b)), 14))
#define MULT16_16_Q15(a, b) (SHR(MULT16_16((a), (b)), 15))
#define MULT16_16_P13(a, b) (SHR(ADD32(4096, MULT16_16((a), (b))), 13))
#define MULT16_16_P14(a, b) (SHR(ADD32(8192, MULT16_16((a), (b))), 14))
#define MULT16_16_P15(a, b) (SHR(ADD32(16384, MULT16_16((a), (b))), 15))
#define DIV32_16(a, b) ((int16_t)(((int32_t)(a)) / ((int16_t)(b)))) /** Divide a 32-bit value by a 16-bit value. Result fits in 16 bits */
#define DIV32(a, b) (((int32_t)(a)) / ((int32_t)(b))) /** Divide a 32-bit value by a 32-bit value. Result fits in 32 bits */
#define celt_div(a, b) MULT32_32_Q31((int32_t)(a), celt_rcp(b))
#define MAX_PERIOD 1024
#define OPUS_MOVE(dst, src, n) (memmove((dst), (src), (n) * sizeof(*(dst)) + 0 * ((dst) - (src))))
#define OPUS_CLEAR(dst, n) (memset((dst), 0, (n) * sizeof(*(dst))))
#define ALLOC_STEPS 6
#define celt_inner_prod(x, y, N) (celt_inner_prod_c(x, y, N))
#define dual_inner_prod(x, y01, y02, N, xy1, xy2) (dual_inner_prod_c(x, y01, y02, N, xy1, xy2))
#define FRAC_MUL16(a, b) ((16384 + ((int32_t)(int16_t)(a) * (int16_t)(b))) >> 15) /* Multiplies two 16-bit fractional values. Bit-exactness of this macro is important */
#define VARDECL(type, var)
#define ALLOC(var, size, type) type var[size]
#define FINE_OFFSET 21
#define QTHETA_OFFSET 4
#define QTHETA_OFFSET_TWOPHASE 16
#define MAX_FINE_BITS 8
#define MAX_PSEUDO 40
#define LOG_MAX_PSEUDO 6
#define ALLOC_NONE 1
#define OPUS_FPRINTF (void)
#define DECODE_BUFFER_SIZE 2048
#define CELT_PVQ_U(_n, _k) (celt_pvq_u_row(min(_n, _k), max(_n, _k)))
#define CELT_PVQ_V(_n, _k) (CELT_PVQ_U(_n, _k) + CELT_PVQ_U(_n, (_k) + 1))
#define CELT_GET_AND_CLEAR_ERROR_REQUEST 10007
#define CELT_SET_CHANNELS_REQUEST 10008
#define CELT_SET_START_BAND_REQUEST 10010
#define CELT_SET_END_BAND_REQUEST 10012
#define CELT_GET_MODE_REQUEST 10015
#define CELT_SET_SIGNALLING_REQUEST 10016
#define CELT_SET_TONALITY_REQUEST 10018
#define CELT_SET_TONALITY_SLOPE_REQUEST 10020
#define CELT_SET_ANALYSIS_REQUEST 10022
#define OPUS_SET_LFE_REQUEST 10024
#define OPUS_SET_ENERGY_MASK_REQUEST 10026
#define CELT_SET_SILK_INFO_REQUEST 10028
#define PLC_PITCH_LAG_MAX 720
#define PLC_PITCH_LAG_MIN 100

View File

@@ -0,0 +1,98 @@
#pragma once
#include <stdint-gcc.h>
#include "celt_defines.h"
typedef struct {
int32_t r;
int32_t i;
} kiss_fft_cpx;
typedef struct {
int16_t r;
int16_t i;
} kiss_twiddle_cpx;
typedef struct kiss_fft_state {
int32_t nfft;
int16_t scale;
int32_t scale_shift;
int32_t shift;
int16_t factors[2 * MAXFACTORS];
const int16_t* bitrev;
const kiss_twiddle_cpx* twiddles;
} kiss_fft_state;
typedef struct {
int32_t n;
int32_t maxshift;
const kiss_fft_state* kfft[4];
const int16_t* trig;
} mdct_lookup_t;
typedef struct {
int32_t size;
const int16_t* index;
const uint8_t* bits;
const uint8_t* caps;
} PulseCache;
typedef struct _CELTMode {
int32_t Fs;
int32_t overlap;
int32_t nbEBands;
int32_t effEBands;
int16_t preemph[4];
int32_t maxLM;
int32_t nbShortMdcts;
int32_t shortMdctSize;
int32_t nbAllocVectors; /**< Number of lines in the matrix below */
} CELTMode_t;
typedef struct _band_ctx {
int32_t resynth;
const CELTMode_t* m;
int32_t i;
int32_t intensity;
int32_t spread;
int32_t tf_change;
int32_t remaining_bits;
const int32_t* bandE;
uint32_t seed;
int32_t theta_round;
int32_t disable_inv;
int32_t avoid_split_noise;
} band_ctx_t;
struct split_ctx {
int32_t inv;
int32_t imid;
int32_t iside;
int32_t delta;
int32_t itheta;
int32_t qalloc;
};
typedef struct _CELTDecoder {
int32_t overlap;
int32_t channels;
int32_t stream_channels;
int32_t downsample;
int32_t start, end;
int32_t signalling;
int32_t disable_inv;
uint32_t rng;
int32_t error;
int32_t last_pitch_index;
int32_t loss_count;
int32_t skip_plc;
int32_t postfilter_period;
int32_t postfilter_period_old;
int16_t postfilter_gain;
int16_t postfilter_gain_old;
int32_t postfilter_tapset;
int32_t postfilter_tapset_old;
int32_t preemph_memD[2];
} CELTDecoder_t;

View File

@@ -0,0 +1,359 @@
#pragma once // celt_tables
#include "celt_structs.h"
#include <stdint-gcc.h>
static const int16_t eband5ms[22] = {
/*0 200 400 600 800 1k 1.2 1.4 1.6 2k 2.4 2.8 3.2 4k 4.8 5.6 6.8 8k 9.6 12k 15.6 */
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100};
static const uint8_t band_allocation[231] = {
/*0 200 400 600 800 1k 1.2 1.4 1.6 2k 2.4 2.8 3.2 4k 4.8 5.6 6.8 8k 9.6 12k 15.6 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90, 80, 75, 69, 63, 56, 49, 40, 34, 29, 20, 18, 10, 0, 0, 0, 0, 0,
0, 0, 0, 110, 100, 90, 84, 78, 71, 65, 58, 51, 45, 39, 32, 26, 20, 12, 0, 0, 0, 0, 0, 0, 118, 110, 103, 93, 86, 80, 75, 70, 65, 59, 53, 47, 40, 31, 23,
15, 4, 0, 0, 0, 0, 126, 119, 112, 104, 95, 89, 83, 78, 72, 66, 60, 54, 47, 39, 32, 25, 17, 12, 1, 0, 0, 134, 127, 120, 114, 103, 97, 91, 85, 78, 72, 66, 60,
54, 47, 41, 35, 29, 23, 16, 10, 1, 144, 137, 130, 124, 113, 107, 101, 95, 88, 82, 76, 70, 64, 57, 51, 45, 39, 33, 26, 15, 1, 152, 145, 138, 132, 123, 117, 111, 105, 98,
92, 86, 80, 74, 67, 61, 55, 49, 43, 36, 20, 1, 162, 155, 148, 142, 133, 127, 121, 115, 108, 102, 96, 90, 84, 77, 71, 65, 59, 53, 46, 30, 1, 172, 165, 158, 152, 143, 137,
131, 125, 118, 112, 106, 100, 94, 87, 81, 75, 69, 63, 56, 45, 20, 200, 200, 200, 200, 200, 200, 200, 200, 198, 193, 188, 183, 178, 173, 168, 163, 158, 153, 148, 129, 104,
};
/*For each V(N,K) supported, we will access element U(min(N,K+1),max(N,K+1)). Thus, the number of entries in row I is
the larger of the maximum number of pulses we will ever allocate for a given N=I (K=128, or however many fit in
32 bits, whichever is smaller), plus one, and the maximum N for which K=I-1 pulses fit in 32 bits.
The largest band size in an Opus Custom mode is 208. Otherwise, we can limit things to the set of N which can be
achieved by splitting a band from a
standard Opus mode: 176, 144, 96, 88, 72, 64, 48,44, 36, 32, 24, 22, 18, 16, 8, 4, 2).*/
static const uint32_t CELT_PVQ_U_DATA[1272] = {
/*N=0, K=0...176:*/
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/*N=1, K=1...176:*/
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/*N=2, K=2...176:*/
3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101,
103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179,
181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221, 223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253, 255, 257,
259, 261, 263, 265, 267, 269, 271, 273, 275, 277, 279, 281, 283, 285, 287, 289, 291, 293, 295, 297, 299, 301, 303, 305, 307, 309, 311, 313, 315, 317, 319, 321, 323, 325, 327, 329, 331, 333, 335,
337, 339, 341, 343, 345, 347, 349, 351,
/*N=3, K=3...176:*/
13, 25, 41, 61, 85, 113, 145, 181, 221, 265, 313, 365, 421, 481, 545, 613, 685, 761, 841, 925, 1013, 1105, 1201, 1301, 1405, 1513, 1625, 1741, 1861, 1985, 2113, 2245, 2381, 2521, 2665, 2813, 2965,
3121, 3281, 3445, 3613, 3785, 3961, 4141, 4325, 4513, 4705, 4901, 5101, 5305, 5513, 5725, 5941, 6161, 6385, 6613, 6845, 7081, 7321, 7565, 7813, 8065, 8321, 8581, 8845, 9113, 9385, 9661, 9941,
10225, 10513, 10805, 11101, 11401, 11705, 12013, 12325, 12641, 12961, 13285, 13613, 13945, 14281, 14621, 14965, 15313, 15665, 16021, 16381, 16745, 17113, 17485, 17861, 18241, 18625, 19013, 19405,
19801, 20201, 20605, 21013, 21425, 21841, 22261, 22685, 23113, 23545, 23981, 24421, 24865, 25313, 25765, 26221, 26681, 27145, 27613, 28085, 28561, 29041, 29525, 30013, 30505, 31001, 31501, 32005,
32513, 33025, 33541, 34061, 34585, 35113, 35645, 36181, 36721, 37265, 37813, 38365, 38921, 39481, 40045, 40613, 41185, 41761, 42341, 42925, 43513, 44105, 44701, 45301, 45905, 46513, 47125, 47741,
48361, 48985, 49613, 50245, 50881, 51521, 52165, 52813, 53465, 54121, 54781, 55445, 56113, 56785, 57461, 58141, 58825, 59513, 60205, 60901, 61601,
/*N=4, K=4...176:*/
63, 129, 231, 377, 575, 833, 1159, 1561, 2047, 2625, 3303, 4089, 4991, 6017, 7175, 8473, 9919, 11521, 13287, 15225, 17343, 19649, 22151, 24857, 27775, 30913, 34279, 37881, 41727, 45825, 50183,
54809, 59711, 64897, 70375, 76153, 82239, 88641, 95367, 102425, 109823, 117569, 125671, 134137, 142975, 152193, 161799, 171801, 182207, 193025, 204263, 215929, 228031, 240577, 253575, 267033,
280959, 295361, 310247, 325625, 341503, 357889, 374791, 392217, 410175, 428673, 447719, 467321, 487487, 508225, 529543, 551449, 573951, 597057, 620775, 645113, 670079, 695681, 721927, 748825,
776383, 804609, 833511, 863097, 893375, 924353, 956039, 988441, 1021567, 1055425, 1090023, 1125369, 1161471, 1198337, 1235975, 1274393, 1313599, 1353601, 1394407, 1436025, 1478463, 1521729,
1565831, 1610777, 1656575, 1703233, 1750759, 1799161, 1848447, 1898625, 1949703, 2001689, 2054591, 2108417, 2163175, 2218873, 2275519, 2333121, 2391687, 2451225, 2511743, 2573249, 2635751,
2699257, 2763775, 2829313, 2895879, 2963481, 3032127, 3101825, 3172583, 3244409, 3317311, 3391297, 3466375, 3542553, 3619839, 3698241, 3777767, 3858425, 3940223, 4023169, 4107271, 4192537,
4278975, 4366593, 4455399, 4545401, 4636607, 4729025, 4822663, 4917529, 5013631, 5110977, 5209575, 5309433, 5410559, 5512961, 5616647, 5721625, 5827903, 5935489, 6044391, 6154617, 6266175,
6379073, 6493319, 6608921, 6725887, 6844225, 6963943, 7085049, 7207551,
/*N=5, K=5...176:*/
321, 681, 1289, 2241, 3649, 5641, 8361, 11969, 16641, 22569, 29961, 39041, 50049, 63241, 78889, 97281, 118721, 143529, 172041, 204609, 241601, 283401, 330409, 383041, 441729, 506921, 579081,
658689, 746241, 842249, 947241, 1061761, 1186369, 1321641, 1468169, 1626561, 1797441, 1981449, 2179241, 2391489, 2618881, 2862121, 3121929, 3399041, 3694209, 4008201, 4341801, 4695809, 5071041,
5468329, 5888521, 6332481, 6801089, 7295241, 7815849, 8363841, 8940161, 9545769, 10181641, 10848769, 11548161, 12280841, 13047849, 13850241, 14689089, 15565481, 16480521, 17435329, 18431041,
19468809, 20549801, 21675201, 22846209, 24064041, 25329929, 26645121, 28010881, 29428489, 30899241, 32424449, 34005441, 35643561, 37340169, 39096641, 40914369, 42794761, 44739241, 46749249,
48826241, 50971689, 53187081, 55473921, 57833729, 60268041, 62778409, 65366401, 68033601, 70781609, 73612041, 76526529, 79526721, 82614281, 85790889, 89058241, 92418049, 95872041, 99421961,
103069569, 106816641, 110664969, 114616361, 118672641, 122835649, 127107241, 131489289, 135983681, 140592321, 145317129, 150160041, 155123009, 160208001, 165417001, 170752009, 176215041,
181808129, 187533321, 193392681, 199388289, 205522241, 211796649, 218213641, 224775361, 231483969, 238341641, 245350569, 252512961, 259831041, 267307049, 274943241, 282741889, 290705281,
298835721, 307135529, 315607041, 324252609, 333074601, 342075401, 351257409, 360623041, 370174729, 379914921, 389846081, 399970689, 410291241, 420810249, 431530241, 442453761, 453583369,
464921641, 476471169, 488234561, 500214441, 512413449, 524834241, 537479489, 550351881, 563454121, 576788929, 590359041, 604167209, 618216201, 632508801,
/*N=6, K=6...96:*/
1683, 3653, 7183, 13073, 22363, 36365, 56695, 85305, 124515, 177045, 246047, 335137, 448427, 590557, 766727, 982729, 1244979, 1560549, 1937199, 2383409, 2908411, 3522221, 4235671, 5060441,
6009091, 7095093, 8332863, 9737793, 11326283, 13115773, 15124775, 17372905, 19880915, 22670725, 25765455, 29189457, 32968347, 37129037, 41699767, 46710137, 52191139, 58175189, 64696159, 71789409,
79491819, 87841821, 96879431, 106646281, 117185651, 128542501, 140763503, 153897073, 167993403, 183104493, 199284183, 216588185, 235074115, 254801525, 275831935, 298228865, 322057867, 347386557,
374284647, 402823977, 433078547, 465124549, 499040399, 534906769, 572806619, 612825229, 655050231, 699571641, 746481891, 795875861, 847850911, 902506913, 959946283, 1020274013, 1083597703,
1150027593, 1219676595, 1292660325, 1369097135, 1449108145, 1532817275, 1620351277, 1711839767, 1807415257, 1907213187, 2011371957, 2120032959,
/*N=7, K=7...54*/
8989, 19825, 40081, 75517, 134245, 227305, 369305, 579125, 880685, 1303777, 1884961, 2668525, 3707509, 5064793, 6814249, 9041957, 11847485, 15345233, 19665841, 24957661, 31388293, 39146185,
48442297, 59511829, 72616013, 88043969, 106114625, 127178701, 151620757, 179861305, 212358985, 249612805, 292164445, 340600625, 395555537, 457713341, 527810725, 606639529, 695049433, 793950709,
904317037, 1027188385, 1163673953, 1314955181, 1482288821, 1667010073, 1870535785, 2094367717,
/*N=8, K=8...37*/
48639, 108545, 224143, 433905, 795455, 1392065, 2340495, 3800305, 5984767, 9173505, 13726991, 20103025, 28875327, 40754369, 56610575, 77500017, 104692735, 139703809, 184327311, 240673265,
311207743, 398796225, 506750351, 638878193, 799538175, 993696769, 1226990095, 1505789553, 1837271615, 2229491905U,
/*N=9, K=9...28:*/
265729, 598417, 1256465, 2485825, 4673345, 8405905, 14546705, 24331777, 39490049, 62390545, 96220561, 145198913, 214828609, 312193553, 446304145, 628496897, 872893441, 1196924561, 1621925137,
2173806145U,
/*N=10, K=10...24:*/
1462563, 3317445, 7059735, 14218905, 27298155, 50250765, 89129247, 152951073, 254831667, 413442773, 654862247, 1014889769, 1541911931, 2300409629U, 3375210671U,
/*N=11, K=11...19:*/
8097453, 18474633, 39753273, 81270333, 158819253, 298199265, 540279585, 948062325, 1616336765,
/*N=12, K=12...18:*/
45046719, 103274625, 224298231, 464387817, 921406335, 1759885185, 3248227095U,
/*N=13, K=13...16:*/
251595969, 579168825, 1267854873, 2653649025U,
/*N=14, K=14:*/
1409933619};
static const int16_t mdct_twiddles960[1800] = {
32767, 32767, 32767, 32766, 32765, 32763, 32761, 32759, 32756, 32753, 32750, 32746, 32742, 32738, 32733, 32728, 32722, 32717, 32710, 32704, 32697, 32690, 32682, 32674,
32666, 32657, 32648, 32639, 32629, 32619, 32609, 32598, 32587, 32576, 32564, 32552, 32539, 32526, 32513, 32500, 32486, 32472, 32457, 32442, 32427, 32411, 32395, 32379,
32362, 32345, 32328, 32310, 32292, 32274, 32255, 32236, 32217, 32197, 32177, 32157, 32136, 32115, 32093, 32071, 32049, 32027, 32004, 31981, 31957, 31933, 31909, 31884,
31859, 31834, 31809, 31783, 31756, 31730, 31703, 31676, 31648, 31620, 31592, 31563, 31534, 31505, 31475, 31445, 31415, 31384, 31353, 31322, 31290, 31258, 31226, 31193,
31160, 31127, 31093, 31059, 31025, 30990, 30955, 30920, 30884, 30848, 30812, 30775, 30738, 30701, 30663, 30625, 30587, 30548, 30509, 30470, 30430, 30390, 30350, 30309,
30269, 30227, 30186, 30144, 30102, 30059, 30016, 29973, 29930, 29886, 29842, 29797, 29752, 29707, 29662, 29616, 29570, 29524, 29477, 29430, 29383, 29335, 29287, 29239,
29190, 29142, 29092, 29043, 28993, 28943, 28892, 28842, 28791, 28739, 28688, 28636, 28583, 28531, 28478, 28425, 28371, 28317, 28263, 28209, 28154, 28099, 28044, 27988,
27932, 27876, 27820, 27763, 27706, 27648, 27591, 27533, 27474, 27416, 27357, 27298, 27238, 27178, 27118, 27058, 26997, 26936, 26875, 26814, 26752, 26690, 26628, 26565,
26502, 26439, 26375, 26312, 26247, 26183, 26119, 26054, 25988, 25923, 25857, 25791, 25725, 25658, 25592, 25524, 25457, 25389, 25322, 25253, 25185, 25116, 25047, 24978,
24908, 24838, 24768, 24698, 24627, 24557, 24485, 24414, 24342, 24270, 24198, 24126, 24053, 23980, 23907, 23834, 23760, 23686, 23612, 23537, 23462, 23387, 23312, 23237,
23161, 23085, 23009, 22932, 22856, 22779, 22701, 22624, 22546, 22468, 22390, 22312, 22233, 22154, 22075, 21996, 21916, 21836, 21756, 21676, 21595, 21515, 21434, 21352,
21271, 21189, 21107, 21025, 20943, 20860, 20777, 20694, 20611, 20528, 20444, 20360, 20276, 20192, 20107, 20022, 19937, 19852, 19767, 19681, 19595, 19509, 19423, 19336,
19250, 19163, 19076, 18988, 18901, 18813, 18725, 18637, 18549, 18460, 18372, 18283, 18194, 18104, 18015, 17925, 17835, 17745, 17655, 17565, 17474, 17383, 17292, 17201,
17110, 17018, 16927, 16835, 16743, 16650, 16558, 16465, 16372, 16279, 16186, 16093, 15999, 15906, 15812, 15718, 15624, 15529, 15435, 15340, 15245, 15150, 15055, 14960,
14864, 14769, 14673, 14577, 14481, 14385, 14288, 14192, 14095, 13998, 13901, 13804, 13706, 13609, 13511, 13414, 13316, 13218, 13119, 13021, 12923, 12824, 12725, 12626,
12527, 12428, 12329, 12230, 12130, 12030, 11930, 11831, 11730, 11630, 11530, 11430, 11329, 11228, 11128, 11027, 10926, 10824, 10723, 10622, 10520, 10419, 10317, 10215,
10113, 10011, 9909, 9807, 9704, 9602, 9499, 9397, 9294, 9191, 9088, 8985, 8882, 8778, 8675, 8572, 8468, 8364, 8261, 8157, 8053, 7949, 7845, 7741,
7637, 7532, 7428, 7323, 7219, 7114, 7009, 6905, 6800, 6695, 6590, 6485, 6380, 6274, 6169, 6064, 5958, 5853, 5747, 5642, 5536, 5430, 5325, 5219,
5113, 5007, 4901, 4795, 4689, 4583, 4476, 4370, 4264, 4157, 4051, 3945, 3838, 3732, 3625, 3518, 3412, 3305, 3198, 3092, 2985, 2878, 2771, 2664,
2558, 2451, 2344, 2237, 2130, 2023, 1916, 1809, 1702, 1594, 1487, 1380, 1273, 1166, 1059, 952, 844, 737, 630, 523, 416, 308, 201, 94,
-13, -121, -228, -335, -442, -550, -657, -764, -871, -978, -1086, -1193, -1300, -1407, -1514, -1621, -1728, -1835, -1942, -2049, -2157, -2263, -2370, -2477,
-2584, -2691, -2798, -2905, -3012, -3118, -3225, -3332, -3439, -3545, -3652, -3758, -3865, -3971, -4078, -4184, -4290, -4397, -4503, -4609, -4715, -4821, -4927, -5033,
-5139, -5245, -5351, -5457, -5562, -5668, -5774, -5879, -5985, -6090, -6195, -6301, -6406, -6511, -6616, -6721, -6826, -6931, -7036, -7140, -7245, -7349, -7454, -7558,
-7663, -7767, -7871, -7975, -8079, -8183, -8287, -8390, -8494, -8597, -8701, -8804, -8907, -9011, -9114, -9217, -9319, -9422, -9525, -9627, -9730, -9832, -9934, -10037,
-10139, -10241, -10342, -10444, -10546, -10647, -10748, -10850, -10951, -11052, -11153, -11253, -11354, -11455, -11555, -11655, -11756, -11856, -11955, -12055, -12155, -12254, -12354, -12453,
-12552, -12651, -12750, -12849, -12947, -13046, -13144, -13242, -13340, -13438, -13536, -13633, -13731, -13828, -13925, -14022, -14119, -14216, -14312, -14409, -14505, -14601, -14697, -14793,
-14888, -14984, -15079, -15174, -15269, -15364, -15459, -15553, -15647, -15741, -15835, -15929, -16023, -16116, -16210, -16303, -16396, -16488, -16581, -16673, -16766, -16858, -16949, -17041,
-17133, -17224, -17315, -17406, -17497, -17587, -17678, -17768, -17858, -17948, -18037, -18127, -18216, -18305, -18394, -18483, -18571, -18659, -18747, -18835, -18923, -19010, -19098, -19185,
-19271, -19358, -19444, -19531, -19617, -19702, -19788, -19873, -19959, -20043, -20128, -20213, -20297, -20381, -20465, -20549, -20632, -20715, -20798, -20881, -20963, -21046, -21128, -21210,
-21291, -21373, -21454, -21535, -21616, -21696, -21776, -21856, -21936, -22016, -22095, -22174, -22253, -22331, -22410, -22488, -22566, -22643, -22721, -22798, -22875, -22951, -23028, -23104,
-23180, -23256, -23331, -23406, -23481, -23556, -23630, -23704, -23778, -23852, -23925, -23998, -24071, -24144, -24216, -24288, -24360, -24432, -24503, -24574, -24645, -24716, -24786, -24856,
-24926, -24995, -25064, -25133, -25202, -25270, -25339, -25406, -25474, -25541, -25608, -25675, -25742, -25808, -25874, -25939, -26005, -26070, -26135, -26199, -26264, -26327, -26391, -26455,
-26518, -26581, -26643, -26705, -26767, -26829, -26891, -26952, -27013, -27073, -27133, -27193, -27253, -27312, -27372, -27430, -27489, -27547, -27605, -27663, -27720, -27777, -27834, -27890,
-27946, -28002, -28058, -28113, -28168, -28223, -28277, -28331, -28385, -28438, -28491, -28544, -28596, -28649, -28701, -28752, -28803, -28854, -28905, -28955, -29006, -29055, -29105, -29154,
-29203, -29251, -29299, -29347, -29395, -29442, -29489, -29535, -29582, -29628, -29673, -29719, -29764, -29808, -29853, -29897, -29941, -29984, -30027, -30070, -30112, -30154, -30196, -30238,
-30279, -30320, -30360, -30400, -30440, -30480, -30519, -30558, -30596, -30635, -30672, -30710, -30747, -30784, -30821, -30857, -30893, -30929, -30964, -30999, -31033, -31068, -31102, -31135,
-31168, -31201, -31234, -31266, -31298, -31330, -31361, -31392, -31422, -31453, -31483, -31512, -31541, -31570, -31599, -31627, -31655, -31682, -31710, -31737, -31763, -31789, -31815, -31841,
-31866, -31891, -31915, -31939, -31963, -31986, -32010, -32032, -32055, -32077, -32099, -32120, -32141, -32162, -32182, -32202, -32222, -32241, -32260, -32279, -32297, -32315, -32333, -32350,
-32367, -32383, -32399, -32415, -32431, -32446, -32461, -32475, -32489, -32503, -32517, -32530, -32542, -32555, -32567, -32579, -32590, -32601, -32612, -32622, -32632, -32641, -32651, -32659,
-32668, -32676, -32684, -32692, -32699, -32706, -32712, -32718, -32724, -32729, -32734, -32739, -32743, -32747, -32751, -32754, -32757, -32760, -32762, -32764, -32765, -32767, -32767, -32767,
32767, 32767, 32765, 32761, 32756, 32750, 32742, 32732, 32722, 32710, 32696, 32681, 32665, 32647, 32628, 32608, 32586, 32562, 32538, 32512, 32484, 32455, 32425, 32393,
32360, 32326, 32290, 32253, 32214, 32174, 32133, 32090, 32046, 32001, 31954, 31906, 31856, 31805, 31753, 31700, 31645, 31588, 31530, 31471, 31411, 31349, 31286, 31222,
31156, 31089, 31020, 30951, 30880, 30807, 30733, 30658, 30582, 30504, 30425, 30345, 30263, 30181, 30096, 30011, 29924, 29836, 29747, 29656, 29564, 29471, 29377, 29281,
29184, 29086, 28987, 28886, 28784, 28681, 28577, 28471, 28365, 28257, 28147, 28037, 27925, 27812, 27698, 27583, 27467, 27349, 27231, 27111, 26990, 26868, 26744, 26620,
26494, 26367, 26239, 26110, 25980, 25849, 25717, 25583, 25449, 25313, 25176, 25038, 24900, 24760, 24619, 24477, 24333, 24189, 24044, 23898, 23751, 23602, 23453, 23303,
23152, 22999, 22846, 22692, 22537, 22380, 22223, 22065, 21906, 21746, 21585, 21423, 21261, 21097, 20933, 20767, 20601, 20434, 20265, 20096, 19927, 19756, 19584, 19412,
19239, 19065, 18890, 18714, 18538, 18361, 18183, 18004, 17824, 17644, 17463, 17281, 17098, 16915, 16731, 16546, 16361, 16175, 15988, 15800, 15612, 15423, 15234, 15043,
14852, 14661, 14469, 14276, 14083, 13889, 13694, 13499, 13303, 13107, 12910, 12713, 12515, 12317, 12118, 11918, 11718, 11517, 11316, 11115, 10913, 10710, 10508, 10304,
10100, 9896, 9691, 9486, 9281, 9075, 8869, 8662, 8455, 8248, 8040, 7832, 7623, 7415, 7206, 6996, 6787, 6577, 6366, 6156, 5945, 5734, 5523, 5311,
5100, 4888, 4675, 4463, 4251, 4038, 3825, 3612, 3399, 3185, 2972, 2758, 2544, 2330, 2116, 1902, 1688, 1474, 1260, 1045, 831, 617, 402, 188,
-27, -241, -456, -670, -885, -1099, -1313, -1528, -1742, -1956, -2170, -2384, -2598, -2811, -3025, -3239, -3452, -3665, -3878, -4091, -4304, -4516, -4728, -4941,
-5153, -5364, -5576, -5787, -5998, -6209, -6419, -6629, -6839, -7049, -7258, -7467, -7676, -7884, -8092, -8300, -8507, -8714, -8920, -9127, -9332, -9538, -9743, -9947,
-10151, -10355, -10558, -10761, -10963, -11165, -11367, -11568, -11768, -11968, -12167, -12366, -12565, -12762, -12960, -13156, -13352, -13548, -13743, -13937, -14131, -14324, -14517, -14709,
-14900, -15091, -15281, -15470, -15659, -15847, -16035, -16221, -16407, -16593, -16777, -16961, -17144, -17326, -17508, -17689, -17869, -18049, -18227, -18405, -18582, -18758, -18934, -19108,
-19282, -19455, -19627, -19799, -19969, -20139, -20308, -20475, -20642, -20809, -20974, -21138, -21301, -21464, -21626, -21786, -21946, -22105, -22263, -22420, -22575, -22730, -22884, -23037,
-23189, -23340, -23490, -23640, -23788, -23935, -24080, -24225, -24369, -24512, -24654, -24795, -24934, -25073, -25211, -25347, -25482, -25617, -25750, -25882, -26013, -26143, -26272, -26399,
-26526, -26651, -26775, -26898, -27020, -27141, -27260, -27379, -27496, -27612, -27727, -27841, -27953, -28065, -28175, -28284, -28391, -28498, -28603, -28707, -28810, -28911, -29012, -29111,
-29209, -29305, -29401, -29495, -29587, -29679, -29769, -29858, -29946, -30032, -30118, -30201, -30284, -30365, -30445, -30524, -30601, -30677, -30752, -30825, -30897, -30968, -31038, -31106,
-31172, -31238, -31302, -31365, -31426, -31486, -31545, -31602, -31658, -31713, -31766, -31818, -31869, -31918, -31966, -32012, -32058, -32101, -32144, -32185, -32224, -32262, -32299, -32335,
-32369, -32401, -32433, -32463, -32491, -32518, -32544, -32568, -32591, -32613, -32633, -32652, -32669, -32685, -32700, -32713, -32724, -32735, -32744, -32751, -32757, -32762, -32766, -32767,
32767, 32764, 32755, 32741, 32720, 32694, 32663, 32626, 32583, 32535, 32481, 32421, 32356, 32286, 32209, 32128, 32041, 31948, 31850, 31747, 31638, 31523, 31403, 31278,
31148, 31012, 30871, 30724, 30572, 30415, 30253, 30086, 29913, 29736, 29553, 29365, 29172, 28974, 28771, 28564, 28351, 28134, 27911, 27684, 27452, 27216, 26975, 26729,
26478, 26223, 25964, 25700, 25432, 25159, 24882, 24601, 24315, 24026, 23732, 23434, 23133, 22827, 22517, 22204, 21886, 21565, 21240, 20912, 20580, 20244, 19905, 19563,
19217, 18868, 18516, 18160, 17802, 17440, 17075, 16708, 16338, 15964, 15588, 15210, 14829, 14445, 14059, 13670, 13279, 12886, 12490, 12093, 11693, 11291, 10888, 10482,
10075, 9666, 9255, 8843, 8429, 8014, 7597, 7180, 6760, 6340, 5919, 5496, 5073, 4649, 4224, 3798, 3372, 2945, 2517, 2090, 1661, 1233, 804, 375,
-54, -483, -911, -1340, -1768, -2197, -2624, -3052, -3479, -3905, -4330, -4755, -5179, -5602, -6024, -6445, -6865, -7284, -7702, -8118, -8533, -8946, -9358, -9768,
-10177, -10584, -10989, -11392, -11793, -12192, -12589, -12984, -13377, -13767, -14155, -14541, -14924, -15305, -15683, -16058, -16430, -16800, -17167, -17531, -17892, -18249, -18604, -18956,
-19304, -19649, -19990, -20329, -20663, -20994, -21322, -21646, -21966, -22282, -22595, -22904, -23208, -23509, -23806, -24099, -24387, -24672, -24952, -25228, -25499, -25766, -26029, -26288,
-26541, -26791, -27035, -27275, -27511, -27741, -27967, -28188, -28405, -28616, -28823, -29024, -29221, -29412, -29599, -29780, -29957, -30128, -30294, -30455, -30611, -30761, -30906, -31046,
-31181, -31310, -31434, -31552, -31665, -31773, -31875, -31972, -32063, -32149, -32229, -32304, -32373, -32437, -32495, -32547, -32594, -32635, -32671, -32701, -32726, -32745, -32758, -32766,
32767, 32754, 32717, 32658, 32577, 32473, 32348, 32200, 32029, 31837, 31624, 31388, 31131, 30853, 30553, 30232, 29891, 29530, 29148, 28746, 28324, 27883, 27423, 26944,
26447, 25931, 25398, 24847, 24279, 23695, 23095, 22478, 21846, 21199, 20538, 19863, 19174, 18472, 17757, 17030, 16291, 15541, 14781, 14010, 13230, 12441, 11643, 10837,
10024, 9204, 8377, 7545, 6708, 5866, 5020, 4171, 3319, 2464, 1608, 751, -107, -965, -1822, -2678, -3532, -4383, -5232, -6077, -6918, -7754, -8585, -9409,
-10228, -11039, -11843, -12639, -13426, -14204, -14972, -15730, -16477, -17213, -17937, -18648, -19347, -20033, -20705, -21363, -22006, -22634, -23246, -23843, -24423, -24986, -25533, -26062,
-26573, -27066, -27540, -27995, -28431, -28848, -29245, -29622, -29979, -30315, -30630, -30924, -31197, -31449, -31679, -31887, -32074, -32239, -32381, -32501, -32600, -32675, -32729, -32759,
};
static const int16_t window120[120] = {
2, 20, 55, 108, 178, 266, 372, 494, 635, 792, 966, 1157, 1365, 1590, 1831, 2089, 2362, 2651, 2956, 3276, 3611, 3961, 4325, 4703,
5094, 5499, 5916, 6346, 6788, 7241, 7705, 8179, 8663, 9156, 9657, 10167, 10684, 11207, 11736, 12271, 12810, 13353, 13899, 14447, 14997, 15547, 16098, 16648,
17197, 17744, 18287, 18827, 19363, 19893, 20418, 20936, 21447, 21950, 22445, 22931, 23407, 23874, 24330, 24774, 25208, 25629, 26039, 26435, 26819, 27190, 27548, 27893,
28224, 28541, 28845, 29135, 29411, 29674, 29924, 30160, 30384, 30594, 30792, 30977, 31151, 31313, 31463, 31602, 31731, 31849, 31958, 32057, 32148, 32229, 32303, 32370,
32429, 32481, 32528, 32568, 32604, 32634, 32661, 32683, 32701, 32717, 32729, 32740, 32748, 32754, 32758, 32762, 32764, 32766, 32767, 32767, 32767, 32767, 32767, 32767,
};
static const int16_t logN400[21] = {
0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 16, 16, 16, 21, 21, 24, 29, 34, 36,
};
static const int16_t cache_index50[105] = {
-1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 41, 41, 41, 82, 82, 123, 164, 200, 222, 0, 0, 0, 0, 0, 0, 0, 0, 41, 41, 41, 41, 123, 123,
123, 164, 164, 240, 266, 283, 295, 41, 41, 41, 41, 41, 41, 41, 41, 123, 123, 123, 123, 240, 240, 240, 266, 266, 305, 318, 328, 336, 123, 123, 123, 123, 123, 123, 123,
123, 240, 240, 240, 240, 305, 305, 305, 318, 318, 343, 351, 358, 364, 240, 240, 240, 240, 240, 240, 240, 240, 305, 305, 305, 305, 343, 343, 343, 351, 351, 370, 376, 382, 387,
};
static const uint8_t cache_bits50[392] = {
40, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 40, 15, 23, 28, 31, 34, 36, 38, 39, 41, 42, 43, 44, 45, 46, 47, 47, 49, 50, 51, 52, 53, 54, 55, 55, 57, 58, 59, 60, 61, 62,
63, 63, 65, 66, 67, 68, 69, 70, 71, 71, 40, 20, 33, 41, 48, 53, 57, 61, 64, 66, 69, 71, 73, 75, 76, 78, 80, 82, 85, 87, 89, 91, 92, 94, 96, 98,
101, 103, 105, 107, 108, 110, 112, 114, 117, 119, 121, 123, 124, 126, 128, 40, 23, 39, 51, 60, 67, 73, 79, 83, 87, 91, 94, 97, 100, 102, 105, 107, 111, 115, 118, 121,
124, 126, 129, 131, 135, 139, 142, 145, 148, 150, 153, 155, 159, 163, 166, 169, 172, 174, 177, 179, 35, 28, 49, 65, 78, 89, 99, 107, 114, 120, 126, 132, 136, 141, 145, 149,
153, 159, 165, 171, 176, 180, 185, 189, 192, 199, 205, 211, 216, 220, 225, 229, 232, 239, 245, 251, 21, 33, 58, 79, 97, 112, 125, 137, 148, 157, 166, 174, 182, 189, 195, 201,
207, 217, 227, 235, 243, 251, 17, 35, 63, 86, 106, 123, 139, 152, 165, 177, 187, 197, 206, 214, 222, 230, 237, 250, 25, 31, 55, 75, 91, 105, 117, 128, 138, 146, 154, 161,
168, 174, 180, 185, 190, 200, 208, 215, 222, 229, 235, 240, 245, 255, 16, 36, 65, 89, 110, 128, 144, 159, 173, 185, 196, 207, 217, 226, 234, 242, 250, 11, 41, 74, 103, 128,
151, 172, 191, 209, 225, 241, 255, 9, 43, 79, 110, 138, 163, 186, 207, 227, 246, 12, 39, 71, 99, 123, 144, 164, 182, 198, 214, 228, 241, 253, 9, 44, 81, 113, 142, 168,
192, 214, 235, 255, 7, 49, 90, 127, 160, 191, 220, 247, 6, 51, 95, 134, 170, 203, 234, 7, 47, 87, 123, 155, 184, 212, 237, 6, 52, 97, 137, 174, 208, 240, 5, 57,
106, 151, 192, 231, 5, 59, 111, 158, 202, 243, 5, 55, 103, 147, 187, 224, 5, 60, 113, 161, 206, 248, 4, 65, 122, 175, 224, 4, 67, 127, 182, 234,
};
static const uint8_t cache_caps50[168] = {
224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240, 240, 240, 240, 207,
207, 207, 198, 198, 183, 144, 66, 40, 160, 160, 160, 160, 160, 160, 160, 160, 185, 185, 185, 185, 193, 193, 193, 183, 183, 172, 138, 64, 38, 240, 240, 240, 240, 240,
240, 240, 240, 207, 207, 207, 207, 204, 204, 204, 193, 193, 180, 143, 66, 40, 185, 185, 185, 185, 185, 185, 185, 185, 193, 193, 193, 193, 193, 193, 193, 183, 183, 172,
138, 65, 39, 207, 207, 207, 207, 207, 207, 207, 207, 204, 204, 204, 204, 201, 201, 201, 188, 188, 176, 141, 66, 40, 193, 193, 193, 193, 193, 193, 193, 193, 193, 193,
193, 193, 194, 194, 194, 184, 184, 173, 139, 65, 39, 204, 204, 204, 204, 204, 204, 204, 204, 201, 201, 201, 201, 198, 198, 198, 187, 187, 175, 140, 66, 40,
};
static const kiss_twiddle_cpx fft_twiddles48000_960[480] = {
{32767, 0}, {32766, -429}, {32757, -858}, {32743, -1287}, {32724, -1715}, {32698, -2143}, {32667, -2570}, {32631, -2998}, {32588, -3425}, {32541, -3851},
{32488, -4277}, {32429, -4701}, {32364, -5125}, {32295, -5548}, {32219, -5971}, {32138, -6393}, {32051, -6813}, {31960, -7231}, {31863, -7650}, {31760, -8067},
{31652, -8481}, {31539, -8895}, {31419, -9306}, {31294, -9716}, {31165, -10126}, {31030, -10532}, {30889, -10937}, {30743, -11340}, {30592, -11741}, {30436, -12141},
{30274, -12540}, {30107, -12935}, {29936, -13328}, {29758, -13718}, {29577, -14107}, {29390, -14493}, {29197, -14875}, {29000, -15257}, {28797, -15635}, {28590, -16010},
{28379, -16384}, {28162, -16753}, {27940, -17119}, {27714, -17484}, {27482, -17845}, {27246, -18205}, {27006, -18560}, {26760, -18911}, {26510, -19260}, {26257, -19606},
{25997, -19947}, {25734, -20286}, {25466, -20621}, {25194, -20952}, {24918, -21281}, {24637, -21605}, {24353, -21926}, {24063, -22242}, {23770, -22555}, {23473, -22865},
{23171, -23171}, {22866, -23472}, {22557, -23769}, {22244, -24063}, {21927, -24352}, {21606, -24636}, {21282, -24917}, {20954, -25194}, {20622, -25465}, {20288, -25733},
{19949, -25997}, {19607, -26255}, {19261, -26509}, {18914, -26760}, {18561, -27004}, {18205, -27246}, {17846, -27481}, {17485, -27713}, {17122, -27940}, {16755, -28162},
{16385, -28378}, {16012, -28590}, {15636, -28797}, {15258, -28999}, {14878, -29197}, {14494, -29389}, {14108, -29576}, {13720, -29757}, {13329, -29934}, {12937, -30107},
{12540, -30274}, {12142, -30435}, {11744, -30592}, {11342, -30743}, {10939, -30889}, {10534, -31030}, {10127, -31164}, {9718, -31294}, {9307, -31418}, {8895, -31537},
{8482, -31652}, {8067, -31759}, {7650, -31862}, {7233, -31960}, {6815, -32051}, {6393, -32138}, {5973, -32219}, {5549, -32294}, {5127, -32364}, {4703, -32429},
{4278, -32487}, {3852, -32541}, {3426, -32588}, {2999, -32630}, {2572, -32667}, {2144, -32698}, {1716, -32724}, {1287, -32742}, {860, -32757}, {430, -32766},
{0, -32767}, {-429, -32766}, {-858, -32757}, {-1287, -32743}, {-1715, -32724}, {-2143, -32698}, {-2570, -32667}, {-2998, -32631}, {-3425, -32588}, {-3851, -32541},
{-4277, -32488}, {-4701, -32429}, {-5125, -32364}, {-5548, -32295}, {-5971, -32219}, {-6393, -32138}, {-6813, -32051}, {-7231, -31960}, {-7650, -31863}, {-8067, -31760},
{-8481, -31652}, {-8895, -31539}, {-9306, -31419}, {-9716, -31294}, {-10126, -31165}, {-10532, -31030}, {-10937, -30889}, {-11340, -30743}, {-11741, -30592}, {-12141, -30436},
{-12540, -30274}, {-12935, -30107}, {-13328, -29936}, {-13718, -29758}, {-14107, -29577}, {-14493, -29390}, {-14875, -29197}, {-15257, -29000}, {-15635, -28797}, {-16010, -28590},
{-16384, -28379}, {-16753, -28162}, {-17119, -27940}, {-17484, -27714}, {-17845, -27482}, {-18205, -27246}, {-18560, -27006}, {-18911, -26760}, {-19260, -26510}, {-19606, -26257},
{-19947, -25997}, {-20286, -25734}, {-20621, -25466}, {-20952, -25194}, {-21281, -24918}, {-21605, -24637}, {-21926, -24353}, {-22242, -24063}, {-22555, -23770}, {-22865, -23473},
{-23171, -23171}, {-23472, -22866}, {-23769, -22557}, {-24063, -22244}, {-24352, -21927}, {-24636, -21606}, {-24917, -21282}, {-25194, -20954}, {-25465, -20622}, {-25733, -20288},
{-25997, -19949}, {-26255, -19607}, {-26509, -19261}, {-26760, -18914}, {-27004, -18561}, {-27246, -18205}, {-27481, -17846}, {-27713, -17485}, {-27940, -17122}, {-28162, -16755},
{-28378, -16385}, {-28590, -16012}, {-28797, -15636}, {-28999, -15258}, {-29197, -14878}, {-29389, -14494}, {-29576, -14108}, {-29757, -13720}, {-29934, -13329}, {-30107, -12937},
{-30274, -12540}, {-30435, -12142}, {-30592, -11744}, {-30743, -11342}, {-30889, -10939}, {-31030, -10534}, {-31164, -10127}, {-31294, -9718}, {-31418, -9307}, {-31537, -8895},
{-31652, -8482}, {-31759, -8067}, {-31862, -7650}, {-31960, -7233}, {-32051, -6815}, {-32138, -6393}, {-32219, -5973}, {-32294, -5549}, {-32364, -5127}, {-32429, -4703},
{-32487, -4278}, {-32541, -3852}, {-32588, -3426}, {-32630, -2999}, {-32667, -2572}, {-32698, -2144}, {-32724, -1716}, {-32742, -1287}, {-32757, -860}, {-32766, -430},
{-32767, 0}, {-32766, 429}, {-32757, 858}, {-32743, 1287}, {-32724, 1715}, {-32698, 2143}, {-32667, 2570}, {-32631, 2998}, {-32588, 3425}, {-32541, 3851},
{-32488, 4277}, {-32429, 4701}, {-32364, 5125}, {-32295, 5548}, {-32219, 5971}, {-32138, 6393}, {-32051, 6813}, {-31960, 7231}, {-31863, 7650}, {-31760, 8067},
{-31652, 8481}, {-31539, 8895}, {-31419, 9306}, {-31294, 9716}, {-31165, 10126}, {-31030, 10532}, {-30889, 10937}, {-30743, 11340}, {-30592, 11741}, {-30436, 12141},
{-30274, 12540}, {-30107, 12935}, {-29936, 13328}, {-29758, 13718}, {-29577, 14107}, {-29390, 14493}, {-29197, 14875}, {-29000, 15257}, {-28797, 15635}, {-28590, 16010},
{-28379, 16384}, {-28162, 16753}, {-27940, 17119}, {-27714, 17484}, {-27482, 17845}, {-27246, 18205}, {-27006, 18560}, {-26760, 18911}, {-26510, 19260}, {-26257, 19606},
{-25997, 19947}, {-25734, 20286}, {-25466, 20621}, {-25194, 20952}, {-24918, 21281}, {-24637, 21605}, {-24353, 21926}, {-24063, 22242}, {-23770, 22555}, {-23473, 22865},
{-23171, 23171}, {-22866, 23472}, {-22557, 23769}, {-22244, 24063}, {-21927, 24352}, {-21606, 24636}, {-21282, 24917}, {-20954, 25194}, {-20622, 25465}, {-20288, 25733},
{-19949, 25997}, {-19607, 26255}, {-19261, 26509}, {-18914, 26760}, {-18561, 27004}, {-18205, 27246}, {-17846, 27481}, {-17485, 27713}, {-17122, 27940}, {-16755, 28162},
{-16385, 28378}, {-16012, 28590}, {-15636, 28797}, {-15258, 28999}, {-14878, 29197}, {-14494, 29389}, {-14108, 29576}, {-13720, 29757}, {-13329, 29934}, {-12937, 30107},
{-12540, 30274}, {-12142, 30435}, {-11744, 30592}, {-11342, 30743}, {-10939, 30889}, {-10534, 31030}, {-10127, 31164}, {-9718, 31294}, {-9307, 31418}, {-8895, 31537},
{-8482, 31652}, {-8067, 31759}, {-7650, 31862}, {-7233, 31960}, {-6815, 32051}, {-6393, 32138}, {-5973, 32219}, {-5549, 32294}, {-5127, 32364}, {-4703, 32429},
{-4278, 32487}, {-3852, 32541}, {-3426, 32588}, {-2999, 32630}, {-2572, 32667}, {-2144, 32698}, {-1716, 32724}, {-1287, 32742}, {-860, 32757}, {-430, 32766},
{0, 32767}, {429, 32766}, {858, 32757}, {1287, 32743}, {1715, 32724}, {2143, 32698}, {2570, 32667}, {2998, 32631}, {3425, 32588}, {3851, 32541},
{4277, 32488}, {4701, 32429}, {5125, 32364}, {5548, 32295}, {5971, 32219}, {6393, 32138}, {6813, 32051}, {7231, 31960}, {7650, 31863}, {8067, 31760},
{8481, 31652}, {8895, 31539}, {9306, 31419}, {9716, 31294}, {10126, 31165}, {10532, 31030}, {10937, 30889}, {11340, 30743}, {11741, 30592}, {12141, 30436},
{12540, 30274}, {12935, 30107}, {13328, 29936}, {13718, 29758}, {14107, 29577}, {14493, 29390}, {14875, 29197}, {15257, 29000}, {15635, 28797}, {16010, 28590},
{16384, 28379}, {16753, 28162}, {17119, 27940}, {17484, 27714}, {17845, 27482}, {18205, 27246}, {18560, 27006}, {18911, 26760}, {19260, 26510}, {19606, 26257},
{19947, 25997}, {20286, 25734}, {20621, 25466}, {20952, 25194}, {21281, 24918}, {21605, 24637}, {21926, 24353}, {22242, 24063}, {22555, 23770}, {22865, 23473},
{23171, 23171}, {23472, 22866}, {23769, 22557}, {24063, 22244}, {24352, 21927}, {24636, 21606}, {24917, 21282}, {25194, 20954}, {25465, 20622}, {25733, 20288},
{25997, 19949}, {26255, 19607}, {26509, 19261}, {26760, 18914}, {27004, 18561}, {27246, 18205}, {27481, 17846}, {27713, 17485}, {27940, 17122}, {28162, 16755},
{28378, 16385}, {28590, 16012}, {28797, 15636}, {28999, 15258}, {29197, 14878}, {29389, 14494}, {29576, 14108}, {29757, 13720}, {29934, 13329}, {30107, 12937},
{30274, 12540}, {30435, 12142}, {30592, 11744}, {30743, 11342}, {30889, 10939}, {31030, 10534}, {31164, 10127}, {31294, 9718}, {31418, 9307}, {31537, 8895},
{31652, 8482}, {31759, 8067}, {31862, 7650}, {31960, 7233}, {32051, 6815}, {32138, 6393}, {32219, 5973}, {32294, 5549}, {32364, 5127}, {32429, 4703},
{32487, 4278}, {32541, 3852}, {32588, 3426}, {32630, 2999}, {32667, 2572}, {32698, 2144}, {32724, 1716}, {32742, 1287}, {32757, 860}, {32766, 430},
};
static const int16_t fft_bitrev480[480] = {
0, 96, 192, 288, 384, 32, 128, 224, 320, 416, 64, 160, 256, 352, 448, 8, 104, 200, 296, 392, 40, 136, 232, 328, 424, 72, 168, 264, 360, 456, 16, 112, 208, 304, 400, 48, 144, 240, 336, 432,
80, 176, 272, 368, 464, 24, 120, 216, 312, 408, 56, 152, 248, 344, 440, 88, 184, 280, 376, 472, 4, 100, 196, 292, 388, 36, 132, 228, 324, 420, 68, 164, 260, 356, 452, 12, 108, 204, 300, 396,
44, 140, 236, 332, 428, 76, 172, 268, 364, 460, 20, 116, 212, 308, 404, 52, 148, 244, 340, 436, 84, 180, 276, 372, 468, 28, 124, 220, 316, 412, 60, 156, 252, 348, 444, 92, 188, 284, 380, 476,
1, 97, 193, 289, 385, 33, 129, 225, 321, 417, 65, 161, 257, 353, 449, 9, 105, 201, 297, 393, 41, 137, 233, 329, 425, 73, 169, 265, 361, 457, 17, 113, 209, 305, 401, 49, 145, 241, 337, 433,
81, 177, 273, 369, 465, 25, 121, 217, 313, 409, 57, 153, 249, 345, 441, 89, 185, 281, 377, 473, 5, 101, 197, 293, 389, 37, 133, 229, 325, 421, 69, 165, 261, 357, 453, 13, 109, 205, 301, 397,
45, 141, 237, 333, 429, 77, 173, 269, 365, 461, 21, 117, 213, 309, 405, 53, 149, 245, 341, 437, 85, 181, 277, 373, 469, 29, 125, 221, 317, 413, 61, 157, 253, 349, 445, 93, 189, 285, 381, 477,
2, 98, 194, 290, 386, 34, 130, 226, 322, 418, 66, 162, 258, 354, 450, 10, 106, 202, 298, 394, 42, 138, 234, 330, 426, 74, 170, 266, 362, 458, 18, 114, 210, 306, 402, 50, 146, 242, 338, 434,
82, 178, 274, 370, 466, 26, 122, 218, 314, 410, 58, 154, 250, 346, 442, 90, 186, 282, 378, 474, 6, 102, 198, 294, 390, 38, 134, 230, 326, 422, 70, 166, 262, 358, 454, 14, 110, 206, 302, 398,
46, 142, 238, 334, 430, 78, 174, 270, 366, 462, 22, 118, 214, 310, 406, 54, 150, 246, 342, 438, 86, 182, 278, 374, 470, 30, 126, 222, 318, 414, 62, 158, 254, 350, 446, 94, 190, 286, 382, 478,
3, 99, 195, 291, 387, 35, 131, 227, 323, 419, 67, 163, 259, 355, 451, 11, 107, 203, 299, 395, 43, 139, 235, 331, 427, 75, 171, 267, 363, 459, 19, 115, 211, 307, 403, 51, 147, 243, 339, 435,
83, 179, 275, 371, 467, 27, 123, 219, 315, 411, 59, 155, 251, 347, 443, 91, 187, 283, 379, 475, 7, 103, 199, 295, 391, 39, 135, 231, 327, 423, 71, 167, 263, 359, 455, 15, 111, 207, 303, 399,
47, 143, 239, 335, 431, 79, 175, 271, 367, 463, 23, 119, 215, 311, 407, 55, 151, 247, 343, 439, 87, 183, 279, 375, 471, 31, 127, 223, 319, 415, 63, 159, 255, 351, 447, 95, 191, 287, 383, 479,
};
static const int16_t fft_bitrev240[240] = {
0, 48, 96, 144, 192, 16, 64, 112, 160, 208, 32, 80, 128, 176, 224, 4, 52, 100, 148, 196, 20, 68, 116, 164, 212, 36, 84, 132, 180, 228, 8, 56, 104, 152, 200, 24, 72, 120, 168, 216,
40, 88, 136, 184, 232, 12, 60, 108, 156, 204, 28, 76, 124, 172, 220, 44, 92, 140, 188, 236, 1, 49, 97, 145, 193, 17, 65, 113, 161, 209, 33, 81, 129, 177, 225, 5, 53, 101, 149, 197,
21, 69, 117, 165, 213, 37, 85, 133, 181, 229, 9, 57, 105, 153, 201, 25, 73, 121, 169, 217, 41, 89, 137, 185, 233, 13, 61, 109, 157, 205, 29, 77, 125, 173, 221, 45, 93, 141, 189, 237,
2, 50, 98, 146, 194, 18, 66, 114, 162, 210, 34, 82, 130, 178, 226, 6, 54, 102, 150, 198, 22, 70, 118, 166, 214, 38, 86, 134, 182, 230, 10, 58, 106, 154, 202, 26, 74, 122, 170, 218,
42, 90, 138, 186, 234, 14, 62, 110, 158, 206, 30, 78, 126, 174, 222, 46, 94, 142, 190, 238, 3, 51, 99, 147, 195, 19, 67, 115, 163, 211, 35, 83, 131, 179, 227, 7, 55, 103, 151, 199,
23, 71, 119, 167, 215, 39, 87, 135, 183, 231, 11, 59, 107, 155, 203, 27, 75, 123, 171, 219, 43, 91, 139, 187, 235, 15, 63, 111, 159, 207, 31, 79, 127, 175, 223, 47, 95, 143, 191, 239,
};
static const int16_t fft_bitrev120[120] = {
0, 24, 48, 72, 96, 8, 32, 56, 80, 104, 16, 40, 64, 88, 112, 4, 28, 52, 76, 100, 12, 36, 60, 84, 108, 20, 44, 68, 92, 116, 1, 25, 49, 73, 97, 9, 33, 57, 81, 105,
17, 41, 65, 89, 113, 5, 29, 53, 77, 101, 13, 37, 61, 85, 109, 21, 45, 69, 93, 117, 2, 26, 50, 74, 98, 10, 34, 58, 82, 106, 18, 42, 66, 90, 114, 6, 30, 54, 78, 102,
14, 38, 62, 86, 110, 22, 46, 70, 94, 118, 3, 27, 51, 75, 99, 11, 35, 59, 83, 107, 19, 43, 67, 91, 115, 7, 31, 55, 79, 103, 15, 39, 63, 87, 111, 23, 47, 71, 95, 119,
};
static const int16_t fft_bitrev60[60] = {
0, 12, 24, 36, 48, 4, 16, 28, 40, 52, 8, 20, 32, 44, 56, 1, 13, 25, 37, 49, 5, 17, 29, 41, 53, 9, 21, 33, 45, 57,
2, 14, 26, 38, 50, 6, 18, 30, 42, 54, 10, 22, 34, 46, 58, 3, 15, 27, 39, 51, 7, 19, 31, 43, 55, 11, 23, 35, 47, 59,
};
static const uint8_t LOG2_FRAC_TABLE[24] = {0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37};
/* Mean energy in each band quantized in Q4 */
static const signed char eMeans[25] = {103, 100, 92, 85, 81, 77, 72, 70, 78, 75, 73, 71, 78, 74, 69, 72, 70, 74, 76, 71, 60, 60, 60, 60, 60};
/* prediction coefficients: 0.9, 0.8, 0.65, 0.5 */
static const int16_t pred_coef[4] = {29440, 26112, 21248, 16384};
static const int16_t beta_coef[4] = {30147, 22282, 12124, 6554};
static const int16_t beta_intra = 4915;
/*Parameters of the Laplace-like probability models used for the coarse energy. There is one pair of parameters for
each frame size, prediction type (inter/intra), and band number. The first number of each pair is the probability
of 0, and the second is the decay rate, both in Q8 precision.*/
static const uint8_t e_prob_model[4][2][42] = {
/*120 sample frames.*/
{/*Inter*/
{72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, 116, 41, 115, 40, 114, 40, 132, 26, 132, 26, 145, 17, 161, 12, 176, 10, 177, 11},
/*Intra*/
{24, 179, 48, 138, 54, 135, 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, 100, 59, 108, 50, 120, 40, 122, 37, 97, 43, 78, 50}},
/*240 sample frames.*/
{/*Inter*/
{83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, 93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, 178, 7, 189, 6, 190, 8, 177, 9},
/*Intra*/
{23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, 138, 35, 133, 31, 97, 38, 77, 45}},
/*480 sample frames.*/
{/*Inter*/
{61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, 155, 14, 159, 16, 158, 18, 170, 13, 177, 10, 187, 8, 192, 6, 175, 9, 159, 10},
/*Intra*/
{21, 178, 59, 110, 71, 86, 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56, 129, 51, 132, 40, 150, 33, 140, 29, 98, 35, 77, 42}},
/*960 sample frames.*/
{/*Inter*/
{42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, 120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, 16, 184, 13, 184, 10, 150, 13, 139, 15},
/*Intra*/
{22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, 157, 32, 145, 29, 97, 33, 77, 40}}};
static const uint8_t small_energy_icdf[3] = {2, 1, 0};
/* TF change table. Positive values mean better frequency resolution (longer effective window), whereas negative values mean better time resolution (shorter effective window).
The second index is computed as: 4*isTransient + 2*tf_select + per_band_flag */
static const int8_t tf_select_table[4][8] = {
/*isTransient=0 isTransient=1 */
{0, -1, 0, -1, 0, -1, 0, -1}, /* 2.5 ms */
{0, -1, 0, -2, 1, 0, 1, -1}, /* 5 ms */
{0, -2, 0, -3, 2, 0, 1, -1}, /* 10 ms */
{0, -2, 0, -3, 3, 0, 1, -1}, /* 20 ms */
};
/* Indexing table for converting from natural Hadamard to ordery Hadamarangedec-> This is essentially a bit-reversed Gray,
on top of which we've added an inversion of the order because we want the DC at the end rather than the beginning.
The lines are for N=2, 4, 8, 16 */
static const int32_t ordery_table[30] = {
1, 0, 3, 0, 2, 1, 7, 0, 4, 3, 6, 1, 5, 2, 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5,
};
static const int32_t second_check[16] = {0, 0, 3, 2, 3, 2, 5, 2, 3, 2, 3, 2, 5, 2, 3, 2};
static const uint8_t trim_icdf[11] = {126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0};
/* Probs: NONE: 21.875%, LIGHT: 6.25%, NORMAL: 65.625%, AGGRESSIVE: 6.25% */
static const uint8_t spread_icdf[4] = {25, 23, 2, 0};
static const uint8_t tapset_icdf[3] = {2, 1, 0};
static const uint32_t row_idx[15] = {0, 176, 351, 525, 698, 870, 1041, 1131, 1178, 1207, 1226, 1240, 1248, 1254, 1257};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,228 @@
// based on Xiph.Org Foundation celt decoder
#pragma once
#include "../Audio.h"
#include "../psram_unique_ptr.hpp"
#include "celt.h"
#include "range_decoder.h"
#include "silk.h"
#include <vector>
#define ANSI_ESC_RESET "\033[0m"
#define ANSI_ESC_BLACK "\033[30m"
#define ANSI_ESC_RED "\033[31m"
#define ANSI_ESC_GREEN "\033[32m"
#define ANSI_ESC_YELLOW "\033[33m"
#define ANSI_ESC_BLUE "\033[34m"
#define ANSI_ESC_MAGENTA "\033[35m"
#define ANSI_ESC_CYAN "\033[36m"
#define ANSI_ESC_WHITE "\033[37m"
class OpusDecoder : public Decoder {
public:
OpusDecoder(Audio& audioRef)
: Decoder(audioRef), rangedec(std::make_unique<RangeDecoder>()), silkdec(std::make_unique<SilkDecoder>(*rangedec)), celtdec(std::make_unique<CeltDecoder>(*rangedec)), audio(audioRef) {}
~OpusDecoder() { reset(); }
bool init() override;
void clear() override;
void reset() override;
bool isValid() override;
int32_t findSyncWord(uint8_t* buf, int32_t nBytes) override;
uint8_t getChannels() override;
uint32_t getSampleRate() override;
uint32_t getOutputSamples();
uint8_t getBitsPerSample() override;
uint32_t getBitRate() override;
uint32_t getAudioDataStart() override;
uint32_t getAudioFileDuration() override;
const char* getStreamTitle() override;
const char* whoIsIt() override;
int32_t decode(uint8_t* inbuf, int32_t* bytesLeft, int32_t* outbuf) override;
void setRawBlockParams(uint8_t channels, uint32_t sampleRate, uint8_t BPS, uint32_t tsis, uint32_t AuDaLength) override;
std::vector<uint32_t> getMetadataBlockPicture() override;
const char* arg1() override;
const char* arg2() override;
virtual int32_t val1() override;
virtual int32_t val2() override;
std::unique_ptr<RangeDecoder> rangedec;
std::unique_ptr<SilkDecoder> silkdec;
std::unique_ptr<CeltDecoder> celtdec;
enum : int8_t { OPUS_END = 120, OPUS_CONTINUE = 10, OPUS_PARSE_OGG_DONE = 100, OPUS_NONE = 0, OPUS_ERR = -1 };
private:
Audio& audio;
typedef struct _ofp2 {
uint16_t firstFrameLength{};
uint16_t secondFrameLength{};
void reset() {
*this = _ofp2{}; // sauber neu initialisieren
}
} ofp2_t;
typedef struct _ofp3 { // opus_FramePacking_Code
bool firstCall{};
bool v{}; // VBR indicator
bool p{}; // padding exists
int16_t fs{}; // frame size
uint8_t M{}; // nr of frames
int32_t spf{}; // samples per frame
int32_t paddingLength{};
uint16_t c1fs{};
uint16_t vfs[48]{}; // variable frame size
uint32_t idx{};
void reset() {
*this = _ofp3{}; // sauber neu initialisieren
}
} ofp3_t;
typedef struct _odp3 {
int8_t configNr{};
uint16_t samplesPerFrame{};
void reset() {
// Default-initialize alles neu (inklusive Array)
*this = _odp3{};
}
} odp3_t;
#define CELT_SET_END_BAND_REQUEST 10012
#define CELT_SET_CHANNELS_REQUEST 10008
#define CELT_SET_START_BAND_REQUEST 10010
#define CELT_SET_SIGNALLING_REQUEST 10016
#define CELT_GET_AND_CLEAR_ERROR_REQUEST 10007
#define CELT_GET_MODE_REQUEST 10015
enum { OPUS_BANDWIDTH_NARROWBAND = 1101, OPUS_BANDWIDTH_MEDIUMBAND = 1102, OPUS_BANDWIDTH_WIDEBAND = 1103, OPUS_BANDWIDTH_SUPERWIDEBAND = 1104, OPUS_BANDWIDTH_FULLBAND = 1105 };
enum ParseResult { OPUS_COMMENT_INVALID = -1, OPUS_COMMENT_NEED_MORE = 1, OPUS_COMMENT_DONE = 2 };
uint8_t m_opusChannels = 0;
uint8_t m_opusCountCode = 0;
uint8_t m_opusPageNr = 0;
uint8_t m_frameCount = 0;
uint8_t m_opusSegmentTableSize = 0;
uint16_t m_mode = 0;
uint16_t m_opusOggHeaderSize = 0;
uint16_t m_bandWidth = 0;
uint16_t m_internalSampleRate = 0;
uint16_t m_endband = 0;
uint32_t m_opusSamplerate = 0;
uint32_t m_opusSegmentLength = 0;
uint32_t m_opusCurrentFilePos = 0;
uint32_t m_opusAudioDataStart = 0;
uint32_t m_opusBlockPicPos = 0;
uint32_t m_opusBlockLen = 0;
bool m_f_opusParseOgg = false;
bool m_f_newSteamTitle = false; // streamTitle
bool m_f_opusNewMetadataBlockPicture = false; // new metadata block picture
bool m_f_opusStereoFlag = false;
bool m_f_continuedPage = false;
bool m_f_firstPage = false;
bool m_f_lastPage = false;
bool m_f_nextChunk = false;
bool m_isValid = false;
int8_t m_opusError = 0;
int16_t m_opusSegmentTableRdPtr = -1;
int16_t m_prev_mode = 0;
int32_t m_opusValidSamples = 0;
int32_t m_opusBlockPicLen = 0;
int32_t m_blockPicLenUntilFrameEnd = 0;
int32_t m_opusRemainBlockPicLen = 0;
int32_t m_opusCommentBlockSize = 0;
float m_opusCompressionRatio = 0;
ps_ptr<int16_t> m_out16;
struct picture_segment_t {
uint32_t start_page_index{};
uint32_t start_offset{};
uint32_t end_page_index{};
uint32_t end_offset{};
bool in_progress{};
};
typedef struct _comment {
uint32_t pointer{};
uint32_t list_length{};
bool oob{}; // out of bounds (block overflow)
uint32_t save_len{};
uint32_t comment_size{};
uint32_t start_pos{}; // comment start file position
uint32_t end_pos{}; // comment end file position
uint8_t length_bytes[4]{}; // 🆕 Addition for split 4-byte length fields
uint8_t partial_length{}; // how many of the 4 bytes have already been read
uint32_t bytes_available{};
ps_ptr<char> stream_title{};
ps_ptr<char> comment_content{};
std::vector<uint32_t> item_vec;
std::vector<uint32_t> pic_vec;
void reset() { *this = _comment{}; }
} comment_t;
comment_t m_comment;
ps_ptr<uint16_t> m_opusSegmentTable;
ofp2_t m_ofp2; // used in opus_FramePacking_Code2
ofp3_t m_ofp3; // used in opus_FramePacking_Code3
odp3_t m_odp3; // used in opusDecodePage3
std::vector<uint32_t> m_opusBlockPicItem;
void OPUSsetDefaults();
int32_t opusDecodePage0(uint8_t* inbuf, int32_t* bytesLeft, uint32_t segmentLength);
int32_t opusDecodePage3(uint8_t* inbuf, int32_t* bytesLeft, uint32_t segmentLength, int16_t* outbuf);
int8_t opus_FramePacking_Code0(uint8_t* inbuf, int32_t* bytesLeft, int16_t* outbuf, int32_t packetLen, uint16_t samplesPerFrame);
int8_t opus_FramePacking_Code1(uint8_t* inbuf, int32_t* bytesLeft, int16_t* outbuf, int32_t packetLen, uint16_t samplesPerFrame, uint8_t* frameCount);
int8_t opus_FramePacking_Code2(uint8_t* inbuf, int32_t* bytesLeft, int16_t* outbuf, int32_t packetLen, uint16_t samplesPerFrame, uint8_t* frameCount);
int8_t opus_FramePacking_Code3(uint8_t* inbuf, int32_t* bytesLeft, int16_t* outbuf, int32_t packetLen, uint16_t samplesPerFrame, uint8_t* frameCount);
int32_t parseOGG(uint8_t* inbuf, int32_t* bytesLeft);
int32_t parseOpusHead(uint8_t* inbuf, int32_t nBytes);
int32_t parseOpusComment(uint8_t* inbuf, int32_t nBytes, uint32_t current_file_pos);
int8_t parseOpusTOC(uint8_t TOC_Byte);
int32_t opus_packet_get_samples_per_frame(const uint8_t* data, int32_t Fs);
int32_t opus_decode_frame(uint8_t* inbuf, int16_t* outbuf, int32_t packetLen, uint16_t samplesPerFrame);
// some helper functions
int32_t OPUS_specialIndexOf(uint8_t* base, const char* str, int32_t baselen, bool exact = false);
int32_t OPUS_specialIndexOf_icase(uint8_t* base, const char* str, int32_t baselen, bool exact = false);
uint32_t little_endian(uint8_t* data);
enum { MODE_NONE = 0, MODE_SILK_ONLY = 1000, MODE_HYBRID = 1001, MODE_CELT_ONLY = 1002 };
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// Macro for comfortable calls
#define OPUS_LOG_ERROR(fmt, ...) Audio::AUDIO_LOG_IMPL(1, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define OPUS_LOG_WARN(fmt, ...) Audio::AUDIO_LOG_IMPL(2, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define OPUS_LOG_INFO(fmt, ...) Audio::AUDIO_LOG_IMPL(3, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define OPUS_LOG_DEBUG(fmt, ...) Audio::AUDIO_LOG_IMPL(4, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
#define OPUS_LOG_VERBOSE(fmt, ...) Audio::AUDIO_LOG_IMPL(5, __FILE__, __LINE__, __func__, fmt, ##__VA_ARGS__)
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// Macro for time measuring
// PROFILE_START(decodeNative);
// ret = decodeNative(inbuf, bytesLeft, outbuf);
// PROFILE_END_N(decodeNative, 1000);
#define PROFILE_START(name) \
static uint64_t _prof_##name##_start = 0; \
_prof_##name##_start = esp_timer_get_time()
#define PROFILE_END_N(name, N) \
do { \
static uint64_t _prof_##name##_sum = 0; \
static uint32_t _prof_##name##_count = 0; \
uint64_t _prof_##name##_elapsed = esp_timer_get_time() - _prof_##name##_start; \
_prof_##name##_sum += _prof_##name##_elapsed; \
_prof_##name##_count++; \
if (_prof_##name##_count >= (N)) { \
printf("%-20s avg: %.2f µs over %u runs\n", #name, (double)_prof_##name##_sum / _prof_##name##_count, _prof_##name##_count); \
_prof_##name##_sum = 0; \
_prof_##name##_count = 0; \
} \
} while (0)
};
// —————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

View File

@@ -0,0 +1,223 @@
#include "range_decoder.h"
RangeDecoder::RangeDecoder() : m_buf(nullptr) {}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/* This is a faster version of ec_tell_frac() that takes advantage of the low (1/8 bit) resolution to use just a linear function followed by a lookup to determine the exact transition thresholds. */
uint32_t RangeDecoder::tell_frac() {
const uint32_t correction[8] = {35733, 38967, 42495, 46340, 50535, 55109, 60097, 65535};
uint32_t nbits;
uint32_t r;
int32_t l;
uint32_t b;
nbits = m_nbits_total << EC_BITRES;
l = EC_ILOG(m_rng);
r = m_rng >> (l - 16);
b = (r >> 12) - 8;
b += r > correction[b];
l = (l << 3) + b;
return nbits - l;
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
int32_t RangeDecoder::read_byte() { return m_offs < m_storage ? m_buf[m_offs++] : 0; }
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
int32_t RangeDecoder::read_byte_from_end() {
return m_end_offs < m_storage ? m_buf[m_storage - ++(m_end_offs)] : 0;
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/*Normalizes the contents of val and rng so that rng lies entirely in the high-order symbol.*/
void RangeDecoder::dec_normalize() {
/*If the range is too small, rescale it and input some bits.*/
while (m_rng <= EC_CODE_BOT) {
int32_t sym;
m_nbits_total += EC_SYM_BITS;
m_rng <<= EC_SYM_BITS;
/*Use up the remaining bits from our last symbol.*/
sym = m_rem;
/*Read the next value from the input.*/
m_rem = read_byte();
/*Take the rest of the bits we need from this new symbol.*/
sym = (sym << EC_SYM_BITS | m_rem) >> (EC_SYM_BITS - EC_CODE_EXTRA);
/*And subtract them from val, capped to be less than EC_CODE_TOP.*/
m_val = ((m_val << EC_SYM_BITS) + (EC_SYM_MAX & ~sym)) & ((EC_CODE_TOP) - 1);
}
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
void RangeDecoder::dec_init(uint8_t *_buf, uint32_t _storage) {
m_buf = _buf;
m_storage = _storage;
m_end_offs = 0;
m_end_window = 0;
m_nend_bits = 0;
m_nbits_total = EC_CODE_BITS + 1 - ((EC_CODE_BITS - EC_CODE_EXTRA) / EC_SYM_BITS) * EC_SYM_BITS;
m_offs = 0;
m_rng = 1U << EC_CODE_EXTRA;
m_rem = read_byte();
m_val = m_rng - 1 - (m_rem >> (EC_SYM_BITS - EC_CODE_EXTRA));
m_error = 0;
/*Normalize the interval.*/
dec_normalize();
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint32_t RangeDecoder::decode(uint32_t _ft) {
uint32_t s;
m_ext = m_rng / _ft;
s = (uint32_t)(m_val / m_ext);
return _ft - EC_MINI(s + 1, _ft);
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint32_t RangeDecoder::decode_bin(uint32_t _bits) {
uint32_t s;
m_ext = m_rng >> _bits;
s = (uint32_t)(m_val / m_ext);
return (1U << _bits) - EC_MINI(s + 1U, 1U << _bits);
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
void RangeDecoder::dec_update(uint32_t _fl, uint32_t _fh, uint32_t _ft) {
uint32_t s;
s = m_ext * (_ft - _fh);
m_val -= s;
if(_fl > 0){
m_rng = m_ext * (_fh - _fl);
}
else{
m_rng = m_rng - s;
}
dec_normalize();
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/*The probability of having a "one" is 1/(1<<_logp).*/
int32_t RangeDecoder::dec_bit_logp( uint32_t _logp) {
uint32_t r;
uint32_t d;
uint32_t s;
int32_t ret;
r = m_rng;
d = m_val;
s = r >> _logp;
ret = d < s;
if (!ret) m_val = d - s;
m_rng = ret ? s : r - s;
dec_normalize();
return ret;
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
int32_t RangeDecoder::dec_icdf(const uint8_t *_icdf, uint32_t _ftb) {
uint32_t r;
uint32_t d;
uint32_t s;
uint32_t t;
int32_t ret;
s = m_rng;
d = m_val;
r = s >> _ftb;
ret = -1;
do {
t = s;
s = r * _icdf[++ret];
} while (d < s);
m_val = d - s;
m_rng = t - s;
dec_normalize();
return ret;
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint32_t RangeDecoder::dec_uint(uint32_t _ft) {
uint32_t ft;
uint32_t s;
int32_t ftb;
/*In order to optimize EC_ILOG(), it is undefined for the value 0.*/
assert(_ft > 1);
_ft--;
ftb = EC_ILOG(_ft);
if (ftb > EC_UINT_BITS) {
uint32_t t;
ftb -= EC_UINT_BITS;
ft = (uint32_t)(_ft >> ftb) + 1;
s = decode(ft);
dec_update(s, s + 1, ft);
t = (uint32_t)s << ftb | dec_bits(ftb);
if (t <= _ft) return t;
m_error = 1;
return _ft;
} else {
_ft++;
s = decode((uint32_t)_ft);
dec_update(s, s + 1, (uint32_t)_ft);
return s;
}
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
uint32_t RangeDecoder::dec_bits(uint32_t _bits) {
uint32_t window;
int32_t available;
uint32_t ret;
window = m_end_window;
available = m_nend_bits;
if ((uint32_t)available < _bits) {
do {
window |= (uint32_t)read_byte_from_end() << available;
available += EC_SYM_BITS;
} while (available <= EC_WINDOW_SIZE - EC_SYM_BITS);
}
ret = (uint32_t)window & (((uint32_t)1 << _bits) - 1U);
window >>= _bits;
available -= _bits;
m_end_window = window;
m_nend_bits = available;
m_nbits_total += _bits;
return ret;
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
int32_t RangeDecoder::tell(){return m_nbits_total-EC_ILOG(m_rng);}
void RangeDecoder::add_nbits_total(int32_t nbits_total){m_nbits_total += nbits_total;}
uint32_t RangeDecoder::get_storage(){return m_storage;}
int32_t RangeDecoder::get_error(){return m_error;}
uint32_t RangeDecoder::get_rng(){return m_rng;}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/* When called, decay is positive and at most 11456. */
uint32_t RangeDecoder::laplace_get_freq1(uint32_t fs0, int32_t decay) {
uint32_t ft;
ft = 32768 - LAPLACE_MINP * (2 * LAPLACE_NMIN) - fs0;
return ft * (int32_t)(16384 - decay) >> 15;
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
int32_t RangeDecoder::laplace_decode(uint32_t fs, int32_t decay) {
int32_t val = 0;
uint32_t fl;
uint32_t fm;
fm = decode_bin(15);
fl = 0;
if (fm >= fs) {
val++;
fl = fs;
fs = laplace_get_freq1(fs, decay) + LAPLACE_MINP;
/* Search the decaying part of the PDF.*/
while (fs > LAPLACE_MINP && fm >= fl + 2 * fs) {
fs *= 2;
fl += fs;
fs = ((fs - 2 * LAPLACE_MINP) * (int32_t)decay) >> 15;
fs += LAPLACE_MINP;
val++;
}
/* Everything beyond that has probability LAPLACE_MINP. */
if (fs <= LAPLACE_MINP) {
int32_t di;
di = (fm - fl) >> (LAPLACE_LOG_MINP + 1);
val += di;
fl += 2 * di * LAPLACE_MINP;
}
if (fm < fl + fs)
val = -val;
else
fl += fs;
}
assert(fl < 32768);
assert(fs > 0);
assert(fl <= fm);
assert(fm < min((uint32_t)(fl + fs), (uint32_t)32768));
dec_update(fl, min((uint32_t)(fl + fs), (uint32_t)32768), (uint32_t)32768);
return val;
}

Some files were not shown because too many files have changed in this diff Show More