3 Commits
Author SHA1 Message Date
Claude 00cdf2240f Center the Art view, theme the scrollbars, single-zip downloads
The editing area now centers in wide windows instead of hugging the app
list, scrollbars match the app instead of Chrome's grey ones, and the
build artifact holds the PSGFX folder directly (GitHub already zips it).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019sEKffq7xSxkEwHu87bM8X
2026-10-11 18:10:36 +00:00
Claude 9a69f98f89 Play the music: point app.db's snd0Info at it; add icon presets
The home screen only plays a title's music when its app.db row names
the file in snd0Info, which the PS5 fills in at install time and leaves
empty for apps installed without music. Homebrew now gets snd0Info set
to /user/app/<id>/sce_sys/snd0.at9 (as the PS5 does for apps that ship
music), and games with no music entry get one pointing at the uploaded
file. Restore clears it again.

Also adds built-in icon presets for a few apps, offered in the Art view
when the selected title matches.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019sEKffq7xSxkEwHu87bM8X
2026-10-11 17:52:08 +00:00
Claude 217d17db2c Home-screen music: turn an MP3, WAV or FLAC into snd0.at9 (1.3)
A Music slot in the Art view takes a song, lets you pick where the clip
starts and how long it runs (up to the 2 MiB the PS5 allows, about 85 s),
and plays a preview. Apply writes snd0.at9 (ATRAC9 48 kHz stereo,
192 kb/s, looped) to sce_sys for homebrew and /user/appmeta for games,
with pubtools.loudnessSnd0 in param.json; when app.db has a snd0 path
column pointing elsewhere it is repointed as game art is. Restore
removes or restores it like art.

The encoder is a C++ port of PS5 AT9 Converter (BlackBearReloaded,
GPL-3.0-or-later), checked against its Python CLI: same audio after
decoding for every test input, byte-identical for most. Audio files are
read with minimp3, dr_wav and dr_flac. Because of the encoder, PSGFX
is now GPL-3.0-or-later.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019sEKffq7xSxkEwHu87bM8X
2026-10-11 17:35:13 +00:00
53 changed files with 62593 additions and 60 deletions

No files matched your search

+2 -1
View File
@@ -29,10 +29,11 @@ jobs:
cp release/HOW-TO.txt dist/PSGFX/
cd dist && zip -r PSGFX-windows.zip PSGFX
# GitHub zips artifacts itself, so upload the folder: one zip to open, not a zip in a zip.
- uses: actions/upload-artifact@v4
with:
name: PSGFX-windows
path: dist/PSGFX-windows.zip
path: dist/PSGFX
- name: Attach to release
if: startsWith(github.ref, 'refs/tags/v')
+671 -17
View File
@@ -1,21 +1,675 @@
MIT License
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (c) 2026 Ruben
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.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Preamble
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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>.
THE SOFTWARE IS PROVIDED "AS IS", 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
AUTHORS OR COPYRIGHT HOLDERS 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.
+6 -4
View File
@@ -18,8 +18,9 @@ It works through [PS5 Upload](https://github.com/phantomptr/ps5upload): keep the
- **Custom backgrounds.** Any 16:9 image becomes the backdrop behind the app on the home screen. Homebrew gets full 4K backgrounds.
- **Homebrew and installed games.** Homebrew apps registered with PS5 Upload show up with their icons, and so do your installed PS4 and PS5 games, with their real names.
- **Live preview.** A replica of the PS5 home screen shows your art before anything touches the console. Drop an image on the tile to set the icon, or anywhere else to set the background.
- **Home-screen music (new in 1.3).** Drop an MP3, WAV or FLAC on an app or game, pick where the clip starts and how long it runs, and listen to it before applying. PSGFX converts it to the PS5's own format (`snd0.at9`, ATRAC9), levels it like official games, and loops it while the tile is selected. Clips can run up to about 85 seconds, the most the PS5's 2 MB limit allows.
- **Rename from the Art view.** Change a homebrew app's or game's home-screen name right next to its art. For homebrew, PSGFX also updates the name in the app's `param.json` so changing its art later keeps the new name.
- **One-click restore.** The first time you change something, PSGFX saves the original next to it. **Restore original art** puts it back exactly.
- **One-click restore.** The first time you change something, PSGFX saves the original next to it. **Restore original** puts it back exactly.
- **Clean list.** System apps and leftovers are tucked away under *Show other items*.
- **Home layout (new in 1.1).** Hide any tile (PlayStation Store, Game Library, PS Plus, media apps), rename games and apps, move apps between the Games and Media tabs, and reorder your games by dragging or with A–Z / Z–A.
- **Lock order.** Keeps your arrangement in place even after you play other games.
@@ -43,7 +44,7 @@ It works through [PS5 Upload](https://github.com/phantomptr/ps5upload): keep the
6. Close that app or game on the PS5, then click **Apply to PS5**.
7. Restart the PS5 to see the new art on the home screen.
To undo, select the app and click **Restore original art**.
To undo, select the app and click **Restore original**.
### Home layout
@@ -82,7 +83,7 @@ On Windows, run `./build.sh` from an [MSYS2](https://www.msys2.org/) MinGW shell
### How it works
PSGFX runs a small local web server (127.0.0.1 only) and opens your browser to it. PS5 Upload 6.0 replaced its old protocol (FTX2, ports 9113 and 9114) with AVA1, an encrypted connection on port 9120 that the console only opens to an app it has paired with. So PSGFX doesn't talk to the console itself: it sends each command to the PS5 Upload app's local engine (`POST http://127.0.0.1:19113/api/mgmt/call`), which runs it over its paired connection. It uses the payload's existing commands to list apps, read and write files, and back up. Homebrew art is written to the app's `sce_sys` folder and to the home-screen metadata folder. Game art is written to `/user/appmeta/<title id>` in the same size and format as the original files. When the home-screen database (`app.db`) shows the game's tile art coming from somewhere PSGFX can't write, such as inside the game's own package, PSGFX writes the image to `/user/appmeta/<title id>/psgfx_*` and points the database at it. It keeps the original paths in `psgfx_original.json` for **Restore original art** and backs up the database first, as Home layout does. Backgrounds are encoded as BC7 DDS where the console uses DDS.
PSGFX runs a small local web server (127.0.0.1 only) and opens your browser to it. PS5 Upload 6.0 replaced its old protocol (FTX2, ports 9113 and 9114) with AVA1, an encrypted connection on port 9120 that the console only opens to an app it has paired with. So PSGFX doesn't talk to the console itself: it sends each command to the PS5 Upload app's local engine (`POST http://127.0.0.1:19113/api/mgmt/call`), which runs it over its paired connection. It uses the payload's existing commands to list apps, read and write files, and back up. Homebrew art is written to the app's `sce_sys` folder and to the home-screen metadata folder. Game art is written to `/user/appmeta/<title id>` in the same size and format as the original files. When the home-screen database (`app.db`) shows the game's tile art coming from somewhere PSGFX can't write, such as inside the game's own package, PSGFX writes the image to `/user/appmeta/<title id>/psgfx_*` and points the database at it. It keeps the original paths in `psgfx_original.json` for **Restore original** and backs up the database first, as Home layout does. Backgrounds are encoded as BC7 DDS where the console uses DDS. Music becomes `snd0.at9` (ATRAC9, 48 kHz stereo, 192 kb/s, looped), written to the app's `sce_sys` folder for homebrew and to `/user/appmeta/<title id>` for games, with its loudness in `param.json` (`pubtools.loudnessSnd0`).
`tools/mock_engine.py` is a stand-in for the PS5 Upload engine and console that serves a folder on your computer as if it were a PS5. Use it to develop without a console:
@@ -96,10 +97,11 @@ If PS5 Upload's engine runs somewhere else (a NAS or Docker), add `"engine": "ho
## Credits
- [PS5 Upload](https://github.com/phantomptr/ps5upload) by phantomptr, whose app and payload PSGFX works through
- [PS5 AT9 Converter](https://github.com/blackbearreloaded/ps5-at9-converter) by BlackBearReloaded, whose ATRAC9 encoder PSGFX's music feature is ported from, and [LibAtrac9](https://github.com/Thealexbarney/LibAtrac9) by Alex Barney
- [bc7enc](https://github.com/richgel999/bc7enc) by Rich Geldreich, [stb](https://github.com/nothings/stb) by Sean Barrett, [BLAKE3](https://github.com/BLAKE3-team/BLAKE3), [JSON for Modern C++](https://github.com/nlohmann/json) by Niels Lohmann, and the [Sora](https://github.com/sora-xor/sora-font) typeface. See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
## License
[MIT](LICENSE).
PSGFX is free software under the [GNU General Public License v3.0 or later](LICENSE). Versions up to 1.2 were released under the MIT License; 1.3 moved to the GPL because it includes the ATRAC9 encoder from [PS5 AT9 Converter](https://github.com/blackbearreloaded/ps5-at9-converter), which is GPL-3.0-or-later.
PSGFX is an independent fan project. It is not affiliated with, endorsed by, or sponsored by Sony Interactive Entertainment. "PlayStation" and "PS5" are trademarks of Sony Interactive Entertainment Inc. Only use PSGFX with games you own.
+3
View File
@@ -8,6 +8,9 @@ PSGFX includes the following components. Their full license texts are in the hea
| stb_image, stb_image_write, stb_image_resize2 by Sean Barrett | `src/lib/stb_*.h` | MIT or public domain |
| BLAKE3 reference implementation | `src/lib/blake3*` | CC0 1.0 or Apache 2.0 |
| JSON for Modern C++ by Niels Lohmann | `src/lib/json.hpp` | MIT |
| PS5 AT9 Converter by BlackBearReloaded (ATRAC9 encoder and audio processing, ported to C++) | `src/lib/at9/` | GPL-3.0-or-later |
| LibAtrac9 by Alex Barney (ATRAC9 tables) | `src/lib/at9/` | MIT |
| minimp3, dr_wav, dr_flac (audio decoding) | `src/lib/at9/`, see `src/lib/at9/NOTICES.md` | CC0 / public domain or MIT-0 |
| Sora typeface, The Sora Project Authors | `assets/fonts/*.woff2` (embedded in `src/assets_embed.cpp`) | SIL Open Font License 1.1, see `assets/fonts/OFL.txt` |
PSGFX talks to the payload of [PS5 Upload](https://github.com/phantomptr/ps5upload) over the network. It does not include any PS5 Upload code.
Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

+1 -1
View File
@@ -9,7 +9,7 @@ mkdir -p build
BLAKE3_FLAGS="-O2 -DBLAKE3_NO_SSE2 -DBLAKE3_NO_SSE41 -DBLAKE3_NO_AVX2 -DBLAKE3_NO_AVX512"
SQLITE_FLAGS="-O2 -DSQLITE_THREADSAFE=1 -DSQLITE_OMIT_LOAD_EXTENSION -DSQLITE_DEFAULT_MEMSTATUS=0"
SOURCES="src/main.cpp src/ui.cpp src/assets_embed.cpp src/lib/bc7enc.cpp src/lib/bc7decomp.cpp"
SOURCES="src/main.cpp src/ui.cpp src/assets_embed.cpp src/lib/bc7enc.cpp src/lib/bc7decomp.cpp src/presets_embed.cpp src/lib/at9/at9_encoder.cpp src/lib/at9/at9_snd0.cpp src/lib/at9/at9_decode.cpp src/lib/at9/at9_tables.cpp"
if [[ "${1:-}" == "linux" ]]; then
for f in src/lib/blake3.c src/lib/blake3_dispatch.c src/lib/blake3_portable.c; do
+7 -2
View File
@@ -1,4 +1,4 @@
PSGFX 1.2
PSGFX 1.3
Custom icons and backgrounds for your PS5 homebrew and games, and your home-screen layout.
BEFORE YOU START
@@ -18,8 +18,13 @@ STEPS
5. Close that app or game on the PS5, then click "Apply to PS5".
6. Restart the PS5 to see the new art.
MUSIC (new in 1.3)
- Drop an MP3, WAV or FLAC on the preview, or use "Choose song".
- Set where it starts and how long it runs, listen to it, then Apply.
- It plays when the app's or game's tile is selected. Restart the PS5 to hear it.
UNDO
- Select the app and click "Restore original art".
- Select the app and click "Restore original".
HOME LAYOUT (new in 1.1)
1. Connect, then click "Home layout" at the top.
+14
View File
@@ -0,0 +1,14 @@
# src/lib/at9 notices
- `at9.h`, `at9_encoder.cpp`, `at9_snd0.cpp`, `at9_decode.cpp`, `at9_internal.h`:
C++ port of [PS5 AT9 Converter](https://github.com/blackbearreloaded/ps5-at9-converter)
v0.1.0 (commit 65be0a1), Copyright (C) 2026 BlackBearReloaded, GPL-3.0-or-later.
- `at9_tables.h`, `at9_tables.cpp`: ATRAC9 constant tables (Huffman codebooks, scale factor
weights, gradient curve, band extension tables) from
[LibAtrac9](https://github.com/Thealexbarney/LibAtrac9), MIT License, Copyright (c) 2018
Alex Barney (full text in the file header). Generated by `tools/at9check/gen_tables.py`
from `ps5at9/atrac9_tables.py`.
- `minimp3.h`, `minimp3_ex.h`: [minimp3](https://github.com/lieff/minimp3) by lieff
(commit ea99364), dedicated to the public domain under CC0 1.0.
- `dr_wav.h` (v0.14.6), `dr_flac.h` (v0.13.4): [dr_libs](https://github.com/mackron/dr_libs)
by David Reid (commit dfe8377), public domain (Unlicense) or MIT No Attribution, at your choice.
+76
View File
@@ -0,0 +1,76 @@
// PS5 snd0.at9 maker: audio decoding, excerpt preparation and ATRAC9 encoding.
//
// C++ port of PS5 AT9 Converter v0.1.0 (ps5at9/{cli,dsp,at9file,atrac9,
// atrac9_encoder}.py, https://github.com/blackbearreloaded/ps5-at9-converter).
// Copyright (C) 2026 BlackBearReloaded (original Python implementation)
// C++ port: part of PSGFX.
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Input decoding uses minimp3 (CC0) and dr_wav / dr_flac (public domain or
// MIT-0); the ATRAC9 tables come from LibAtrac9 (MIT). See NOTICES.md.
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace at9 {
// Decoded audio: interleaved float samples in [-1, 1].
struct Audio {
int rate = 0;
int channels = 0;
std::vector<float> pcm;
};
// Decode MP3, WAV (PCM 8/16/24/32-bit, float; RIFF/RF64), AIFF/AIFC or FLAC.
// The format is detected from the content, like the Python tool does.
bool decode_file(const std::vector<uint8_t> &bytes, Audio &out, std::string &err);
// Defaults mirror the Python CLI (ps5_at9.py) defaults.
struct Options {
int bitrate_kbps = 192; // 72, 96, 120, 144, 168 or 192
bool loop = true; // whole-track loop (smpl chunk); CLI --no-loop sets false
double start_sec = 0; // excerpt start
double duration_sec = 15; // excerpt length; <= 0 means "max" (longest that fits 2 MiB)
double fade_in = 0.01; // seconds
double fade_out = 0.01; // seconds
double lufs = -28; // integrated loudness target (param.json loudnessSnd0)
double true_peak_db = -2; // true-peak ceiling, dBTP
bool normalize = true; // false = keep source level, only limit peaks
};
struct Result {
std::vector<uint8_t> at9; // complete snd0.at9 file
double loudness_lufs = 0; // integrated loudness of the processed excerpt (-inf if silent)
double seconds = 0; // excerpt length
std::string loudness_param; // "%.2f" of loudness_lufs: value for pubtools.loudnessSnd0
std::vector<float> processed; // what was encoded: 48 kHz interleaved stereo, after
// resample, cut, loudness, limiting and fades
};
// Whole CLI pipeline: to stereo, resample to 48 kHz, cut the excerpt, loudness
// normalise, true-peak limit, fades, ATRAC9 encode, RIFF build. Throws
// std::runtime_error (readable message) on bad options, an empty excerpt or a
// file above the 2 MiB PS5 limit.
Result make_snd0(const Audio &in, const Options &o);
// 16-bit PCM WAV of interleaved 48 kHz stereo float samples (for previews).
std::vector<uint8_t> wav_bytes(const std::vector<float> &stereo48k);
// Lower-level pieces, used by the test harness.
namespace detail {
// Same as make_snd0; optionally returns the processed excerpt in double
// precision (planar, 2 channels) and lets the caller choose the thread count
// (0 = hardware concurrency). Output bytes do not depend on the thread count.
Result make_snd0_ex(const Audio &in, const Options &o, std::vector<double> *left,
std::vector<double> *right, unsigned threads);
// ATRAC9-encode 48 kHz stereo (full scale = 1.0); returns the data chunk.
std::vector<uint8_t> encode_atrac9(const std::vector<double> &left, const std::vector<double> &right,
int bitrate_kbps, unsigned threads);
// Complete .at9 file around a data chunk.
std::vector<uint8_t> build_at9(int bitrate_kbps, uint32_t sample_count, const std::vector<uint8_t> &data,
bool loop);
} // namespace detail
} // namespace at9
+141
View File
@@ -0,0 +1,141 @@
// Input decoding for the snd0.at9 maker: MP3 (minimp3), WAV/RF64/AIFF
// (dr_wav) and FLAC (dr_flac). Format detection mirrors ps5at9/audio_io.py.
// Copyright (C) 2026 BlackBearReloaded (original Python implementation)
// SPDX-License-Identifier: GPL-3.0-or-later
#include "at9.h"
#include <cstdlib>
#include <cstring>
#define MINIMP3_IMPLEMENTATION
#define MINIMP3_FLOAT_OUTPUT
#define MINIMP3_NO_STDIO
#include "minimp3_ex.h"
#define DR_WAV_IMPLEMENTATION
#define DR_WAV_NO_STDIO
#define DR_WAV_NO_WCHAR
#include "dr_wav.h"
#define DR_FLAC_IMPLEMENTATION
#define DR_FLAC_NO_STDIO
#define DR_FLAC_NO_WCHAR
#define DR_FLAC_NO_OGG
#include "dr_flac.h"
namespace at9 {
namespace {
bool starts(const std::vector<uint8_t> &b, size_t off, const char *s) {
size_t n = std::strlen(s);
return b.size() >= off + n && std::memcmp(b.data() + off, s, n) == 0;
}
// Integer samples are scaled by 1 / 2^31 after left-justification, exactly as
// the Python reader does (16- and 24-bit input is represented exactly).
constexpr double INT_SCALE = 1.0 / 2147483648.0;
bool decode_wav(const std::vector<uint8_t> &bytes, Audio &out, std::string &err) {
drwav wav;
if (!drwav_init_memory(&wav, bytes.data(), bytes.size(), nullptr)) {
err = "could not read WAV/AIFF file";
return false;
}
bool ok = true;
if (wav.channels < 1 || wav.sampleRate < 1) {
err = "unsupported WAVE format";
ok = false;
} else {
const size_t ch = wav.channels;
const drwav_uint64 frames = wav.totalPCMFrameCount;
out.rate = (int)wav.sampleRate;
out.channels = (int)ch;
out.pcm.clear();
if (wav.translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
out.pcm.resize((size_t)frames * ch);
drwav_uint64 got = drwav_read_pcm_frames_f32(&wav, frames, out.pcm.data());
out.pcm.resize((size_t)got * ch);
} else {
std::vector<drwav_int32> tmp((size_t)frames * ch);
drwav_uint64 got = drwav_read_pcm_frames_s32(&wav, frames, tmp.data());
out.pcm.resize((size_t)got * ch);
for (size_t i = 0; i < out.pcm.size(); i++) out.pcm[i] = (float)(tmp[i] * INT_SCALE);
}
if (out.pcm.empty()) {
err = "the WAV/AIFF file contains no audio";
ok = false;
}
}
drwav_uninit(&wav);
return ok;
}
bool decode_flac(const std::vector<uint8_t> &bytes, Audio &out, std::string &err) {
drflac *f = drflac_open_memory(bytes.data(), bytes.size(), nullptr);
if (!f) {
err = "could not decode FLAC";
return false;
}
const size_t ch = f->channels;
out.rate = (int)f->sampleRate;
out.channels = (int)ch;
out.pcm.clear();
std::vector<drflac_int32> buf(4096 * ch);
for (;;) {
drflac_uint64 got = drflac_read_pcm_frames_s32(f, 4096, buf.data());
if (!got) break;
for (size_t i = 0; i < (size_t)got * ch; i++) out.pcm.push_back((float)(buf[i] * INT_SCALE));
}
drflac_close(f);
if (out.pcm.empty() || out.rate <= 0) {
err = "could not decode FLAC (no audio)";
return false;
}
return true;
}
bool decode_mp3(const std::vector<uint8_t> &bytes, Audio &out, std::string &err) {
mp3dec_t dec;
mp3dec_file_info_t info;
std::memset(&info, 0, sizeof info);
if (mp3dec_load_buf(&dec, bytes.data(), bytes.size(), &info, nullptr, nullptr) || !info.buffer ||
!info.samples || info.channels <= 0 || info.hz <= 0) {
std::free(info.buffer);
err = "could not decode MP3: no MPEG audio frames found";
return false;
}
out.rate = info.hz;
out.channels = info.channels;
out.pcm.assign(info.buffer, info.buffer + info.samples - info.samples % info.channels);
std::free(info.buffer);
return true;
}
} // namespace
bool decode_file(const std::vector<uint8_t> &bytes, Audio &out, std::string &err) {
out = Audio();
err.clear();
if (bytes.size() < 12) {
err = "the file is too small to be audio";
return false;
}
if ((starts(bytes, 0, "RIFF") || starts(bytes, 0, "RF64")) && starts(bytes, 8, "WAVE"))
return decode_wav(bytes, out, err);
if (starts(bytes, 0, "FORM") && (starts(bytes, 8, "AIFF") || starts(bytes, 8, "AIFC")))
return decode_wav(bytes, out, err);
if (starts(bytes, 0, "fLaC")) return decode_flac(bytes, out, err);
if (starts(bytes, 0, "OggS")) {
err = "unsupported input format (OGG); use MP3, WAV, AIFF or FLAC";
return false;
}
if (starts(bytes, 4, "ftyp")) {
err = "unsupported input format (MP4); use MP3, WAV, AIFF or FLAC";
return false;
}
// ID3, an MPEG frame sync, or junk before the first frame: try MP3.
return decode_mp3(bytes, out, err);
}
} // namespace at9
File diff suppressed because it is too large. Load diff
+53
View File
@@ -0,0 +1,53 @@
// Internal helpers shared by the at9 sources.
// Copyright (C) 2026 BlackBearReloaded (original Python implementation)
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
namespace at9 {
namespace internal {
constexpr double PI = 3.141592653589793238462643383279502884;
constexpr int RATE = 48000;
constexpr int SUPERFRAME_SAMPLES = 1024;
constexpr int ENCODER_DELAY = 256;
constexpr uint32_t PS5_SIZE_LIMIT = 2u * 1024u * 1024u;
// numpy's pairwise summation (used by np.sum / np.mean along a contiguous
// axis). Reproducing its order keeps results bit-identical to the reference
// where the inputs are identical.
double pairwise_sum_large(const double *a, std::ptrdiff_t n, std::ptrdiff_t stride); // n > 128
inline double pairwise_sum(const double *a, std::ptrdiff_t n, std::ptrdiff_t stride = 1) {
if (n < 8) {
double res = 0.;
for (std::ptrdiff_t i = 0; i < n; i++) res += a[i * stride];
return res;
}
if (n <= 128) {
double r[8];
for (int j = 0; j < 8; j++) r[j] = a[j * stride];
std::ptrdiff_t i;
for (i = 8; i < n - (n % 8); i += 8)
for (int j = 0; j < 8; j++) r[j] += a[(i + j) * stride];
double res = ((r[0] + r[1]) + (r[2] + r[3])) + ((r[4] + r[5]) + (r[6] + r[7]));
for (; i < n; i++) res += a[i * stride];
return res;
}
return pairwise_sum_large(a, n, stride);
}
// np.add.reduceat segment: first element, then the pairwise sum of the rest.
inline double reduceat_sum(const double *a, std::ptrdiff_t n) {
return n <= 0 ? 0.0 : a[0] + pairwise_sum(a + 1, n - 1);
}
int frame_bytes_for(int bitrate_kbps); // throws on unsupported rates
uint32_t header_size(bool loop);
uint64_t file_size(uint64_t sample_count, uint32_t superframe_bytes, bool loop);
} // namespace internal
} // namespace at9
+531
View File
@@ -0,0 +1,531 @@
// snd0.at9 pipeline: channel mapping, resampling, loudness (BS.1770-4),
// true-peak limiting, fades, and the make_snd0 driver; preview WAV writer.
//
// C++ port of ps5at9/dsp.py, ps5at9/cli.py and parts of ps5at9/audio_io.py and
// ps5at9/wav.py from PS5 AT9 Converter v0.1.0
// (https://github.com/blackbearreloaded/ps5-at9-converter).
// Copyright (C) 2026 BlackBearReloaded (original Python implementation)
// SPDX-License-Identifier: GPL-3.0-or-later
#include "at9.h"
#include "at9_internal.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <deque>
#include <limits>
#include <numeric>
#include <stdexcept>
#include <string>
#include <thread>
namespace at9 {
namespace {
using namespace internal;
using Planar = std::vector<std::vector<double>>;
// Run fn(begin, end) over [0, n) split across threads. Every output element
// is computed independently, so results do not depend on the thread count.
template <class F> void parallel_chunks(size_t n, unsigned threads, F fn) {
const size_t min_chunk = 16384;
unsigned t = std::max(1u, std::min<unsigned>(threads, (unsigned)((n + min_chunk - 1) / min_chunk)));
if (t <= 1) {
fn((size_t)0, n);
return;
}
std::vector<std::thread> pool;
size_t step = (n + t - 1) / t;
for (unsigned i = 0; i < t; i++) {
size_t b = i * step, e = std::min(n, b + step);
if (b < e) pool.emplace_back([=] { fn(b, e); });
}
for (auto &th : pool) th.join();
}
// ---------------------------------------------------------------- numpy.i0 (Cephes)
const double I0A[30] = {
-4.4153416464793395e-18, 3.3307945188222384e-17, -2.431279846547955e-16, 1.715391285555133e-15,
-1.1685332877993451e-14, 7.676185498604936e-14, -4.856446783111929e-13, 2.95505266312964e-12,
-1.726826291441556e-11, 9.675809035373237e-11, -5.189795601635263e-10, 2.6598237246823866e-09,
-1.300025009986248e-08, 6.046995022541919e-08, -2.670793853940612e-07, 1.1173875391201037e-06,
-4.4167383584587505e-06, 1.6448448070728896e-05, -5.754195010082104e-05, 0.00018850288509584165,
-0.0005763755745385824, 0.0016394756169413357, -0.004324309995050576, 0.010546460394594998,
-0.02373741480589947, 0.04930528423967071, -0.09490109704804764, 0.17162090152220877,
-0.3046826723431984, 0.6767952744094761};
const double I0B[25] = {
-7.233180487874754e-18, -4.830504485944182e-18, 4.46562142029676e-17, 3.461222867697461e-17,
-2.8276239805165836e-16, -3.425485619677219e-16, 1.7725601330565263e-15, 3.8116806693526224e-15,
-9.554846698828307e-15, -4.150569347287222e-14, 1.54008621752141e-14, 3.8527783827421426e-13,
7.180124451383666e-13, -1.7941785315068062e-12, -1.3215811840447713e-11, -3.1499165279632416e-11,
1.1889147107846439e-11, 4.94060238822497e-10, 3.3962320257083865e-09, 2.266668990498178e-08,
2.0489185894690638e-07, 2.8913705208347567e-06, 6.889758346916825e-05, 0.0033691164782556943,
0.8044904110141088};
double chbevl(double x, const double *vals, int n) {
double b0 = vals[0], b1 = 0.0, b2 = 0.0;
for (int i = 1; i < n; i++) {
b2 = b1;
b1 = b0;
b0 = x * b1 - b2 + vals[i];
}
return 0.5 * (b0 - b2);
}
double i0(double x) {
x = std::fabs(x);
if (x <= 8.0) return std::exp(x) * chbevl(x / 2.0 - 2, I0A, 30);
return std::exp(x) * chbevl(32.0 / x - 2.0, I0B, 25) / std::sqrt(x);
}
double sinc(double x) {
double y = PI * x;
if (y == 0) y = std::numeric_limits<double>::epsilon();
return std::sin(y) / y;
}
// ---------------------------------------------------------------- resampling
// Polyphase Kaiser-windowed low-pass h[phase][tap] (taps = 2 * half).
std::vector<double> kaiser_phases(int up, double rate_in, double pass_hz, double stop_hz, double atten_db,
int &half) {
double beta = 0.1102 * (atten_db - 8.7);
double width = (stop_hz - pass_hz) / rate_in;
int taps = (int)std::ceil((atten_db - 8.0) / (2.285 * 2.0 * PI * width));
half = std::max(8, taps / 2 + 1);
double cutoff = (pass_hz + stop_hz) / 2.0 / rate_in;
const int L = 2 * half;
std::vector<double> h((size_t)up * L);
double ib = i0(beta);
for (int p = 0; p < up; p++) {
double phase = (double)p / up;
double *row = &h[(size_t)p * L];
for (int j = 0; j < L; j++) {
double t = (double)(-half + 1 + j) - phase;
double v = 2.0 * cutoff * sinc(2.0 * cutoff * t);
double r = t / half;
double c = std::min(std::max(1.0 - r * r, 0.0), 1.0);
double win = i0(beta * std::sqrt(c)) / ib;
row[j] = v * win;
}
double sum = pairwise_sum(row, L);
for (int j = 0; j < L; j++) row[j] /= sum;
}
return h;
}
long long gcd_ll(long long a, long long b) {
while (b) {
long long t = a % b;
a = b;
b = t;
}
return a;
}
std::vector<double> resample_channel(const std::vector<double> &x, const std::vector<double> &h, int half, int up,
int down, size_t n_out, unsigned threads) {
const size_t n_in = x.size();
const int L = 2 * half;
std::vector<double> pad(n_in + 2 * half + 2, 0.0);
std::copy(x.begin(), x.end(), pad.begin() + half);
std::vector<double> out(n_out);
parallel_chunks(n_out, threads, [&](size_t begin, size_t end) {
for (size_t n = begin; n < end; n++) {
long long pos = (long long)n * down;
long long base = pos / up;
int phase = (int)(pos % up);
const double *c = &h[(size_t)phase * L];
const double *s = &pad[base + 1];
double acc = 0.0;
for (int j = 0; j < L; j++) acc += s[j] * c[j];
out[n] = acc;
}
});
return out;
}
Planar resample(const Planar &pcm, int rate_in, int rate_out, unsigned threads) {
if (rate_in == rate_out) return pcm;
long long g = gcd_ll(rate_in, rate_out);
int up = (int)(rate_out / g), down = (int)(rate_in / g);
double nyquist = std::min(rate_in, rate_out) / 2.0;
double pass_hz = std::min(20000.0, 0.9 * nyquist);
int half = 0;
std::vector<double> h = kaiser_phases(up, rate_in, pass_hz, nyquist, 100.0, half);
size_t n_in = pcm[0].size();
size_t n_out = (size_t)std::ceil((double)((long long)n_in * up) / (double)down);
Planar out;
for (const auto &ch : pcm) out.push_back(resample_channel(ch, h, half, up, down, n_out, threads));
return out;
}
// ---------------------------------------------------------------- loudness
std::vector<double> k_weight(const std::vector<double> &x) {
// ITU-R BS.1770-4 K-weighting at 48 kHz: high shelf, then high-pass.
static const double sb[3] = {1.53512485958697, -2.69169618940638, 1.19839281085285};
static const double sa[3] = {1.0, -1.69065929318241, 0.73248077421585};
static const double hb[3] = {1.0, -2.0, 1.0};
static const double ha[3] = {1.0, -1.99004745483398, 0.99007225036621};
std::vector<double> y(x.size());
double x1 = 0, x2 = 0, y1 = 0, y2 = 0;
for (size_t n = 0; n < x.size(); n++) {
double x0 = x[n];
double y0 = sb[0] * x0 + sb[1] * x1 + sb[2] * x2 - sa[1] * y1 - sa[2] * y2;
x2 = x1;
x1 = x0;
y2 = y1;
y1 = y0;
y[n] = y0;
}
x1 = x2 = y1 = y2 = 0;
for (size_t n = 0; n < y.size(); n++) {
double x0 = y[n];
double y0 = hb[0] * x0 + hb[1] * x1 + hb[2] * x2 - ha[1] * y1 - ha[2] * y2;
x2 = x1;
x1 = x0;
y2 = y1;
y1 = y0;
y[n] = y0;
}
return y;
}
double integrated_loudness(const Planar &pcm) {
const size_t block = (size_t)(0.4 * 48000), step = (size_t)(0.1 * 48000);
const size_t n = pcm[0].size();
Planar w;
for (const auto &ch : pcm) {
std::vector<double> k = k_weight(ch);
for (double &v : k) v = v * v;
w.push_back(std::move(k));
}
if (n < block) {
double power = 0.0;
for (const auto &ch : w) power += pairwise_sum(ch.data(), (std::ptrdiff_t)n) / (double)n;
return power > 0 ? -0.691 + 10.0 * std::log10(power) : -std::numeric_limits<double>::infinity();
}
Planar csum;
for (const auto &ch : w) {
std::vector<double> c(n + 1);
c[0] = 0.0;
double acc = 0.0;
for (size_t i = 0; i < n; i++) {
acc += ch[i];
c[i + 1] = acc;
}
csum.push_back(std::move(c));
}
std::vector<double> z, lk;
for (size_t s = 0; s + block <= n; s += step) {
double v = 0.0;
for (size_t c = 0; c < csum.size(); c++) {
double e = (csum[c][s + block] - csum[c][s]) / (double)block;
v = c ? v + e : e;
}
z.push_back(v);
lk.push_back(-0.691 + 10.0 * std::log10(v));
}
std::vector<double> gated;
for (size_t i = 0; i < z.size(); i++)
if (lk[i] > -70.0) gated.push_back(z[i]);
if (gated.empty()) return -std::numeric_limits<double>::infinity();
double relative =
-0.691 + 10.0 * std::log10(pairwise_sum(gated.data(), (std::ptrdiff_t)gated.size()) / gated.size()) - 10.0;
std::vector<double> fin;
for (size_t i = 0; i < z.size(); i++)
if (lk[i] > -70.0 && lk[i] > relative) fin.push_back(z[i]);
return -0.691 + 10.0 * std::log10(pairwise_sum(fin.data(), (std::ptrdiff_t)fin.size()) / fin.size());
}
// ---------------------------------------------------------------- true peak
struct Oversampler {
std::vector<double> h;
int half = 0;
Oversampler() { h = kaiser_phases(4, 48000, 18000.0, 24000.0, 60.0, half); }
};
const Oversampler &oversampler() {
static const Oversampler o;
return o;
}
// Per-sample true peak (max |x| over 4x oversampled points), max over channels.
std::vector<double> true_peak_envelope(const Planar &pcm, unsigned threads) {
const Oversampler &O = oversampler();
const int half = O.half, L = 2 * half;
const size_t n = pcm[0].size();
std::vector<double> env(n, 0.0);
std::vector<double> pad(n + 2 * half + 2);
for (size_t c = 0; c < pcm.size(); c++) {
std::fill(pad.begin(), pad.end(), 0.0);
std::copy(pcm[c].begin(), pcm[c].end(), pad.begin() + half);
parallel_chunks(n, threads, [&](size_t begin, size_t end) {
for (size_t i = begin; i < end; i++) {
const double *s = &pad[i + 1];
double m = 0.0;
for (int p = 0; p < 4; p++) {
const double *k = &O.h[(size_t)p * L];
double acc = 0.0;
for (int j = 0; j < L; j++) acc += s[j] * k[j];
m = std::max(m, std::fabs(acc));
}
env[i] = c ? std::max(env[i], m) : m;
}
});
}
return env;
}
double max_of(const std::vector<double> &v) {
double m = -std::numeric_limits<double>::infinity();
for (double x : v) m = std::max(m, x);
return m;
}
// Minimum over the centred window [n - width, n + width] (edges extended).
std::vector<double> sliding_min(const std::vector<double> &x, int width) {
if (width <= 0) return x;
const long long n = (long long)x.size();
std::vector<double> out(n);
std::deque<long long> dq; // indices into x with increasing values
long long next = 0;
for (long long i = 0; i < n; i++) {
long long hi = std::min(n - 1, i + width);
while (next <= hi) {
while (!dq.empty() && x[dq.back()] >= x[next]) dq.pop_back();
dq.push_back(next++);
}
long long lo = i - width;
while (dq.front() < lo) dq.pop_front();
out[i] = x[dq.front()];
}
return out;
}
// Mean over the centred window [n - width, n + width] (edges extended).
std::vector<double> moving_average(const std::vector<double> &x, int width) {
if (width <= 0) return x;
const size_t n = x.size();
const size_t w = 2 * (size_t)width + 1;
std::vector<double> c(n + 2 * width + 1);
c[0] = 0.0;
double acc = 0.0;
for (size_t i = 0; i < n + 2 * (size_t)width; i++) {
double v = i < (size_t)width ? x[0] : (i - width < n ? x[i - width] : x[n - 1]);
acc += v;
c[i + 1] = acc;
}
std::vector<double> out(n);
for (size_t i = 0; i < n; i++) out[i] = (c[i + w] - c[i]) / (double)w;
return out;
}
bool limit_true_peak(Planar &pcm, double ceiling_db, unsigned threads, int rate = 48000, double attack = 0.002,
double release = 0.05) {
std::vector<double> env = true_peak_envelope(pcm, threads);
const double ceiling = std::pow(10.0, ceiling_db / 20.0);
if (max_of(env) <= ceiling) return false;
double target = ceiling_db;
int a = std::max(1, (int)(attack * rate));
int r = std::max(1, (int)(release * rate));
for (int it = 0; it < 8; it++) {
double t = std::pow(10.0, target / 20.0);
std::vector<double> need(env.size());
for (size_t i = 0; i < env.size(); i++) need[i] = std::min(1.0, t / std::max(env[i], 1e-12));
std::vector<double> gain = moving_average(sliding_min(need, a), a / 2);
gain = moving_average(sliding_min(gain, r), r / 2);
for (auto &ch : pcm)
for (size_t i = 0; i < ch.size(); i++) ch[i] = ch[i] * gain[i];
env = true_peak_envelope(pcm, threads);
if (max_of(env) <= ceiling) break;
target -= 0.05;
}
return true;
}
// ---------------------------------------------------------------- fades
void apply_fades(Planar &pcm, int rate, double fade_in, double fade_out) {
const long long n = (long long)pcm[0].size();
long long fi = std::min(n, (long long)std::nearbyint(fade_in * rate));
long long fo = std::min(n, (long long)std::nearbyint(fade_out * rate));
for (auto &ch : pcm) {
for (long long i = 0; i < fi; i++) ch[i] *= 0.5 - 0.5 * std::cos(PI * (i + 0.5) / fi);
for (long long i = 0; i < fo; i++) ch[n - fo + i] *= 0.5 + 0.5 * std::cos(PI * (i + 0.5) / fo);
}
}
// ---------------------------------------------------------------- helpers
Planar to_stereo(const Audio &in, size_t a, size_t b) {
const int ch = in.channels;
const size_t frames = b - a;
Planar out(2, std::vector<double>(frames));
auto at = [&](size_t i, int c) { return (double)in.pcm[(a + i) * ch + c]; };
if (ch == 1) {
for (size_t i = 0; i < frames; i++) out[0][i] = out[1][i] = at(i, 0);
} else if (ch == 6) { // FL FR FC LFE BL BR, ITU-R BS.775 downmix
const double k = 1.0 / std::sqrt(2.0);
const double norm = 1.0 + 2.0 * k;
for (size_t i = 0; i < frames; i++) {
out[0][i] = (at(i, 0) + k * at(i, 2) + k * at(i, 4)) / norm;
out[1][i] = (at(i, 1) + k * at(i, 2) + k * at(i, 5)) / norm;
}
} else {
for (size_t i = 0; i < frames; i++) {
out[0][i] = at(i, 0);
out[1][i] = at(i, 1);
}
}
return out;
}
std::string fmt_time(double seconds) {
double minutes = std::floor(seconds / 60.0);
double sec = seconds - minutes * 60.0;
char buf[64];
std::snprintf(buf, sizeof buf, "%d:%06.3f", (int)minutes, sec);
return buf;
}
uint64_t max_samples_for(int bitrate, bool loop) {
uint64_t sfb = (uint64_t)frame_bytes_for(bitrate) * 4;
uint64_t superframes = (PS5_SIZE_LIMIT - header_size(loop)) / sfb;
return superframes * SUPERFRAME_SAMPLES - ENCODER_DELAY;
}
} // namespace
namespace detail {
Result make_snd0_ex(const Audio &in, const Options &o, std::vector<double> *left, std::vector<double> *right,
unsigned threads) {
static const int rates[] = {72, 96, 120, 144, 168, 192};
if (std::find(std::begin(rates), std::end(rates), o.bitrate_kbps) == std::end(rates))
throw std::runtime_error("bit rate must be 72, 96, 120, 144, 168 or 192 kb/s");
if (in.rate <= 0 || in.channels <= 0 || in.pcm.size() < (size_t)in.channels)
throw std::runtime_error("the input has no audio");
if (!(o.start_sec >= 0) || !std::isfinite(o.start_sec)) throw std::runtime_error("start must be positive");
const bool max_dur = !(o.duration_sec > 0);
const size_t total = in.pcm.size() / in.channels;
// audio_io.load: decode from up to 0.25 s before the start so resampling
// can be trimmed cleanly afterwards.
const double margin = 0.25;
const double begin = std::max(0.0, o.start_sec - margin);
const double offset = o.start_sec - begin;
size_t a = (size_t)std::floor(begin * in.rate);
size_t b = total;
if (!max_dur) {
double length = o.duration_sec + offset + margin;
b = (size_t)std::min<double>((double)total, (double)a + std::ceil(length * in.rate));
}
if (a >= total || b <= a) throw std::runtime_error("the start time is beyond the end of the input");
if (threads == 0) threads = std::max(1u, std::thread::hardware_concurrency());
Planar pcm = resample(to_stereo(in, a, b), in.rate, RATE, threads);
const size_t skip = (size_t)std::nearbyint(offset * RATE);
const size_t available = pcm[0].size() > skip ? pcm[0].size() - skip : 0;
const bool loop = o.loop;
const uint64_t max_samples = max_samples_for(o.bitrate_kbps, loop);
size_t count;
if (max_dur)
count = (size_t)std::min<uint64_t>(available, max_samples);
else
count = std::min(available, (size_t)std::nearbyint(o.duration_sec * RATE));
if (count == 0) throw std::runtime_error("the selected excerpt is empty");
for (auto &ch : pcm) ch = std::vector<double>(ch.begin() + skip, ch.begin() + skip + count);
const uint32_t sfb = (uint32_t)frame_bytes_for(o.bitrate_kbps) * 4;
const uint64_t size = file_size(count, sfb, loop);
if (size > PS5_SIZE_LIMIT) {
char msg[256];
std::snprintf(msg, sizeof msg,
"%.3f s at %d kb/s makes a %llu-byte file, above the 2 MiB PS5 limit; use at most %.3f s "
"(or a lower bit rate)",
count / (double)RATE, o.bitrate_kbps, (unsigned long long)size, max_samples / (double)RATE);
throw std::runtime_error(msg);
}
const double source_lufs = integrated_loudness(pcm);
if (o.normalize && std::isfinite(source_lufs)) {
double gain_db = o.lufs - source_lufs;
double g = std::pow(10.0, gain_db / 20.0);
for (auto &ch : pcm)
for (double &v : ch) v = v * g;
}
limit_true_peak(pcm, o.true_peak_db, threads, RATE);
apply_fades(pcm, RATE, o.fade_in, o.fade_out);
const double final_lufs = integrated_loudness(pcm);
Result r;
std::vector<uint8_t> data = encode_atrac9(pcm[0], pcm[1], o.bitrate_kbps, threads);
r.at9 = build_at9(o.bitrate_kbps, (uint32_t)count, data, loop);
if (r.at9.size() != size) throw std::runtime_error("internal error: unexpected file size");
r.loudness_lufs = final_lufs;
r.seconds = count / (double)RATE;
char buf[64];
if (std::isfinite(final_lufs))
std::snprintf(buf, sizeof buf, "%.2f", final_lufs);
else
std::snprintf(buf, sizeof buf, "%s", final_lufs < 0 ? "-inf" : "inf"); // Python's "%.2f" % -inf
r.loudness_param = buf;
r.processed.resize(count * 2);
for (size_t i = 0; i < count; i++) {
r.processed[2 * i] = (float)pcm[0][i];
r.processed[2 * i + 1] = (float)pcm[1][i];
}
if (left) *left = pcm[0];
if (right) *right = pcm[1];
return r;
}
} // namespace detail
Result make_snd0(const Audio &in, const Options &o) { return detail::make_snd0_ex(in, o, nullptr, nullptr, 0); }
std::vector<uint8_t> wav_bytes(const std::vector<float> &stereo48k) {
const uint32_t channels = 2, rate = 48000, bits = 16;
const size_t frames = stereo48k.size() / 2;
const uint32_t payload = (uint32_t)(frames * channels * 2);
std::vector<uint8_t> out;
out.reserve(44 + payload + 1);
auto u16 = [&](uint32_t x) {
out.push_back((uint8_t)x);
out.push_back((uint8_t)(x >> 8));
};
auto u32 = [&](uint32_t x) {
u16(x & 0xFFFF);
u16(x >> 16);
};
auto tag = [&](const char *t) { out.insert(out.end(), t, t + 4); };
tag("RIFF");
u32(4 + 8 + 16 + 8 + payload + (payload & 1));
tag("WAVE");
tag("fmt ");
u32(16);
u16(1);
u16(channels);
u32(rate);
u32(rate * channels * bits / 8);
u16(channels * bits / 8);
u16(bits);
tag("data");
u32(payload);
for (size_t i = 0; i < frames * 2; i++) {
double v = std::nearbyint((double)stereo48k[i] * 32768.0);
v = std::min(std::max(v, -32768.0), 32767.0);
int s = (int)v;
u16((uint32_t)(uint16_t)(int16_t)s);
}
if (payload & 1) out.push_back(0);
return out;
}
} // namespace at9
File diff suppressed because it is too large. Load diff
+57
View File
@@ -0,0 +1,57 @@
// ATRAC9 constant tables, converted from LibAtrac9
// (https://github.com/Thealexbarney/LibAtrac9) via ps5at9/atrac9_tables.py of
// PS5 AT9 Converter. Generated by tools/at9check/gen_tables.py; do not edit.
//
// SPDX-License-Identifier: MIT
//
// MIT License
//
// Copyright (c) 2018 Alex Barney
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", 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
// AUTHORS OR COPYRIGHT HOLDERS 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.
#pragma once
#include <cstdint>
namespace at9 {
namespace tables {
struct Huff { int size; int value_count_power; const uint8_t *bits; const uint16_t *codes; };
// Scale factor codebooks indexed by word length (unsigned 1..6, signed 2..5); size 0 = absent.
extern const Huff SF_UNSIGNED[7];
extern const Huff SF_SIGNED[6];
// Spectrum codebooks [codebook set][word length 0..7][codebook index]; size 0 = absent.
extern const Huff SPECTRUM[2][8][4];
extern const int SF_WEIGHTS[8][32];
extern const int GRADIENT_MAIN[48];
// Band extension tables (decoder only).
extern const int BEX_GROUP_INFO[8][3];
extern const int BEX_VALUE_COUNTS[5][6];
extern const int BEX_DATA_LENGTHS[5][6][4];
extern const double BEX_MODE0_BANDS3[5][32];
extern const double BEX_MODE0_BANDS4[5][16];
extern const double BEX_MODE0_BANDS5[3][32];
extern const double BEX_MODE2_SCALE[64];
extern const double BEX_MODE3_INITIAL[16];
extern const double BEX_MODE3_RATE[16];
extern const double BEX_MODE4_MULTIPLIER[8];
} // namespace tables
} // namespace at9
+12760
View File
File diff suppressed because it is too large. Load diff
+9209
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+173 -23
View File
@@ -10,6 +10,8 @@
#include "imaging.h"
#include "ps5client.h"
#include "layout.h"
#include "lib/at9/at9.h"
#include "presets.h"
#include "lib/json.hpp"
#include <atomic>
@@ -27,7 +29,7 @@
#include <shellapi.h>
#include <tlhelp32.h>
#endif
#define STUDIO_VERSION "1.2"
#define STUDIO_VERSION "1.3"
using json = nlohmann::json;
@@ -40,6 +42,11 @@ struct Staged { // the user's image, decoded; converted per targ
img::Image src;
std::vector<uint8_t> preview_png;
std::string note;
// Music: the decoded file, the clip settings, and the snd0.at9 made from them.
at9::Audio audio;
at9::Options opt;
at9::Result enc;
std::vector<uint8_t> preview_wav;
};
static std::mutex g_mu;
static std::string g_ip;
@@ -385,7 +392,52 @@ static std::vector<uint8_t> fetch_background(const std::string &id, const std::s
return {};
}
static std::string secs(double v) { char b[32]; snprintf(b, sizeof b, "%d:%02d", (int)v / 60, (int)v % 60); return b; }
// Cuts, levels and encodes the clip; the result is what Apply uploads, so size problems show up now.
static void encode_music(Staged &s) {
s.enc = at9::make_snd0(s.audio, s.opt);
s.preview_wav = at9::wav_bytes(s.enc.processed);
double total = (double)s.audio.pcm.size() / std::max(1, s.audio.channels) / std::max(1, s.audio.rate);
s.note = "";
if (s.opt.start_sec + 0.5 >= total) s.note = "The start is past the end of the song.";
}
static json music_json(const Staged &s) {
double total = (double)s.audio.pcm.size() / std::max(1, s.audio.channels) / std::max(1, s.audio.rate);
return {{"ok", true}, {"note", s.note}, {"seconds", s.enc.seconds}, {"total", total}, {"kb", (int)(s.enc.at9.size() / 1024)},
{"start", s.opt.start_sec}, {"duration", s.opt.duration_sec},
{"summary", secs(s.opt.start_sec) + " to " + secs(s.opt.start_sec + s.enc.seconds) + ", " + std::to_string(s.enc.at9.size() / 1024) + " KB"}};
}
static json stage_music(const std::vector<uint8_t> &bytes) {
Staged s;
std::string err;
if (!at9::decode_file(bytes, s.audio, err)) throw ps5::Error("That file isn't an MP3, WAV or FLAC PSGFX can read" + (err.empty() ? std::string(".") : " (" + err + ")."));
encode_music(s);
json j = music_json(s);
std::lock_guard<std::mutex> l(g_mu);
g_staged["music"] = std::move(s);
return j;
}
// Start (seconds) and length (seconds; 0 = the longest that fits in the PS5's 2 MB limit).
static json music_clip(const json &req) {
Staged s;
{
std::lock_guard<std::mutex> l(g_mu);
auto it = g_staged.find("music");
if (it == g_staged.end()) throw ps5::Error("Add a song first.");
s = it->second;
}
s.opt.start_sec = std::max(0.0, req.value("start", s.opt.start_sec));
s.opt.duration_sec = std::max(0.0, req.value("duration", s.opt.duration_sec));
encode_music(s);
json j = music_json(s);
std::lock_guard<std::mutex> l(g_mu);
g_staged["music"] = std::move(s);
return j;
}
static json stage(const std::string &kind, const std::vector<uint8_t> &bytes) {
if (kind == "music") return stage_music(bytes);
Staged s;
if (!img::decode(bytes, s.src)) throw ps5::Error("That file isn't a PNG or JPEG image.");
const img::Image &src = s.src;
@@ -408,8 +460,9 @@ static json stage(const std::string &kind, const std::vector<uint8_t> &bytes) {
// A file on the PS5 we're going to replace, and the format it has to stay in.
struct Target { std::string name; bool dds = false; int w = 0, h = 0; };
static std::vector<uint8_t> encode_for(const std::string &kind, const img::Image &src, const Target &t) {
img::Image im = img::cover(src, t.w, t.h);
static std::vector<uint8_t> encode_for(const std::string &kind, const Staged &s, const Target &t) {
if (kind == "music") return s.enc.at9;
img::Image im = img::cover(s.src, t.w, t.h);
img::opaque(im);
return t.dds ? img::to_bc7_dds(im) : img::to_png(im);
}
@@ -418,6 +471,7 @@ static std::vector<uint8_t> encode_for(const std::string &kind, const img::Image
static std::vector<Target> homebrew_targets(const std::string &kind) {
if (kind == "icon") return {{"icon0.png", false, 512, 512}};
if (kind == "background") return {{"pic0.dds", true, 3840, 2160}, {"pic1.dds", true, 3840, 2160}};
if (kind == "music") return {{"snd0.at9"}};
return {};
}
@@ -426,6 +480,7 @@ static std::vector<Target> homebrew_targets(const std::string &kind) {
static std::vector<Target> game_targets(ps5::Client &c, const std::string &id, const std::string &kind,
json &log, std::vector<std::string> &seen) {
std::vector<Target> out;
if (kind == "music") return {{"snd0.at9"}}; // added when the game has none; backed up when it has one
for (auto &e : list_dir(c, appmeta(id))) {
std::string name = e.value("name", ""), ln = lower(name);
std::string ek = e.value("kind", "");
@@ -505,6 +560,13 @@ static void sync_home(ps5::Client &c, const std::string &id, const std::string &
// Restore, and the database is backed up first, as Home layout does.
static const char *const ORIGINALS = "psgfx_original.json";
static std::string art_column(const std::string &kind) { return kind == "icon" ? "icon0Info" : "pic0Info"; }
// The column holding a title's selection-music path, if this database has one (snd0Info or similar).
static std::string music_column(const layout::Info &info) {
auto it = info.cols.find(info.concept_t);
if (it == info.cols.end()) return "";
for (auto &c : it->second) if (lower(c).find("snd0") != std::string::npos) return c;
return "";
}
// Size and format from an image's first bytes; false if it isn't a PNG or DDS we can match.
static bool probe_art(const std::vector<uint8_t> &h, Target &t) {
@@ -525,15 +587,16 @@ static std::vector<uint8_t> read_head(ps5::Client &c, const std::string &path) {
catch (...) { return {}; }
}
// Sets an art column for this title in every table that has it (all user profiles).
// Sets an art column for this title in every table that has it (all user profiles). Empty = NULL.
static void set_art_column(layout::DB &db, const layout::Info &info, const std::string &id, const std::string &concept,
const std::string &col, const std::string &value) {
layout::Val v = value.empty() ? layout::Val(nullptr) : layout::Val(value);
for (auto &[table, cols] : info.cols) {
if (!cols.count(col)) continue;
if (cols.count("localConceptId") && !concept.empty())
db.exec("UPDATE " + layout::q(table) + " SET " + layout::q(col) + "=? WHERE localConceptId=?", {value, concept});
db.exec("UPDATE " + layout::q(table) + " SET " + layout::q(col) + "=? WHERE localConceptId=?", {v, concept});
else if (cols.count("titleId"))
db.exec("UPDATE " + layout::q(table) + " SET " + layout::q(col) + "=? WHERE titleId=?", {value, id});
db.exec("UPDATE " + layout::q(table) + " SET " + layout::q(col) + "=? WHERE titleId=?", {v, id});
}
}
@@ -556,6 +619,27 @@ static json read_originals(ps5::Client &c, const std::string &id) {
catch (...) { return json::object(); }
}
static std::string ts_query() { return "?ts=" + std::to_string((long long)time(nullptr)); }
// The home screen only plays a title's music when its app.db row names the file (snd0Info);
// the PS5 fills that in at install time, so an app installed without music has it empty.
// Points it at `path` (homebrew: /user/app/<id>/sce_sys/snd0.at9, like the PS5 does), or
// clears it when `path` is empty.
static void point_music(const std::string &id, const std::string &path, json &log) {
std::lock_guard<std::mutex> l(g_layout_mu);
try {
auto orig = pull_db();
layout::DB db(orig);
auto info = layout::analyze(db, g_layout_user);
std::string col = music_column(info);
if (col.empty()) { log.push_back("This firmware's home-screen database has no music entry, so the music may not play."); return; }
set_art_column(db, info, id, concept_of(db, info, id), col, path.empty() ? "" : path + ts_query());
upload_db(orig, db, (path.empty() ? "Before removing music for " : "Before music for ") + id, log);
} catch (const std::exception &e) {
log.push_back(std::string("Couldn't point the home screen at the music (") + e.what() + "), so it may not play.");
}
}
// Returns the staged slots it handled; the rest fall back to replacing the art-folder files.
static std::set<std::string> game_apply_db(ps5::Client &c, const std::string &id, const std::map<std::string, Staged> &staged, json &log) {
std::set<std::string> done;
@@ -576,10 +660,12 @@ static std::set<std::string> game_apply_db(ps5::Client &c, const std::string &id
json originals = read_originals(c, id);
std::vector<std::string> replaced; // our older files, deleted once the database points away from them
for (auto &[kind, s] : staged) {
const std::string col = art_column(kind);
const std::string col = kind == "music" ? music_column(info) : art_column(kind);
if (col.empty()) continue;
std::string value = db.scalar_str("SELECT " + layout::q(col) + " FROM " + layout::q(info.concept_t) + " WHERE localConceptId=?", {concept});
std::string path = layout::strip_query(value);
if (path.empty() || path[0] != '/') continue;
// A title without music has no snd0Info at all; the home screen plays nothing until it's set.
if (!(kind == "music" && path.empty()) && (path.empty() || path[0] != '/')) continue;
std::string base = path.substr(path.find_last_of('/') + 1);
bool in_dir = path == dir + "/" + base, ours = in_dir && base.rfind("psgfx_", 0) == 0;
if (in_dir && !ours) { // a real file in the art folder: replacing it in place works
@@ -588,19 +674,25 @@ static std::set<std::string> game_apply_db(ps5::Client &c, const std::string &id
if (regular) continue;
}
Target t;
if (!probe_art(read_head(c, path), t)) {
t.dds = ends_with(lower(base), ".dds");
t.w = kind == "icon" ? 512 : t.dds ? 3840 : 1920;
t.h = kind == "icon" ? 512 : t.dds ? 2160 : 1080;
if (kind == "music") {
t.name = "psgfx_snd0_" + now_stamp("%Y%m%d%H%M%S") + ".at9";
c.upload(dir + "/" + t.name, encode_for(kind, s, t));
log.push_back("Uploaded " + t.name + " (" + std::to_string(s.enc.at9.size() / 1024) + " KB)");
} else {
if (!probe_art(read_head(c, path), t)) {
t.dds = ends_with(lower(base), ".dds");
t.w = kind == "icon" ? 512 : t.dds ? 3840 : 1920;
t.h = kind == "icon" ? 512 : t.dds ? 2160 : 1080;
}
std::string stem = kind == "icon" ? "icon0" : "pic0";
t.name = "psgfx_" + stem + "_" + now_stamp("%Y%m%d%H%M%S") + (t.dds ? ".dds" : ".png");
c.upload(dir + "/" + t.name, encode_for(kind, s, t));
log.push_back("Uploaded " + t.name + " (" + std::to_string(t.w) + "x" + std::to_string(t.h) + ")");
}
std::string stem = kind == "icon" ? "icon0" : "pic0";
t.name = "psgfx_" + stem + "_" + now_stamp("%Y%m%d%H%M%S") + (t.dds ? ".dds" : ".png");
c.upload(dir + "/" + t.name, encode_for(kind, s.src, t));
log.push_back("Uploaded " + t.name + " (" + std::to_string(t.w) + "x" + std::to_string(t.h) + ")");
if (!originals.contains(col)) originals[col] = value;
if (ours) replaced.push_back(dir + "/" + base);
size_t qp = value.find('?');
set_art_column(db, info, id, concept, col, dir + "/" + t.name + (qp == std::string::npos ? "" : value.substr(qp)));
set_art_column(db, info, id, concept, col, dir + "/" + t.name + (qp == std::string::npos ? ts_query() : value.substr(qp)));
done.insert(kind);
}
if (done.empty()) return done;
@@ -633,27 +725,54 @@ static bool game_restore_db(ps5::Client &c, const std::string &id, json &log) {
return true;
}
// The home screen plays snd0.at9 at the level param.json gives in pubtools.loudnessSnd0.
static void set_music_loudness(ps5::Client &c, const std::string &param_path, const std::string &value, json &log) {
if (value.empty() || value.find("inf") != std::string::npos) return; // a silent clip has no level
try {
auto b = c.read_file(param_path, 1u << 20);
auto j = nlohmann::ordered_json::parse(b.begin(), b.end());
if (!j.contains("pubtools") || !j["pubtools"].is_object()) j["pubtools"] = nlohmann::ordered_json::object();
if (j["pubtools"].value("loudnessSnd0", std::string()) == value) return;
j["pubtools"]["loudnessSnd0"] = value;
std::string out = j.dump(2);
c.upload(param_path, std::vector<uint8_t>(out.begin(), out.end()));
log.push_back("Set the music level in " + param_path.substr(param_path.find_last_of('/') + 1) + " (" + value + " LUFS)");
} catch (const std::exception &e) {
log.push_back(std::string("Couldn't set the music level in param.json (") + e.what() + "); the music may play louder or quieter than intended.");
}
}
static json do_apply(const std::string &id, const std::string &src, std::string kind_of_app) {
if (mounted_image(src)) kind_of_app = "game";
json log = json::array();
std::map<std::string, Staged> staged;
{ std::lock_guard<std::mutex> l(g_mu); staged = g_staged; }
if (staged.empty()) throw ps5::Error("Add at least one image first.");
if (staged.empty()) throw ps5::Error("Add an image or a song first.");
const bool music = staged.count("music") > 0;
auto c = client();
if (kind_of_app == "game") {
auto via_db = game_apply_db(c, id, staged, log);
if (via_db.count("music") && exists(c, appmeta(id), "param.json")) {
backup_once(c, appmeta(id), "param.json", log);
set_music_loudness(c, appmeta(id) + "/param.json", staged["music"].enc.loudness_param, log);
}
int written = (int)via_db.size();
std::vector<std::string> seen;
for (auto &[kind, s] : staged) {
if (via_db.count(kind)) continue;
auto targets = game_targets(c, id, kind, log, seen);
if (targets.empty()) log.push_back(std::string("This game has no ") + (kind == "icon" ? "icon" : "background") + " file this tool can replace.");
if (kind == "music" && exists(c, appmeta(id), "param.json")) {
backup_once(c, appmeta(id), "param.json", log);
set_music_loudness(c, appmeta(id) + "/param.json", s.enc.loudness_param, log);
}
for (auto &t : targets) {
backup_once(c, appmeta(id), t.name, log);
auto bytes = encode_for(kind, s.src, t);
auto bytes = encode_for(kind, s, t);
c.upload(appmeta(id) + "/" + t.name, bytes);
log.push_back("Replaced " + t.name + " (" + std::to_string(t.w) + "x" + std::to_string(t.h) + ")");
log.push_back(kind == "music" ? "Uploaded " + t.name + " (" + std::to_string(bytes.size() / 1024) + " KB)"
: "Replaced " + t.name + " (" + std::to_string(t.w) + "x" + std::to_string(t.h) + ")");
written++;
}
}
@@ -664,7 +783,7 @@ static json do_apply(const std::string &id, const std::string &src, std::string
for (auto &n : log) notes += " " + n.get<std::string>();
throw ps5::Error("Nothing was changed. Files in this game's art folder: " + (list.empty() ? std::string("(none)") : list) + "." + notes);
}
log.push_back("Done. Restart the PS5 to see the new art.");
log.push_back(music ? "Done. Restart the PS5 to see and hear the change." : "Done. Restart the PS5 to see the new art.");
} else {
if (src.empty()) throw ps5::Error("This app's folder is unknown.");
const std::string dir = src + "/sce_sys";
@@ -673,12 +792,20 @@ static json do_apply(const std::string &id, const std::string &src, std::string
for (auto &t : homebrew_targets(kind)) {
changed.push_back(t.name);
backup_once(c, dir, t.name, log);
auto bytes = encode_for(kind, s.src, t);
auto bytes = encode_for(kind, s, t);
c.upload(dir + "/" + t.name, bytes);
log.push_back("Uploaded " + t.name + " (" + std::to_string(bytes.size() / 1024) + " KB)");
}
}
if (music) { // not backed up: it also holds a rename, and the level is harmless without the music
set_music_loudness(c, dir + "/param.json", staged["music"].enc.loudness_param, log);
changed.push_back("param.json");
}
sync_home(c, id, src, changed, log);
if (music) {
point_music(id, "/user/app/" + id + "/sce_sys/snd0.at9", log);
log.push_back("Restart the PS5, then hover the app to hear its music.");
}
}
{ std::lock_guard<std::mutex> l(g_mu); g_icon_cache.erase(id); g_staged.clear(); }
return {{"ok", true}, {"log", log}};
@@ -714,7 +841,11 @@ static json do_restore(const std::string &id, const std::string &src, std::strin
}
}
if (kind_of_app == "game") log.push_back("Done. Restart the PS5 to see the original art.");
else sync_home(c, id, src, names, log);
else {
sync_home(c, id, src, names, log);
if (std::find(names.begin(), names.end(), "snd0.at9") != names.end())
point_music(id, exists(c, dir, "snd0.at9") ? "/user/app/" + id + "/sce_sys/snd0.at9" : "", log);
}
{ std::lock_guard<std::mutex> l(g_mu); g_icon_cache.erase(id); }
return {{"ok", true}, {"log", log}};
}
@@ -869,6 +1000,25 @@ static void handle(sock_t s, Req &r) {
}
if (r.path.rfind("/api/stage/", 0) == 0 && r.method == "POST") { respond_json(s, stage(r.path.substr(11), r.body)); return; }
if (r.path.rfind("/api/unstage/", 0) == 0) { std::lock_guard<std::mutex> l(g_mu); g_staged.erase(r.path.substr(13)); respond_json(s, {{"ok", true}}); return; }
if (r.path.rfind("/api/presets/", 0) == 0) { // /api/presets/<title id> -> the built-in icons for it
std::string id = r.path.substr(13);
json list = json::array();
for (size_t i = 0; i < PRESETS_COUNT; i++) if (id == PRESETS[i].title_id) list.push_back({{"i", i}, {"app", PRESETS[i].app}});
respond_json(s, {{"ok", true}, {"presets", list}}); return;
}
if (r.path.rfind("/api/preset/", 0) == 0) { // /api/preset/<index>: the image; POST stages it as the icon
size_t i = (size_t)strtoull(r.path.c_str() + 12, nullptr, 10);
if (i >= PRESETS_COUNT) { respond(s, 404, "text/plain", "none", 4); return; }
if (r.method == "POST") { respond_json(s, stage("icon", std::vector<uint8_t>(PRESETS[i].data, PRESETS[i].data + PRESETS[i].len))); return; }
respond(s, 200, "image/png", PRESETS[i].data, PRESETS[i].len); return;
}
if (r.path == "/api/music/clip" && r.method == "POST") { respond_json(s, music_clip(json::parse(std::string(r.body.begin(), r.body.end())))); return; }
if (r.path == "/api/staged/music") {
std::vector<uint8_t> b;
{ std::lock_guard<std::mutex> l(g_mu); auto it = g_staged.find("music"); if (it != g_staged.end()) b = it->second.preview_wav; }
if (b.empty()) { respond(s, 404, "text/plain", "none", 4); return; }
respond(s, 200, "audio/wav", b.data(), b.size()); return;
}
if (r.path.rfind("/api/staged/", 0) == 0) {
std::vector<uint8_t> b;
{ std::lock_guard<std::mutex> l(g_mu); auto it = g_staged.find(r.path.substr(12)); if (it != g_staged.end()) b = it->second.preview_png; }
+7
View File
@@ -0,0 +1,7 @@
// Preset icons built into PSGFX, by title ID (assets/presets, embedded by tools/embed_presets.py).
#pragma once
#include <cstddef>
struct Preset { const char *app; const char *title_id; const unsigned char *data; size_t len; };
extern const Preset PRESETS[];
extern const size_t PRESETS_COUNT;
+32695
View File
File diff suppressed because it is too large. Load diff
+88 -12
View File
@@ -22,6 +22,13 @@ html,body{margin:0;min-height:100%}
body{background:radial-gradient(1200px 700px at 70% -10%,#13244a 0%,transparent 60%),var(--bg);background-attachment:fixed;color:var(--text);font-size:14px;line-height:1.5}
button,input{font:inherit;color:inherit}
:focus-visible{outline:2px solid var(--blue-hi);outline-offset:2px}
/* Scrollbars in the app's own style, not the browser's grey ones. */
::-webkit-scrollbar{width:12px;height:12px}
::-webkit-scrollbar-track,::-webkit-scrollbar-corner{background:transparent}
::-webkit-scrollbar-thumb{background:rgba(160,190,255,.2);border-radius:12px;border:3px solid transparent;background-clip:padding-box}
::-webkit-scrollbar-thumb:hover{background-color:rgba(160,190,255,.3)}
::-webkit-scrollbar-thumb:active{background-color:var(--blue)}
@supports not selector(::-webkit-scrollbar){*{scrollbar-width:thin;scrollbar-color:rgba(160,190,255,.22) transparent}}
.top{display:flex;align-items:center;gap:20px;padding:16px 24px;border-bottom:1px solid var(--line)}
.brand{display:flex;align-items:flex-end;gap:10px}
@@ -54,7 +61,7 @@ button,input{font:inherit;color:inherit}
.app.locked{opacity:.5}
.empty{color:var(--muted);padding:8px;font-size:13px}
main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:column;gap:20px;max-width:1180px}
main{border-left:1px solid var(--line);padding:24px max(24px,calc((100% - 1132px)/2));display:flex;flex-direction:column;gap:20px;min-width:0}
/* The PS5 home-screen replica: the one bold element. */
.stage{position:relative;aspect-ratio:16/9;width:min(100%,calc((100vh - 330px)*16/9));min-width:min(100%,520px);margin:0 auto;border-radius:var(--r-lg);overflow:hidden;background:linear-gradient(135deg,#101b33,#060913);border:1px solid var(--line);box-shadow:0 30px 80px rgba(0,0,0,.5)}
@@ -82,6 +89,20 @@ main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:
.slot{background:var(--glass);border:1px solid var(--line);border-radius:var(--r-md);padding:14px;display:flex;gap:12px;align-items:center;min-height:92px}
.slot .thumb{width:64px;height:64px;border-radius:10px;background:var(--bg2) center/cover no-repeat;flex:none;border:1px solid var(--line)}
.slot.bgslot .thumb{width:96px;height:54px}
.slot.musicslot{grid-column:1/-1;flex-wrap:wrap}
.presets{grid-column:1/-1;background:var(--glass);border:1px solid var(--line);border-radius:var(--r-md);padding:14px}
.presets .t{font-weight:600}.presets .s{color:var(--muted);font-size:12px}
.presets .row{display:flex;gap:10px;flex-wrap:wrap;margin-top:10px}
.presets button{width:72px;height:72px;padding:0;border-radius:12px;border:2px solid transparent;background:var(--bg2) center/cover no-repeat;cursor:pointer}
.presets button:hover{border-color:var(--line)}
.presets button[aria-pressed="true"]{border-color:var(--blue-hi)}
.slot.musicslot .thumb{display:grid;place-items:center;font-size:26px;color:var(--muted)}
.mclip{display:none;gap:10px;align-items:center;flex-wrap:wrap;width:100%;margin-top:4px}
.mclip.on{display:flex}
.mclip label{color:var(--muted);font-size:12px;display:flex;gap:6px;align-items:center}
.mclip input,.mclip select{padding:5px 8px;border-radius:var(--r-sm);border:1px solid var(--line);background:var(--glass);color:var(--text);font-size:12px}
.mclip input{width:70px}
.mclip audio{height:32px;flex:1;min-width:220px}
.slot .meta{min-width:0;flex:1}
.slot .t{font-weight:600}
.slot .s{color:var(--muted);font-size:12px}
@@ -176,7 +197,7 @@ main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:
</head>
<body>
<header class="top">
<div class="brand"><img src="/wordmark.png" alt="PSGFX"><span>1.2</span></div>
<div class="brand"><img src="/wordmark.png" alt="PSGFX"><span>1.3</span></div>
<nav class="views" aria-label="View"><button data-v="art" aria-pressed="true">Art</button><button data-v="layout" aria-pressed="false">Home layout</button></nav>
<form class="connect" id="cf">
<span class="dot" id="dot" aria-hidden="true"></span>
@@ -208,7 +229,7 @@ main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:
<div class="titlezone"><div class="tname" id="tname"></div></div>
<div class="play" aria-hidden="true">Play</div>
<div class="staged-badge" id="badge">Preview - not applied yet</div>
<div class="stage-hint">Drop an image on the tile or the background</div>
<div class="stage-hint">Drop an image on the tile or the background, or a song anywhere</div>
<div class="drop d-bg" data-kind="background">Background</div>
<div class="drop d-icon" data-kind="icon">Icon</div>
</div>
@@ -218,11 +239,19 @@ main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:
<div class="slots" style="margin-top:20px">
<div class="slot" data-kind="icon"><div class="thumb"></div><div class="meta"><div class="t">Icon</div><div class="s">Square, 512 × 512 or larger</div><div class="row"><button class="btn pick">Choose image</button><button class="btn clear hidden">Remove</button></div></div></div>
<div class="slot bgslot" data-kind="background"><div class="thumb"></div><div class="meta"><div class="t">Background</div><div class="s">16:9, ideally 3840 × 2160</div><div class="row"><button class="btn pick">Choose image</button><button class="btn clear hidden">Remove</button></div></div></div>
<div class="presets hidden" id="presets"><div class="t">Preset icons</div><div class="s" id="presetsS"></div><div class="row" id="presetsRow"></div></div>
<div class="slot musicslot" data-kind="music"><div class="thumb" aria-hidden="true">&#9835;</div><div class="meta"><div class="t">Music</div><div class="s">MP3, WAV or FLAC. Plays when the tile is selected.</div><div class="row"><button class="btn pick">Choose song</button><button class="btn clear hidden">Remove</button></div></div>
<div class="mclip" id="mclip">
<label>Start <input id="mstart" value="0:00" inputmode="numeric" title="Where the clip starts in the song (m:ss)"></label>
<label>Length <select id="mlen"><option value="15">15 s</option><option value="30">30 s</option><option value="60">60 s</option><option value="0">Longest that fits</option></select></label>
<audio id="maudio" controls preload="none"></audio>
</div>
</div>
</div>
<div class="actions" style="margin-top:20px">
<button class="btn primary" id="apply" disabled>Apply to PS5</button>
<button class="btn" id="restore">Restore original art</button>
<button class="btn" id="restore">Restore original</button>
<span class="note" id="anote">Close the app on your PS5 before applying.</span>
</div>
<ul class="log" id="log"></ul>
@@ -273,11 +302,13 @@ main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:
<div class="scrim" id="dlg"><div class="dlg" id="dlgBody"></div></div>
<div class="busyv" id="busyv"><span id="busyT">Working…</span></div>
<input type="file" id="file" accept="image/png,image/jpeg" hidden>
<input type="file" id="afile" accept=".mp3,.wav,.flac,.aif,.aiff,audio/*" hidden>
<script>
const $ = s => document.querySelector(s);
const st = { apps: [], sel: null, staged: {} };
const KINDS = ['icon','background'];
const KINDS = ['icon','background','music'];
const HINT = {icon:'Square, 512 × 512 or larger', background:'16:9, ideally 3840 × 2160', music:'MP3, WAV or FLAC. Plays when the tile is selected.'};
async function api(path, opts={}) {
const r = await fetch(path, opts);
@@ -351,6 +382,27 @@ async function select(a, btn){
const game = a.kind === 'game';
$('#anote').textContent = game ? 'Close the game first. The PS5 may put back its original art when the game updates.' : 'Close the app on your PS5 before applying.';
refreshPreview(true);
loadPresets(a);
}
async function loadPresets(a){
const box = $('#presets'), row = $('#presetsRow');
box.classList.add('hidden'); row.innerHTML = '';
let j; try { j = await api('/api/presets/' + encodeURIComponent(a.title_id)); } catch { return; }
if (st.sel !== a || !j.presets.length) return;
$('#presetsS').textContent = 'Made for ' + j.presets[0].app + '. Pick one to use it as the icon.';
for (const p of j.presets) {
const b = document.createElement('button');
b.style.backgroundImage = `url(/api/preset/${p.i})`; b.title = p.app + ' preset ' + (row.children.length + 1);
b.setAttribute('aria-label', b.title); b.setAttribute('aria-pressed', 'false');
b.onclick = async () => {
row.querySelectorAll('button').forEach(x => x.setAttribute('aria-pressed', 'false'));
try { const r = await api('/api/preset/' + p.i, {method:'POST'}); st.staged.icon = {note: r.note || ''}; b.setAttribute('aria-pressed', 'true'); refreshPreview(false); }
catch (err) { $('#presetsS').textContent = err.message; }
};
row.appendChild(b);
}
box.classList.remove('hidden');
}
function refreshPreview(loadCurrent){
@@ -362,13 +414,17 @@ function refreshPreview(loadCurrent){
bg.src = '/api/current/'+encodeURIComponent(a.title_id)+'?src='+encodeURIComponent(a.src)+'&t='+t; }
document.querySelectorAll('.slot').forEach(sl => {
const k = sl.dataset.kind, s = st.staged[k];
sl.querySelector('.thumb').style.backgroundImage = s ? `url(/api/staged/${k}?t=${t})` : '';
if (k !== 'music') sl.querySelector('.thumb').style.backgroundImage = s ? `url(/api/staged/${k}?t=${t})` : '';
sl.querySelector('.clear').classList.toggle('hidden', !s);
const sEl = sl.querySelector('.s');
if (s && s.note) { sEl.textContent = s.note; sEl.classList.add('warn'); }
else if (s) { sEl.textContent = 'Ready to apply'; sEl.classList.remove('warn'); }
else { sEl.textContent = {icon:'Square, 512 × 512 or larger',background:'16:9, ideally 3840 × 2160'}[k]; sEl.classList.remove('warn'); }
else if (s) { sEl.textContent = s.summary ? 'Ready to apply: ' + s.summary : 'Ready to apply'; sEl.classList.remove('warn'); }
else { sEl.textContent = HINT[k]; sEl.classList.remove('warn'); }
});
const m = st.staged.music;
$('#mclip').classList.toggle('on', !!m);
if (m && m.fresh) { $('#maudio').src = '/api/staged/music?t='+t; m.fresh = false; }
if (!m) $('#maudio').removeAttribute('src');
updateApply();
}
const newName = () => { const v = $('#aname').value.trim(); return v && v !== (st.sel.title_name || st.sel.title_id) ? v : null; };
@@ -383,15 +439,35 @@ async function stage(kind, file){
const sl = document.querySelector(`.slot[data-kind="${kind}"] .s`);
sl.textContent = 'Loading…'; sl.classList.remove('warn');
try {
if (kind === 'music') sl.textContent = 'Converting… this takes a few seconds.';
const j = await api('/api/stage/'+kind, {method:'POST', body: await file.arrayBuffer()});
st.staged[kind] = {note: j.note || ''};
st.staged[kind] = {note: j.note || '', summary: j.summary || '', fresh: true};
if (kind === 'music') { $('#mstart').value = fmtTime(j.start); $('#mlen').value = String(j.duration); }
} catch (err) { sl.textContent = err.message; sl.classList.add('warn'); return; }
refreshPreview(false);
}
const fmtTime = v => Math.floor(v/60) + ':' + String(Math.floor(v%60)).padStart(2,'0');
const parseTime = v => { const p = String(v).trim().split(':').map(Number); if (p.some(isNaN)) return 0; return p.length > 1 ? p[0]*60 + p[1] : p[0]; };
async function reclip(){
const sl = document.querySelector('.slot[data-kind="music"] .s');
sl.textContent = 'Converting…'; sl.classList.remove('warn');
try {
const j = await api('/api/music/clip', {method:'POST', body: JSON.stringify({start: parseTime($('#mstart').value), duration: Number($('#mlen').value)})});
st.staged.music = {note: j.note || '', summary: j.summary || '', fresh: true};
$('#mstart').value = fmtTime(j.start);
} catch (err) { sl.textContent = err.message; sl.classList.add('warn'); return; }
refreshPreview(false);
}
$('#mstart').addEventListener('change', reclip); $('#mlen').addEventListener('change', reclip);
$('#afile').onchange = e => { const f = e.target.files[0]; if (f) stage('music', f); };
const isAudio = f => /^audio\//.test(f.type) || /\.(mp3|wav|flac|aiff?)$/i.test(f.name);
let pickKind = null;
document.querySelectorAll('.slot').forEach(sl => {
sl.querySelector('.pick').onclick = () => { pickKind = sl.dataset.kind; $('#file').value=''; $('#file').click(); };
sl.querySelector('.pick').onclick = () => {
if (sl.dataset.kind === 'music') { $('#afile').value=''; $('#afile').click(); return; }
pickKind = sl.dataset.kind; $('#file').value=''; $('#file').click(); };
sl.querySelector('.clear').onclick = async () => { await api('/api/unstage/'+sl.dataset.kind); delete st.staged[sl.dataset.kind]; refreshPreview(true); };
});
$('#file').onchange = e => { const f = e.target.files[0]; if (f && pickKind) stage(pickKind, f); };
@@ -411,7 +487,7 @@ stageEl.addEventListener('dragover', e => {
});
stageEl.addEventListener('drop', e => {
e.preventDefault(); dragDepth=0; stageEl.classList.remove('dragging');
const f = e.dataTransfer.files[0]; if (f) stage(zoneAt(e.clientX, e.clientY), f);
const f = e.dataTransfer.files[0]; if (f) stage(isAudio(f) ? 'music' : zoneAt(e.clientX, e.clientY), f);
});
window.addEventListener('dragover', e => e.preventDefault()); window.addEventListener('drop', e => e.preventDefault());
@@ -436,7 +512,7 @@ $('#apply').onclick = async () => {
if (artDone) refreshPreview(true); else updateApply();
};
$('#restore').onclick = async () => {
const a = st.sel; showLog(['Restoring original art…'], '');
const a = st.sel; showLog(['Restoring the original art and music…'], '');
try {
const j = await api('/api/restore', {method:'POST', body: JSON.stringify({title_id:a.title_id, src:a.src, kind:a.kind})});
showLog(j.log, 'ok'); refreshPreview(true);
+3
View File
@@ -0,0 +1,3 @@
at9check
at9check.exe
__pycache__/
+115
View File
@@ -0,0 +1,115 @@
// at9check: command-line harness for src/lib/at9 (the C++ snd0.at9 maker).
// SPDX-License-Identifier: GPL-3.0-or-later
//
// at9check IN OUT.at9 [SECONDS] [options]
// SECONDS excerpt length (default 15; "max" or 0 = longest that fits)
// --start S excerpt start (seconds)
// --bitrate K 72..192 kb/s
// --fade-in S / --fade-out S / --loudness L / --true-peak D
// --no-normalize / --no-loop
// --threads N encoder threads (0 = all cores)
// --dump-pcm F write the processed excerpt as raw float64 (left block, then right block)
// --preview F write the processed excerpt as 16-bit WAV (wav_bytes)
// at9check --encode-raw PCM.f64 OUT.at9 [--bitrate K] [--no-loop] [--threads N]
// encode raw planar float64 stereo 48 kHz PCM (left block, then right block) directly.
#include "../../src/lib/at9/at9.h"
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <stdexcept>
#include <string>
#include <vector>
static std::vector<uint8_t> read_file(const std::string &p) {
std::ifstream f(p, std::ios::binary);
if (!f) throw std::runtime_error("cannot read " + p);
return std::vector<uint8_t>((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
}
static void write_file(const std::string &p, const void *d, size_t n) {
std::ofstream f(p, std::ios::binary);
f.write((const char *)d, (std::streamsize)n);
if (!f) throw std::runtime_error("cannot write " + p);
}
int main(int argc, char **argv) {
try {
std::vector<std::string> pos;
at9::Options o;
unsigned threads = 0;
std::string dump, preview, raw;
for (int i = 1; i < argc; i++) {
std::string a = argv[i];
auto next = [&]() -> std::string {
if (i + 1 >= argc) throw std::runtime_error("missing value for " + a);
return argv[++i];
};
if (a == "--start") o.start_sec = std::atof(next().c_str());
else if (a == "--bitrate") o.bitrate_kbps = std::atoi(next().c_str());
else if (a == "--fade-in") o.fade_in = std::atof(next().c_str());
else if (a == "--fade-out") o.fade_out = std::atof(next().c_str());
else if (a == "--loudness") o.lufs = std::atof(next().c_str());
else if (a == "--true-peak") o.true_peak_db = std::atof(next().c_str());
else if (a == "--no-normalize") o.normalize = false;
else if (a == "--no-loop") o.loop = false;
else if (a == "--threads") threads = (unsigned)std::atoi(next().c_str());
else if (a == "--dump-pcm") dump = next();
else if (a == "--preview") preview = next();
else if (a == "--encode-raw") raw = next();
else pos.push_back(a);
}
if (!raw.empty()) {
if (pos.size() != 1) throw std::runtime_error("usage: at9check --encode-raw PCM.f64 OUT.at9");
std::vector<uint8_t> b = read_file(raw);
size_t n = b.size() / 16;
std::vector<double> l(n), r(n);
std::memcpy(l.data(), b.data(), n * 8);
std::memcpy(r.data(), b.data() + n * 8, n * 8);
auto t0 = std::chrono::steady_clock::now();
std::vector<uint8_t> data = at9::detail::encode_atrac9(l, r, o.bitrate_kbps, threads);
std::vector<uint8_t> file = at9::detail::build_at9(o.bitrate_kbps, (uint32_t)n, data, o.loop);
double dt = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
write_file(pos[0], file.data(), file.size());
std::printf("{\"bytes\": %zu, \"samples\": %zu, \"encode_seconds\": %.3f}\n", file.size(), n, dt);
return 0;
}
if (pos.size() < 2 || pos.size() > 3) {
std::fprintf(stderr, "usage: at9check IN OUT.at9 [SECONDS|max] [options]\n");
return 2;
}
if (pos.size() == 3) o.duration_sec = pos[2] == "max" ? 0 : std::atof(pos[2].c_str());
auto t0 = std::chrono::steady_clock::now();
std::vector<uint8_t> bytes = read_file(pos[0]);
at9::Audio audio;
std::string err;
if (!at9::decode_file(bytes, audio, err)) throw std::runtime_error(err);
auto t1 = std::chrono::steady_clock::now();
std::vector<double> l, r;
at9::Result res = at9::detail::make_snd0_ex(audio, o, &l, &r, threads);
auto t2 = std::chrono::steady_clock::now();
write_file(pos[1], res.at9.data(), res.at9.size());
if (!dump.empty()) {
std::vector<double> both(l);
both.insert(both.end(), r.begin(), r.end());
write_file(dump, both.data(), both.size() * 8);
}
if (!preview.empty()) {
std::vector<uint8_t> w = at9::wav_bytes(res.processed);
write_file(preview, w.data(), w.size());
}
std::printf("{\"input_rate\": %d, \"input_channels\": %d, \"input_frames\": %zu, \"bytes\": %zu, "
"\"seconds\": %.6f, \"loudness_param\": \"%s\", \"decode_seconds\": %.3f, "
"\"make_snd0_seconds\": %.3f}\n",
audio.rate, audio.channels, audio.pcm.size() / (audio.channels ? audio.channels : 1),
res.at9.size(), res.seconds, res.loudness_param.c_str(),
std::chrono::duration<double>(t1 - t0).count(), std::chrono::duration<double>(t2 - t1).count());
return 0;
} catch (const std::exception &e) {
std::fprintf(stderr, "error: %s\n", e.what());
return 1;
}
}
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Build the at9check harness. Usage: tools/at9check/build.sh [g++|x86_64-w64-mingw32-g++]
set -e
here=$(cd "$(dirname "$0")" && pwd)
root=$(cd "$here/../.." && pwd)
cxx=${1:-${CXX:-g++}}
out="$here/at9check"
extra="-pthread"
case "$cxx" in
*mingw*) out="$here/at9check.exe"; extra="-static -pthread" ;;
esac
"$cxx" -std=c++17 -O2 -Wall -Wextra -Wno-unused-function \
"$here/at9check.cpp" "$root"/src/lib/at9/at9_encoder.cpp "$root"/src/lib/at9/at9_snd0.cpp \
"$root"/src/lib/at9/at9_decode.cpp "$root"/src/lib/at9/at9_tables.cpp \
-o "$out" $extra
echo "built $out"
+233
View File
@@ -0,0 +1,233 @@
#!/usr/bin/env python3
# Compare the C++ snd0.at9 maker (tools/at9check) against the Python reference
# (PS5 AT9 Converter, https://github.com/blackbearreloaded/ps5-at9-converter).
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Usage: tools/at9check/compare.py /path/to/ps5-at9-converter [WORKDIR]
#
# For each generated input it runs the Python CLI and the C++ harness with the
# same options, then reports:
# - whether the .at9 files are byte-identical, and the first differing offset;
# - header (first 168 bytes / chunk layout) equality;
# - processed-PCM difference (C++ vs Python pipeline before encoding);
# - encoder-only identity: both encoders fed the very same PCM;
# - SNR of each decoded file (Python reference decoder) vs the processed input,
# and of the two decoded files vs each other;
# - file size vs the 2 MiB limit, and timings.
import json
import math
import os
import shutil
import subprocess
import sys
import time
import numpy as np
REF = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "/tmp/claude-0/at9")
WORK = os.path.abspath(sys.argv[2] if len(sys.argv) > 2 else "at9check-work")
HERE = os.path.dirname(os.path.abspath(__file__))
EXE = os.path.join(HERE, "at9check")
sys.path.insert(0, REF)
from ps5at9 import at9file, atrac9, audio_io, dsp, wav # noqa: E402
from ps5at9.atrac9_encoder import Encoder # noqa: E402
RATE = 48000
def write_wav_any(path, x, rate, kind):
"""x: (channels, frames) float in [-1, 1]. kind: pcm16 | pcm24 | float32."""
x = np.atleast_2d(x)
ch, n = x.shape
inter = x.T
if kind == "float32":
payload, tag, bits = inter.astype("<f4").tobytes(), 3, 32
else:
bits = 16 if kind == "pcm16" else 24
scale = float(1 << (bits - 1))
ints = np.clip(np.round(inter * scale), -scale, scale - 1).astype("<i4")
payload = ints.astype("<i2").tobytes() if bits == 16 else \
np.ascontiguousarray(ints).view(np.uint8).reshape(n, ch, 4)[:, :, :3].tobytes()
tag = 1
import struct
w = bits // 8
fmt = struct.pack("<HHIIHH", tag, ch, rate, rate * ch * w, ch * w, bits)
body = b"WAVE" + b"fmt " + struct.pack("<I", len(fmt)) + fmt + b"data" + struct.pack("<I", len(payload)) + payload
if len(payload) & 1:
body += b"\0"
with open(path, "wb") as f:
f.write(b"RIFF" + struct.pack("<I", len(body)) + body)
def make_inputs():
os.makedirs(WORK, exist_ok=True)
rng = np.random.default_rng(12345)
items = []
def add(name, x, rate, kind, args=(), seconds=None):
p = os.path.join(WORK, name)
write_wav_any(p, x, rate, kind)
items.append((name, p, list(args), seconds))
t = np.arange(20 * RATE) / RATE
f0, f1 = 30.0, 18000.0
sweep = 0.5 * np.sin(2 * np.pi * f0 * 20 / math.log(f1 / f0) * (np.exp(t / 20 * math.log(f1 / f0)) - 1))
add("sweep-48k-16.wav", np.vstack([sweep, sweep]), RATE, "pcm16")
add("noise-48k-f32.wav", np.clip(rng.standard_normal((2, 16 * RATE)) * 0.25, -1, 1), RATE, "float32")
t44 = np.arange(20 * 44100) / 44100
tones = sum(a * np.sin(2 * np.pi * f * t44 + p) for a, f, p in
((0.2, 110, 0), (0.15, 220.5, 1), (0.1, 440, 2), (0.08, 1318.5, 0.3), (0.05, 3520, 0.7)))
env = 0.6 + 0.4 * np.sin(2 * np.pi * 0.5 * t44) ** 2
noise = rng.standard_normal((2, len(t44))) * 0.03
music = np.vstack([tones * env, np.roll(tones, 300) * env]) + noise
add("music-44k-24.wav", music, 44100, "pcm24")
add("silence-48k-16.wav", np.zeros((2, 10 * RATE)), RATE, "pcm16")
t2 = np.arange(2 * RATE) / RATE
add("short-2s-48k-16.wav", np.vstack([0.4 * np.sin(2 * np.pi * 660 * t2), 0.4 * np.sin(2 * np.pi * 990 * t2)]),
RATE, "pcm16")
t12 = np.arange(12 * RATE) / RATE
add("stereo-diff-48k-16.wav", np.vstack([0.5 * np.sin(2 * np.pi * 523.25 * t12),
np.clip(rng.standard_normal(len(t12)) * 0.2, -1, 1)]), RATE, "pcm16")
add("mono-22k-16.wav", 0.3 * np.sin(2 * np.pi * 300 * np.arange(8 * 22050) / 22050)[None, :], 22050, "pcm16")
# Loud music: exercises the true-peak limiter and an excerpt start.
add("loud-start-48k-16.wav", np.clip(np.vstack([music[0], music[1]])[:, :18 * 44100] * 3.0, -1, 1),
44100, "pcm16", args=["--start", "2.5"])
# Long input for the timing of an 85 s excerpt.
tl = np.arange(90 * RATE) / RATE
long = 0.3 * np.sin(2 * np.pi * 220 * tl) * (0.5 + 0.5 * np.sin(2 * np.pi * 0.1 * tl)) + \
rng.standard_normal((2, len(tl))) * 0.02
add("long-90s-48k-16.wav", long, RATE, "pcm16", seconds="85")
ff = shutil.which("ffmpeg")
if ff:
src = os.path.join(WORK, "music-44k-24.wav")
mp3 = os.path.join(WORK, "music.mp3")
subprocess.run([ff, "-loglevel", "error", "-y", "-i", src, "-c:a", "libmp3lame", "-b:a", "192k", mp3],
check=True)
items.append(("music.mp3", mp3, [], None))
flac = os.path.join(WORK, "music.flac")
subprocess.run([ff, "-loglevel", "error", "-y", "-i", src, "-c:a", "flac", flac], check=True)
items.append(("music.flac", flac, [], None))
aiff = os.path.join(WORK, "music.aiff")
subprocess.run([ff, "-loglevel", "error", "-y", "-i", src, "-c:a", "pcm_s16be", aiff], check=True)
items.append(("music.aiff", aiff, [], None))
for name in ("tone-44k-stereo.mp3", "tone-44k.flac"):
p = os.path.join(REF, "tests", "data", name)
if os.path.exists(p):
items.append((name, p, [], None))
return items
def py_processed(path, start=0.0, duration=15.0, bitrate=192, loop=True):
"""The Python CLI pipeline up to the encoder (mirrors ps5at9/cli.py run())."""
max_samples = (2 * 1024 * 1024 - at9file.header_size(loop)) // (bitrate * 1000 * 256 // (8 * RATE) * 4) \
* 1024 - 256
pcm, rate, offset = audio_io.load(path, start, duration)
pcm = dsp.resample(dsp.to_stereo(pcm), rate, RATE)
skip = int(round(offset * RATE))
available = max(0, pcm.shape[1] - skip)
count = min(available, max_samples) if duration is None else min(available, int(round(duration * RATE)))
pcm = np.ascontiguousarray(pcm[:, skip:skip + count])
lufs = dsp.integrated_loudness(pcm)
if math.isfinite(lufs):
pcm = pcm * 10.0 ** ((-28.0 - lufs) / 20.0)
pcm, _ = dsp.limit_true_peak(pcm, -2.0, RATE)
return dsp.apply_fades(pcm, RATE, 0.01, 0.01)
def decode(blob):
info = at9file.read_at9(blob)
out = atrac9.Decoder(info.config).decode(info.data)
return info, out[:, 256:256 + info.sample_count] / 32768.0
def snr(ref, test):
num = float(np.sum(ref ** 2))
den = float(np.sum((ref - test) ** 2))
if den == 0:
return math.inf
if num == 0:
return -math.inf
return 10 * math.log10(num / den)
def chunks(blob):
out, pos = [], 12
import struct
while pos + 8 <= len(blob):
cid, size = blob[pos:pos + 4], struct.unpack_from("<I", blob, pos + 4)[0]
out.append((cid.decode("latin-1"), size))
pos += 8 + size + (size & 1)
return out
def main():
if not os.path.exists(EXE):
sys.exit("build the harness first: tools/at9check/build.sh")
results = []
all_ok = True
for name, path, args, seconds in make_inputs():
stem = os.path.join(WORK, name.replace(".", "_"))
py_out, cpp_out = stem + ".py.at9", stem + ".cpp.at9"
dur = seconds or "15"
py_args = ["-q", "--duration", dur] + args
t0 = time.time()
subprocess.run([sys.executable, os.path.join(REF, "ps5_at9.py"), "-i", path, "-o", py_out] + py_args,
check=True)
py_time = time.time() - t0
cpp = subprocess.run([EXE, path, cpp_out, dur, "--dump-pcm", stem + ".cpp.f64"] + args,
check=True, capture_output=True, text=True)
meta = json.loads(cpp.stdout)
a, b = open(py_out, "rb").read(), open(cpp_out, "rb").read()
r = {"input": name, "bytes": len(b), "py_bytes": len(a), "identical": a == b,
"cpp_seconds": meta["make_snd0_seconds"], "py_seconds": round(py_time, 2),
"excerpt_s": meta["seconds"], "loudness_param": meta["loudness_param"]}
if a != b:
diff = next((i for i in range(min(len(a), len(b))) if a[i] != b[i]), min(len(a), len(b)))
r["first_diff"] = diff
r["differing_superframes"] = int(sum(a[168 + i * 512:168 + (i + 1) * 512] != b[168 + i * 512:168 + (i + 1) * 512]
for i in range((len(b) - 168) // 512)))
r["header_identical"] = a[:168 - 4] == b[:168 - 4] and chunks(a) == chunks(b)
r["size_ok"] = len(b) <= 2 * 1024 * 1024
# processed PCM: C++ vs Python pipeline
start = float(args[args.index("--start") + 1]) if "--start" in args else 0.0
ref = py_processed(path, start, float(dur))
raw = np.fromfile(stem + ".cpp.f64", dtype="<f8")
cpp_pcm = raw.reshape(2, -1)
r["pcm_max_abs_diff"] = float(np.max(np.abs(cpp_pcm - ref))) if cpp_pcm.shape == ref.shape else "shape"
# Encoder only: both encoders on the C++-processed PCM.
enc = Encoder(2, 192)
py_data = enc.encode(cpp_pcm * 32768.0)
py_blob = at9file.build_at9(enc.config, 2, cpp_pcm.shape[1], py_data)
raw_out = stem + ".raw.at9"
subprocess.run([EXE, "--encode-raw", stem + ".cpp.f64", raw_out], check=True, capture_output=True)
raw_blob = open(raw_out, "rb").read()
r["encoder_only_identical"] = raw_blob == py_blob
if raw_blob != py_blob:
# Same input PCM: the streams must at least decode to the same audio
# (different but equivalent parameter choices; see README notes).
_i, d1 = decode(raw_blob)
_i, d2 = decode(py_blob)
r["encoder_only_decoded_max_diff"] = float(np.max(np.abs(d1 - d2)))
# Decode both with the Python reference decoder.
info_c, dec_c = decode(b)
_info_p, dec_p = decode(a)
r["snr_cpp_vs_input_db"] = round(snr(cpp_pcm, dec_c), 2)
r["snr_py_vs_input_db"] = round(snr(ref, dec_p), 2) if ref.shape == dec_p.shape else None
r["snr_cpp_vs_py_decoded_db"] = round(snr(dec_p, dec_c), 2) if dec_p.shape == dec_c.shape else None
ok = r["header_identical"] and r["size_ok"] and (
r["encoder_only_identical"] or r["encoder_only_decoded_max_diff"] < 1e-6)
if not r["identical"] and r["snr_cpp_vs_py_decoded_db"] != math.inf:
# Must stay well below the coding noise.
ok = ok and r["snr_cpp_vs_py_decoded_db"] is not None and \
r["snr_cpp_vs_py_decoded_db"] > r["snr_cpp_vs_input_db"] + 10
r["ok"] = ok
all_ok &= ok
results.append(r)
print(json.dumps(r), flush=True)
print("ALL OK" if all_ok else "SOME CHECKS FAILED")
return 0 if all_ok else 1
if __name__ == "__main__":
sys.exit(main())
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
# Generate src/lib/at9/at9_tables.{h,cpp} from ps5at9/atrac9_tables.py
# (PS5 AT9 Converter, which converted them from LibAtrac9, MIT License,
# Copyright (c) 2018 Alex Barney).
#
# Usage: tools/at9check/gen_tables.py /path/to/ps5-at9-converter src/lib/at9
import os
import sys
src, dst = sys.argv[1], sys.argv[2]
sys.path.insert(0, src)
from ps5at9 import atrac9_tables as T # noqa: E402
LICENSE = open(os.path.join(src, "third_party", "LibAtrac9.LICENSE.txt")).read().strip()
HEAD = """// ATRAC9 constant tables, converted from LibAtrac9
// (https://github.com/Thealexbarney/LibAtrac9) via ps5at9/atrac9_tables.py of
// PS5 AT9 Converter. Generated by tools/at9check/gen_tables.py; do not edit.
//
// SPDX-License-Identifier: MIT
//
""" + "\n".join(("// " + l).rstrip() for l in LICENSE.splitlines()) + "\n"
def ints(v, per=20):
v = list(v)
rows = [", ".join(str(x) for x in v[i:i + per]) for i in range(0, len(v), per)]
return "{\n " + ",\n ".join(rows) + "\n}" if v else "{0}"
def dbls(v):
return "{" + ", ".join(repr(float(x)) for x in v) + "}"
maxcode = max(max(c) for b, c in list(T.SF_UNSIGNED.values()) + list(T.SF_SIGNED.values()))
maxcode = max(maxcode, max(max(c) for _p, _b, c in T.SPECTRUM.values()))
assert maxcode < 65536
h = [HEAD, "#pragma once", "#include <cstdint>", "", "namespace at9 {", "namespace tables {", "",
"struct Huff { int size; int value_count_power; const uint8_t *bits; const uint16_t *codes; };", "",
"// Scale factor codebooks indexed by word length (unsigned 1..6, signed 2..5); size 0 = absent.",
"extern const Huff SF_UNSIGNED[7];", "extern const Huff SF_SIGNED[6];",
"// Spectrum codebooks [codebook set][word length 0..7][codebook index]; size 0 = absent.",
"extern const Huff SPECTRUM[2][8][4];",
"extern const int SF_WEIGHTS[8][32];",
"extern const int GRADIENT_MAIN[%d];" % len(T.GRADIENT_MAIN),
"// Band extension tables (decoder only).",
"extern const int BEX_GROUP_INFO[8][3];", "extern const int BEX_VALUE_COUNTS[5][6];",
"extern const int BEX_DATA_LENGTHS[5][6][4];",
"extern const double BEX_MODE0_BANDS3[5][32];", "extern const double BEX_MODE0_BANDS4[5][16];",
"extern const double BEX_MODE0_BANDS5[3][32];",
"extern const double BEX_MODE2_SCALE[%d];" % len(T.BEX_MODE2_SCALE),
"extern const double BEX_MODE3_INITIAL[%d];" % len(T.BEX_MODE3_INITIAL),
"extern const double BEX_MODE3_RATE[%d];" % len(T.BEX_MODE3_RATE),
"extern const double BEX_MODE4_MULTIPLIER[%d];" % len(T.BEX_MODE4_MULTIPLIER),
"", "} // namespace tables", "} // namespace at9", ""]
c = [HEAD, '#include "at9_tables.h"', "", "namespace at9 {", "namespace tables {", ""]
def book(name, bits, codes, vcp):
c.append("static const uint8_t %s_bits[] = %s;" % (name, ints(bits)))
c.append("static const uint16_t %s_codes[] = %s;" % (name, ints(codes)))
return "{%d, %d, %s_bits, %s_codes}" % (len(bits), vcp, name, name)
refs = {}
for n, (b, cc) in sorted(T.SF_UNSIGNED.items()):
refs[n] = book("sfu%d" % n, b, cc, 0)
c.append("const Huff SF_UNSIGNED[7] = {{0, 0, nullptr, nullptr}, %s};" %
", ".join(refs.get(n, "{0, 0, nullptr, nullptr}") for n in range(1, 7)))
refs = {}
for n, (b, cc) in sorted(T.SF_SIGNED.items()):
refs[n] = book("sfs%d" % n, b, cc, 0)
c.append("const Huff SF_SIGNED[6] = {%s};" % ", ".join(refs.get(n, "{0, 0, nullptr, nullptr}") for n in range(6)))
refs = {}
for (s, w, ci), (p, b, cc) in sorted(T.SPECTRUM.items()):
refs[(s, w, ci)] = book("sp%d_%d_%d" % (s, w, ci), b, cc, p)
rows = []
for s in range(2):
ws = []
for w in range(8):
ws.append("{" + ", ".join(refs.get((s, w, ci), "{0, 0, nullptr, nullptr}") for ci in range(4)) + "}")
rows.append("{" + ",\n ".join(ws) + "}")
c.append("const Huff SPECTRUM[2][8][4] = {\n " + ",\n ".join(rows) + "};")
c.append("const int SF_WEIGHTS[8][32] = {%s};" % ",\n ".join(ints(r, 32) for r in T.SF_WEIGHTS))
c.append("const int GRADIENT_MAIN[%d] = %s;" % (len(T.GRADIENT_MAIN), ints(T.GRADIENT_MAIN, 48)))
c.append("const int BEX_GROUP_INFO[8][3] = {%s};" % ", ".join(ints(r) for r in T.BEX_GROUP_INFO))
c.append("const int BEX_VALUE_COUNTS[5][6] = {%s};" % ", ".join(ints(r) for r in T.BEX_VALUE_COUNTS))
c.append("const int BEX_DATA_LENGTHS[5][6][4] = {%s};" %
", ".join("{" + ", ".join(ints(x) for x in r) + "}" for r in T.BEX_DATA_LENGTHS))
for name, rows_, w in (("BEX_MODE0_BANDS3", T.BEX_MODE0_BANDS3, 32), ("BEX_MODE0_BANDS4", T.BEX_MODE0_BANDS4, 16),
("BEX_MODE0_BANDS5", T.BEX_MODE0_BANDS5, 32)):
c.append("const double %s[%d][%d] = {%s};" % (name, len(rows_), w, ",\n ".join(dbls(r) for r in rows_)))
for name in ("BEX_MODE2_SCALE", "BEX_MODE3_INITIAL", "BEX_MODE3_RATE", "BEX_MODE4_MULTIPLIER"):
v = getattr(T, name)
c.append("const double %s[%d] = %s;" % (name, len(v), dbls(v)))
c += ["", "} // namespace tables", "} // namespace at9", ""]
with open(os.path.join(dst, "at9_tables.h"), "w") as f:
f.write("\n".join(h))
with open(os.path.join(dst, "at9_tables.cpp"), "w") as f:
f.write("\n".join(c))
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""Regenerate src/presets_embed.cpp from assets/presets/<App name>/<TITLE ID>/<n>.png (preset icons).
Run from the repository root: python3 tools/embed_presets.py"""
import os, re
root = "assets/presets"
items = []
for app in sorted(os.listdir(root)):
for tid in sorted(os.listdir(os.path.join(root, app))):
d = os.path.join(root, app, tid)
if not os.path.isdir(d) or not re.fullmatch(r"[A-Z]{4}\d{5}", tid): continue
names = sorted((n for n in os.listdir(d) if n.lower().endswith(".png")),
key=lambda n: (int(m.group()) if (m := re.match(r"\d+", n)) else 1 << 30, n))
for n in names: items.append((app, tid, os.path.join(d, n)))
out = ["// Generated by tools/embed_presets.py - do not edit.",
"#include <cstddef>", '#include "presets.h"']
for i, (_, _, path) in enumerate(items):
data = open(path, "rb").read()
out.append(f"static const unsigned char p{i}[] = {{")
for j in range(0, len(data), 24):
out.append(" " + ",".join(str(b) for b in data[j:j + 24]) + ",")
out.append("};")
out.append("extern const Preset PRESETS[] = {")
for i, (app, tid, _) in enumerate(items):
out.append(f' {{"{app}", "{tid}", p{i}, sizeof p{i}}},')
out.append("};")
out.append(f"extern const size_t PRESETS_COUNT = {len(items)};")
open("src/presets_embed.cpp", "w").write("\n".join(out) + "\n")
print(f"wrote src/presets_embed.cpp ({len(items)} icons)")