10 Commits
Author SHA1 Message Date
Claude 5ee7aa9e7d Music: Loop switch to leave out the loop marker
Custom music restarts after about 10 seconds on the home screen even with a
60-second clip, though the file holds the whole clip. Turning Loop off writes
the clip without the smpl loop chunk, to see if the PS5 then plays it all.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zQD8DZVn9N7NJ6NHPLGg
2026-10-11 19:43:08 +00:00
Claude b7705fc110 Add Ko-fi support links
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zQD8DZVn9N7NJ6NHPLGg
2026-10-11 19:30:32 +00:00
Claude 4f634edcee New 2.0 banner and README header
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zQD8DZVn9N7NJ6NHPLGg
2026-10-11 19:29:16 +00:00
Claude ca13f15e48 Screenshots of the 2.0 interface
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zQD8DZVn9N7NJ6NHPLGg
2026-10-11 19:24:53 +00:00
Claude ccea007e2a Move the preset icons to the community library
The built-in preset icons are now community icons in elripalda/psgfx-community,
so the Preset icons row and the embedded copies are gone.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zQD8DZVn9N7NJ6NHPLGg
2026-10-11 19:20:47 +00:00
Claude aeb5d36771 Point community icons at ps5gfx.elripalda.com
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zQD8DZVn9N7NJ6NHPLGg
2026-10-11 19:07:22 +00:00
Claude 178c9cb550 PSGFX 2.0: new glass UI, guided connect, community icons
- Redesigned interface: larger, glass style with a chromatic rim, animated
  view/tab switches, search in the app list, Icon/Background/Music/Name tabs.
- Connecting moved into a centred pop-up with step-by-step instructions;
  the header shows a connection button instead of the IP field.
- Home layout preview: the selected tile keeps its white outline on every
  side, the row slides when the selection moves, Games/Media fade, and the
  background crossfades.
- Hiding or moving a tile off the current tab selects the next one, with Undo.
- Community icons: browse, use, share and report icons per game. The server
  (community-server/, PHP) checks uploads, saves them to a public GitHub repo
  with thumbnails and a site mirror, and has a moderation page.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B3zQD8DZVn9N7NJ6NHPLGg
2026-10-11 18:51:54 +00:00
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
42 changed files with 30979 additions and 355 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
ko_fi: ripalda
+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.
+37 -7
View File
@@ -3,7 +3,21 @@
</p>
<p align="center">
<a href="../../releases/latest"><b>Download PSGFX for Windows</b></a>
<a href="https://github.com/elripalda/psgfx/releases/latest"><img alt="Latest release" src="https://img.shields.io/github/v/release/elripalda/psgfx?label=release&color=3b8cff"></a>
<img alt="Platform: Windows" src="https://img.shields.io/badge/platform-Windows-1f5fd6">
<img alt="For jailbroken PS5" src="https://img.shields.io/badge/for-jailbroken%20PS5-5cd3ff">
<a href="LICENSE"><img alt="License: GPL-3.0-or-later" src="https://img.shields.io/badge/license-GPL--3.0--or--later-a9a6ff"></a>
</p>
<p align="center">
<a href="https://github.com/elripalda/psgfx/releases/latest"><b>Download PSGFX 2.0</b></a> ·
<a href="#how-to-use">How to use</a> ·
<a href="#home-layout">Home layout</a> ·
<a href="#community-icons">Community icons</a>
</p>
<p align="center">
<a href="https://ko-fi.com/ripalda"><img alt="Support me on Ko-fi" src="https://img.shields.io/badge/Support%20me%20on-Ko--fi-ff5e5b?style=for-the-badge&logo=ko-fi&logoColor=white"></a>
</p>
PSGFX gives your PS5 homebrew and games new home-screen art, and lets you arrange the home screen itself: hide tiles like the PlayStation Store, rename anything, move apps between Games and Media, and lock your games in the order you want. Pick an app, drop in any image, and click **Apply**. PSGFX resizes and converts it to the exact format the console expects, uploads it to the right folder, and keeps a backup of the original so you can undo it with one click.
@@ -14,12 +28,15 @@ It works through [PS5 Upload](https://github.com/phantomptr/ps5upload): keep the
## Features
- **New look (2.0).** A redesigned, larger glass interface with smooth animations, and a home-screen preview that slides between tiles like the console does.
- **Community icons (new in 2.0).** Browse icons other PSGFX users made for the game you picked and use one in a click, or share yours. Shared icons are stored in a public GitHub repository and moderated.
- **Custom icons.** Use any PNG or JPEG. PSGFX crops it to a square and saves it at the console's native size.
- **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.
@@ -37,23 +54,31 @@ It works through [PS5 Upload](https://github.com/phantomptr/ps5upload): keep the
1. Download `PSGFX.exe` from the [latest release](../../releases/latest) and double-click it. PSGFX opens in your browser.
2. Open PS5 Upload and make sure it's connected to your PS5.
3. Enter your PS5's IP address (the same one PS5 Upload uses) and click **Connect**.
3. PSGFX asks for your PS5's IP address (the same one PS5 Upload uses). Enter it and click **Connect**. Next time it connects by itself.
4. Choose a homebrew app or an installed game from the list.
5. Drop an image onto the preview's tile (**icon**) or background (**background**), or use the **Choose image** buttons.
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
1. Connect, then click **Home layout** at the top.
2. Pick a tile in the strip under the preview. Choose **Games**, **Media** or **Hidden**, or type a new name.
2. Pick a tile in the strip under the preview. Choose **Games**, **Media** or **Hidden**, or type a new name. When a tile leaves the tab you're on, the next one is selected so you can keep going, and **Undo** brings it back.
3. Drag games into any order, or use **A–Z** / **Z–A**. Tick **Lock order** to keep it that way after you play other games.
4. Click **Apply to PS5**, optionally saving the layout as a preset, then restart the PS5.
![Home layout with the console-style preview](docs/screenshot-layout.png)
PSGFX edits the console's home-screen database (`/system_data/priv/mms/app.db`) through PS5 Upload. It uploads the new database to `/data/psgfx` and has PS5 Upload's console shell copy it into place, then reads it back to check it. Backups and presets are kept in the **PSGFX Layout** folder next to `PSGFX.exe`. If the home screen ever looks wrong, restore a backup, or use Safe Mode → **Rebuild Database**. App Library always comes back on its own; the system adds it regardless of the database.
### Community icons
Pick an app or game: the **Icon** tab shows icons other people shared for it. Click one to use it, then **Apply to PS5**. To share yours, choose or drop an icon, click **Share your icon**, and accept the guidelines. It goes live right away. Use the ⚑ on an icon to report it.
The library is run by `community-server/` (a few PHP files on the PSGFX website that save icons to a public GitHub repository). See [community-server/SETUP.md](community-server/SETUP.md).
![Homebrew app with its current background](docs/screenshot-homebrew.png)
## Tips
@@ -82,7 +107,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 +121,15 @@ 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.
## Support
PSGFX is free. If it made your PS5 look the way you want, you can buy me a coffee on [Ko-fi](https://ko-fi.com/ripalda). Thank you!
+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.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

After

Width:  |  Height:  |  Size: 462 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/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
+3
View File
@@ -0,0 +1,3 @@
config.php
data/*.json
files/
+5
View File
@@ -0,0 +1,5 @@
# Only the four pages are public; the settings and helper files are not.
<FilesMatch "^(config|config\.sample|lib)\.php$">
Require all denied
</FilesMatch>
Options -Indexes
+73
View File
@@ -0,0 +1,73 @@
# Community icons: setting up the server
PSGFX 2.0 lets people share icons with each other. Uploads go to a small PHP script on your own
website, which checks each image and saves it to a public GitHub repository. Your GitHub key stays
on your website, so it never ships inside PSGFX.
**Cost:** nothing. It runs on the web hosting plan you already have (any plan with PHP 8,
including Hostinger's) and a free GitHub repository.
## 1. Make the icons repository on GitHub
1. Go to <https://github.com/new>.
2. Name it `psgfx-community`, set it to **Public**, and tick **Add a README file**.
3. Click **Create repository**.
## 2. Make a key that can only touch that repository
1. Go to <https://github.com/settings/personal-access-tokens/new>.
2. **Token name:** `psgfx-community upload`. **Expiration:** the longest it offers. Put a reminder in
your calendar to make a new one before it runs out (uploads stop working when it expires).
3. **Repository access:** *Only select repositories* → `psgfx-community`.
4. **Permissions** → **Repository permissions** → **Contents** → **Read and write**.
5. Click **Generate token** and copy it (it starts with `github_pat_`). You only see it once.
## 3. Put the script on your website (Hostinger)
1. In hPanel open **Websites** → your site → **File Manager**.
2. Open `public_html` and create a folder called `psgfx`.
3. Open `psgfx` and upload everything from `psgfx-community-server.zip`, then extract it there
(right-click the zip → **Extract**, into the current folder). Delete the zip afterwards.
4. Rename `config.sample.php` to `config.php`, open it, and fill in:
- `GITHUB_TOKEN`: the key from step 2.
- `ADMIN_PASSWORD`: a long password for the moderation page.
- `GITHUB_REPO` only if you used a different name than `elripalda/psgfx-community`.
5. Save.
## 4. Check it
Open `https://YOUR-DOMAIN/psgfx/list.php?title=PPSA99764` in your browser. You should see:
```
{"ok":true,"icons":[]}
```
Then send the address (`https://YOUR-DOMAIN/psgfx/`; PSGFX 2.0 is built for `https://ps5gfx.elripalda.com/`) so it can be built into PSGFX. Until then you can
try it yourself by adding `"community": "https://YOUR-DOMAIN/psgfx/"` to `psgfx.json` next to PSGFX.exe.
## Moderating
Open `https://YOUR-DOMAIN/psgfx/mod.php` and log in with `ADMIN_PASSWORD`.
- Every shared icon is listed, newest first. Reported ones come first.
- An icon is hidden automatically after 3 different people report it, until you **Keep** or **Delete** it.
- **Delete** removes it from GitHub and your site, so it disappears from PSGFX within a minute or two.
- **Delete + block** also stops whoever uploaded it from uploading again.
- You can also delete files straight on GitHub; PSGFX follows whatever is in the repository.
Limits per person are 10 uploads an hour and 30 a day. Change them in `config.php`.
## What's where
| File | What it does |
| --- | --- |
| `upload.php` | Receives an icon from PSGFX, checks it, makes a clean 512 × 512 PNG and a 128 × 128 thumbnail, saves both to GitHub, and keeps a copy in `files/` on your site. |
| `list.php?title=ID` | The icons for one game, newest first. |
| `index.php` | Every game and its icons in one file, for apps that show the whole library. |
| `report.php` | Takes a report about an icon. |
| `mod.php` | Your moderation page. |
| `data/` | Upload limits, reports and blocks. Not reachable from the web. |
| `files/` | Copies of every icon and thumbnail, served by your site. |
In the GitHub repository icons are saved as `icons/<title ID>/<time>_<hash>_<name>.png`, with the
thumbnail at the same name under `thumbs/`.
+22
View File
@@ -0,0 +1,22 @@
<?php
// PSGFX community icons - settings. Copy this file to config.php and fill it in.
// config.php holds your GitHub key: never share it or put it on GitHub.
// The GitHub repository the icons are saved to, as "owner/name". It must be public.
const GITHUB_REPO = 'elripalda/psgfx-community';
const GITHUB_BRANCH = 'main';
// A fine-grained personal access token with access to ONLY that repository,
// permission "Contents: Read and write". See SETUP.md.
const GITHUB_TOKEN = 'github_pat_PASTE_YOURS_HERE';
// Password for mod.php, where you review and delete icons. Pick a long one.
const ADMIN_PASSWORD = 'change-me-to-something-long';
// Limits per person (by IP address).
const UPLOADS_PER_HOUR = 10;
const UPLOADS_PER_DAY = 30;
// An icon is hidden after this many different people report it, until you look at it in mod.php.
const REPORTS_TO_HIDE = 3;
// Largest file accepted, in bytes.
const MAX_UPLOAD_BYTES = 6 * 1024 * 1024;
+1
View File
@@ -0,0 +1 @@
Require all denied
+14
View File
@@ -0,0 +1,14 @@
<?php
// GET index.php -> every game that has community icons, and its icons, in one file.
// Made for apps that show the whole library (for example on the PS5), so they don't have to ask per game.
// { "ok": true, "updated": <unix time>, "titles": { "PPSA12345": [ {id, url, thumb, mirror?, mirror_thumb?, by, time}, ... ] } }
require __DIR__ . '/lib.php';
cors();
$reports = data_read('reports');
$titles = [];
foreach (all_icons() as $i) {
if (is_hidden($reports, $i['id'])) continue;
$titles[$i['title']][] = icon_out($i);
}
ksort($titles);
out(['ok' => true, 'updated' => time(), 'titles' => (object)$titles]);
+127
View File
@@ -0,0 +1,127 @@
<?php
// Shared helpers for the PSGFX community icon server.
declare(strict_types=1);
if (!is_file(__DIR__ . '/config.php')) { http_response_code(500); exit('{"ok":false,"error":"The server is not set up yet (config.php is missing)."}'); }
require __DIR__ . '/config.php';
if (!defined('GITHUB_API')) define('GITHUB_API', 'https://api.github.com');
const DATA_DIR = __DIR__ . '/data';
const MIRROR_DIR = __DIR__ . '/files'; // copies of every icon and thumbnail, served by this site
const TREE_TTL = 90; // seconds the icon list is cached before asking GitHub again
// PSGFX runs on http://127.0.0.1 in the user's browser, so every answer allows any origin.
// Nothing here relies on cookies, so that is safe.
function cors(): void {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Max-Age: 86400');
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') { http_response_code(204); exit; }
}
function out(array $j, int $code = 200): void {
http_response_code($code);
header('Content-Type: application/json');
header('Cache-Control: no-store');
echo json_encode($j, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;
}
function fail(string $msg, int $code = 400): void { out(['ok' => false, 'error' => $msg], $code); }
// Who is asking, as a salted hash: enough to rate-limit and block, without storing addresses.
function who(): string {
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
return substr(hash('sha256', $ip . '|' . GITHUB_TOKEN), 0, 20);
}
// Small JSON files in data/, updated under a lock so two requests can't overwrite each other.
function data_path(string $name): string {
if (!is_dir(DATA_DIR)) mkdir(DATA_DIR, 0750, true);
return DATA_DIR . '/' . $name . '.json';
}
function data_read(string $name): array {
$f = data_path($name);
if (!is_file($f)) return [];
$j = json_decode((string)file_get_contents($f), true);
return is_array($j) ? $j : [];
}
function data_update(string $name, callable $fn) {
$h = fopen(data_path($name), 'c+');
flock($h, LOCK_EX);
$j = json_decode((string)stream_get_contents($h), true);
if (!is_array($j)) $j = [];
$ret = $fn($j);
ftruncate($h, 0); rewind($h);
fwrite($h, json_encode($j, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
fflush($h); flock($h, LOCK_UN); fclose($h);
return $ret;
}
function gh(string $method, string $path, ?array $body = null): array {
$ch = curl_init(GITHUB_API . $path);
$hdr = ['Accept: application/vnd.github+json', 'User-Agent: psgfx-community', 'X-GitHub-Api-Version: 2022-11-28',
'Authorization: Bearer ' . GITHUB_TOKEN];
if ($body !== null) { $hdr[] = 'Content-Type: application/json'; curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); }
curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $hdr, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30]);
$res = curl_exec($ch);
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$j = is_string($res) ? json_decode($res, true) : null;
return [$code, is_array($j) ? $j : []];
}
function valid_title(string $t): bool { return (bool)preg_match('/^[A-Z]{4}\d{5}$/', $t); }
function raw_url(string $path): string { return 'https://raw.githubusercontent.com/' . GITHUB_REPO . '/' . GITHUB_BRANCH . '/' . $path; }
// Every icon in the repository: icons/<TITLE ID>/<time>_<hash>_<name>.png. GitHub is the source of truth,
// so an icon you delete on GitHub disappears from PSGFX too. Cached for TREE_TTL seconds.
function all_icons(bool $fresh = false): array {
$cache = data_path('tree-cache');
if (!$fresh && is_file($cache) && time() - filemtime($cache) < TREE_TTL) {
$j = json_decode((string)file_get_contents($cache), true);
if (is_array($j)) return $j;
}
[$code, $j] = gh('GET', '/repos/' . GITHUB_REPO . '/git/trees/' . GITHUB_BRANCH . '?recursive=1');
if ($code === 404 || $code === 409) $j = ['tree' => []]; // empty repository: no icons yet
elseif ($code !== 200) {
if (is_file($cache)) return json_decode((string)file_get_contents($cache), true) ?: [];
fail('GitHub is not answering right now. Try again in a minute.', 502);
}
$icons = [];
foreach ($j['tree'] ?? [] as $e) {
if (($e['type'] ?? '') !== 'blob') continue;
if (!preg_match('#^icons/([A-Z]{4}\d{5})/((\d+)_([0-9a-f]{8})_?([^/]*))\.png$#', $e['path'], $m)) continue;
$icons[] = ['id' => $e['path'], 'title' => $m[1], 'time' => (int)$m[3], 'by' => str_replace('-', ' ', $m[5]), 'sha' => $e['sha']];
}
usort($icons, fn($a, $b) => $b['time'] <=> $a['time']);
file_put_contents($cache, json_encode($icons), LOCK_EX);
return $icons;
}
function forget_icons(): void { @unlink(data_path('tree-cache')); }
// Reports: { "<icon path>": {"by": [who...], "ok": bool} }. "ok" means you reviewed it and kept it.
function is_hidden(array $reports, string $id): bool {
$r = $reports[$id] ?? null;
return $r && empty($r['ok']) && count($r['by'] ?? []) >= REPORTS_TO_HIDE;
}
// This site's own address, for links into files/. Uses whichever of http/https the request came in on.
function site_base(): string {
$https = ($_SERVER['HTTPS'] ?? '') !== '' && $_SERVER['HTTPS'] !== 'off' || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
$dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
return ($https ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . $dir . '/';
}
function mirror_put(string $path, string $bytes): void {
$f = MIRROR_DIR . '/' . $path;
if (!is_dir(dirname($f))) mkdir(dirname($f), 0755, true);
file_put_contents($f, $bytes);
}
function mirror_delete(string $path): void {
@unlink(MIRROR_DIR . '/' . $path);
@unlink(MIRROR_DIR . '/thumbs/' . substr($path, 6));
}
// What PSGFX and other apps get for one icon. "url"/"thumb" are on GitHub; "mirror"/"mirror_thumb" are on this site.
function icon_out(array $i): array {
$t = 'thumbs/' . substr($i['id'], 6);
$o = ['id' => $i['id'], 'url' => raw_url($i['id']), 'thumb' => raw_url($t), 'by' => $i['by'], 'time' => $i['time']];
if (is_file(MIRROR_DIR . '/' . $i['id'])) { $o['mirror'] = site_base() . 'files/' . $i['id']; $o['mirror_thumb'] = site_base() . 'files/' . $t; }
return $o;
}
+13
View File
@@ -0,0 +1,13 @@
<?php
// GET list.php?title=PPSA12345 -> the community icons for that game, newest first.
require __DIR__ . '/lib.php';
cors();
$title = strtoupper((string)($_GET['title'] ?? ''));
if (!valid_title($title)) fail('Unknown title ID.');
$reports = data_read('reports');
$list = [];
foreach (all_icons() as $i) {
if ($i['title'] !== $title || is_hidden($reports, $i['id'])) continue;
$list[] = icon_out($i);
}
out(['ok' => true, 'icons' => $list]);
+90
View File
@@ -0,0 +1,90 @@
<?php
// mod.php - your moderation page. Log in with ADMIN_PASSWORD from config.php.
// Reported icons come first. Delete removes an icon from GitHub (and this site), so it's gone from PSGFX.
require __DIR__ . '/lib.php';
session_start();
header('Cache-Control: no-store');
header('X-Frame-Options: DENY');
$h = fn($s) => htmlspecialchars((string)$s, ENT_QUOTES);
if (isset($_POST['password'])) {
if (hash_equals(ADMIN_PASSWORD, (string)$_POST['password']) && ADMIN_PASSWORD !== 'change-me-to-something-long') {
session_regenerate_id(true); $_SESSION['mod'] = true; $_SESSION['csrf'] = bin2hex(random_bytes(16));
} else { sleep(2); $err = 'Wrong password.'; }
}
if (isset($_GET['logout'])) { $_SESSION = []; session_destroy(); header('Location: mod.php'); exit; }
$msg = '';
if (!empty($_SESSION['mod']) && isset($_POST['act']) && hash_equals($_SESSION['csrf'], (string)($_POST['csrf'] ?? ''))) {
$id = (string)($_POST['id'] ?? '');
if (preg_match('#^icons/[A-Z]{4}\d{5}/[^/]+\.png$#', $id)) {
if ($_POST['act'] === 'keep') {
data_update('reports', function (array &$r) use ($id) { $r[$id] = ['by' => [], 'ok' => true]; });
$msg = 'Kept. It is visible again and reports were cleared.';
} else {
$deleted = 0;
foreach ([$id, 'thumbs/' . substr($id, 6)] as $p) {
[$c, $j] = gh('GET', '/repos/' . GITHUB_REPO . '/contents/' . $p . '?ref=' . GITHUB_BRANCH);
if ($c !== 200 || empty($j['sha'])) continue;
[$c2] = gh('DELETE', '/repos/' . GITHUB_REPO . '/contents/' . $p, ['message' => "Remove $p", 'sha' => $j['sha'], 'branch' => GITHUB_BRANCH]);
if ($c2 === 200) $deleted++;
}
mirror_delete($id);
data_update('reports', function (array &$r) use ($id) { unset($r[$id]); });
if ($_POST['act'] === 'block') {
$owner = data_read('owners')[$id] ?? null;
if ($owner) data_update('blocked', function (array &$b) use ($owner) { if (!in_array($owner, $b, true)) $b[] = $owner; });
$msg = $owner ? 'Deleted, and that person can no longer upload.' : 'Deleted. (Who uploaded it is unknown, so nobody was blocked.)';
} else $msg = 'Deleted.';
forget_icons();
}
}
}
?><!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>PSGFX community - moderation</title>
<style>
body{margin:0;font:15px/1.5 system-ui,"Segoe UI",sans-serif;background:#070b16;color:#e8eefb}
.wrap{max-width:1100px;margin:0 auto;padding:24px 16px}
h1{font-size:22px;margin:0 0 4px}.m{color:#8c98ae}
form.login{max-width:340px;margin:12vh auto;display:grid;gap:10px}
input[type=password]{padding:10px 12px;border-radius:10px;border:1px solid #2a3552;background:#0f1628;color:inherit;font:inherit}
button{padding:7px 12px;border-radius:9px;border:1px solid #2a3552;background:#16203a;color:inherit;font:inherit;cursor:pointer}
button.p{background:#3d7bff;border-color:transparent}button.d{background:#5a1d26;border-color:#7a2a35}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:14px;margin-top:18px}
.c{background:#0f1628;border:1px solid #1f2a45;border-radius:14px;padding:10px}
.c.rep{border-color:#a0553a}.c img{width:100%;aspect-ratio:1;border-radius:10px;background:#1a2440;display:block}
.c .t{font-weight:600;margin-top:8px}.c .s{color:#8c98ae;font-size:13px}.c .r{color:#ffb547;font-size:13px}
.c form{display:inline}.acts{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}
.msg{background:#13304a;border:1px solid #2f6bff;padding:8px 12px;border-radius:10px;margin-top:12px}
</style></head><body><div class="wrap">
<?php if (empty($_SESSION['mod'])): ?>
<form class="login" method="post"><h1>PSGFX moderation</h1>
<?php if (ADMIN_PASSWORD === 'change-me-to-something-long'): ?><p class="m">Set ADMIN_PASSWORD in config.php first.</p><?php endif; ?>
<?php if (!empty($err)): ?><p class="r"><?= $h($err) ?></p><?php endif; ?>
<input type="password" name="password" placeholder="Password" autofocus><button class="p">Log in</button></form>
<?php else:
$icons = all_icons(true); $reports = data_read('reports');
$n = fn($i) => count($reports[$i['id']]['by'] ?? []);
usort($icons, fn($a, $b) => ($n($b) <=> $n($a)) ?: ($b['time'] <=> $a['time']));
$csrf = $_SESSION['csrf'];
?>
<h1>Community icons</h1>
<p class="m"><?= count($icons) ?> icons. Reported ones come first; at <?= REPORTS_TO_HIDE ?> reports an icon is hidden until you keep or delete it. <a href="?logout" style="color:#5b90ff">Log out</a></p>
<?php if ($msg): ?><div class="msg"><?= $h($msg) ?></div><?php endif; ?>
<div class="grid">
<?php foreach (array_slice($icons, 0, 300) as $i): $r = $n($i); $hidden = is_hidden($reports, $i['id']);
$src = is_file(MIRROR_DIR . '/' . $i['id']) ? 'files/' . $i['id'] : raw_url($i['id']); ?>
<div class="c<?= $r ? ' rep' : '' ?>"><img src="<?= $h($src) ?>" alt="" loading="lazy">
<div class="t"><?= $h($i['title']) ?></div>
<div class="s"><?= $h($i['by'] !== '' ? $i['by'] : 'Anonymous') ?> · <?= $h(date('Y-m-d H:i', $i['time'])) ?></div>
<?php if ($r): ?><div class="r"><?= $r ?> report<?= $r > 1 ? 's' : '' ?><?= $hidden ? ' · hidden' : '' ?></div><?php endif; ?>
<div class="acts">
<?php foreach (($r ? ['keep' => 'Keep'] : []) + ['delete' => 'Delete', 'block' => 'Delete + block'] as $act => $label): ?>
<form method="post" <?= $act !== 'keep' ? 'onsubmit="return confirm(\'Delete this icon?\')"' : '' ?>><input type="hidden" name="csrf" value="<?= $h($csrf) ?>"><input type="hidden" name="id" value="<?= $h($i['id']) ?>"><button name="act" value="<?= $act ?>" class="<?= $act === 'keep' ? 'p' : 'd' ?>"><?= $label ?></button></form>
<?php endforeach; ?>
</div></div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div></body></html>
+14
View File
@@ -0,0 +1,14 @@
<?php
// POST report.php id=<icon path> -> one report per person per icon.
require __DIR__ . '/lib.php';
cors();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') fail('Use POST.', 405);
$id = (string)($_POST['id'] ?? '');
if (!preg_match('#^icons/[A-Z]{4}\d{5}/[^/]+\.png$#', $id)) fail('Unknown icon.');
$me = who();
data_update('reports', function (array &$r) use ($id, $me) {
$e = $r[$id] ?? ['by' => [], 'ok' => false];
if (!in_array($me, $e['by'], true)) $e['by'][] = $me;
$r[$id] = $e;
});
out(['ok' => true]);
+69
View File
@@ -0,0 +1,69 @@
<?php
// POST upload.php (multipart): title, name (optional), agree=1, image (PNG or JPEG file).
// Checks the image, turns it into a clean 512 x 512 PNG, and saves it to GitHub at
// icons/<title>/<time>_<hash>_<name>.png, plus a 128 x 128 copy under thumbs/, and keeps a copy of both
// on this site (files/) for consoles that can only use plain http. It shows up in PSGFX straight away.
require __DIR__ . '/lib.php';
cors();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') fail('Use POST.', 405);
if (($_POST['agree'] ?? '') !== '1') fail('Please accept the community guidelines first.');
$title = strtoupper((string)($_POST['title'] ?? ''));
if (!valid_title($title)) fail('Unknown title ID.');
$name = preg_replace('/[^A-Za-z0-9 ._]/', '', (string)($_POST['name'] ?? ''));
$name = trim(substr(preg_replace('/\s+/', ' ', $name), 0, 24));
$f = $_FILES['image'] ?? null;
if (!$f || $f['error'] !== UPLOAD_ERR_OK) fail('No image was received.');
if ($f['size'] > MAX_UPLOAD_BYTES) fail('That image is too large.');
$me = who();
if (in_array($me, data_read('blocked'), true)) fail('Uploads from you are turned off.', 403);
// Rate limit: drop timestamps older than a day, then count.
$now = time();
$allowed = data_update('uploads', function (array &$u) use ($me, $now) {
foreach ($u as $k => $times) { $u[$k] = array_values(array_filter($times, fn($t) => $t > $now - 86400)); if (!$u[$k]) unset($u[$k]); }
$mine = $u[$me] ?? [];
$hour = count(array_filter($mine, fn($t) => $t > $now - 3600));
if ($hour >= UPLOADS_PER_HOUR || count($mine) >= UPLOADS_PER_DAY) return false;
$u[$me][] = $now;
return true;
});
if (!$allowed) fail("You've shared a lot of icons recently. Try again later.", 429);
// Decode and re-encode, so only real pixels reach GitHub (nothing hidden inside the file).
$info = @getimagesize($f['tmp_name']);
if (!$info || !in_array($info[2], [IMAGETYPE_PNG, IMAGETYPE_JPEG], true)) fail("That file isn't a PNG or JPEG image.");
if ($info[0] < 128 || $info[1] < 128) fail('That image is too small. Use one at least 256 x 256.');
if ($info[0] * $info[1] > 40000000) fail('That image is too large.');
$src = $info[2] === IMAGETYPE_PNG ? @imagecreatefrompng($f['tmp_name']) : @imagecreatefromjpeg($f['tmp_name']);
if (!$src) fail("That image couldn't be read.");
$w = imagesx($src); $h = imagesy($src); $side = min($w, $h);
$dst = imagecreatetruecolor(512, 512);
imagealphablending($dst, false); imagesavealpha($dst, true);
imagefill($dst, 0, 0, imagecolorallocatealpha($dst, 0, 0, 0, 127));
imagecopyresampled($dst, $src, 0, 0, intdiv($w - $side, 2), intdiv($h - $side, 2), 512, 512, $side, $side);
ob_start(); imagepng($dst, null, 9); $png = (string)ob_get_clean();
$th = imagecreatetruecolor(128, 128);
imagealphablending($th, false); imagesavealpha($th, true);
imagecopyresampled($th, $dst, 0, 0, 0, 0, 128, 128, 512, 512);
ob_start(); imagepng($th, null, 9); $thumb = (string)ob_get_clean();
imagedestroy($src); imagedestroy($dst); imagedestroy($th);
$hash = substr(sha1($png), 0, 8);
foreach (all_icons() as $i) if ($i['title'] === $title && str_contains($i['id'], '_' . $hash)) fail('That icon is already shared for this game.');
$slug = str_replace(' ', '-', $name);
$path = "icons/$title/{$now}_{$hash}" . ($slug !== '' ? "_$slug" : '') . '.png';
[$code, $j] = gh('PUT', '/repos/' . GITHUB_REPO . '/contents/' . $path, [
'message' => "Add icon for $title" . ($name !== '' ? " by $name" : ''),
'content' => base64_encode($png),
'branch' => GITHUB_BRANCH,
]);
if ($code !== 201 && $code !== 200) fail("Couldn't save the icon to GitHub (error $code). Try again later.", 502);
// The small version for PS5 apps and quick lists. If this one fails, the mirror still has it.
$tpath = 'thumbs/' . substr($path, 6);
gh('PUT', '/repos/' . GITHUB_REPO . '/contents/' . $tpath, ['message' => "Thumbnail for $path", 'content' => base64_encode($thumb), 'branch' => GITHUB_BRANCH]);
mirror_put($path, $png); mirror_put($tpath, $thumb);
data_update('owners', function (array &$o) use ($path, $me) { $o[$path] = $me; });
forget_icons();
out(['ok' => true, 'icon' => icon_out(['id' => $path, 'title' => $title, 'by' => $name, 'time' => $now])]);
Binary file not shown.

Before

Width:  |  Height:  |  Size: 366 KiB

After

Width:  |  Height:  |  Size: 600 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

After

Width:  |  Height:  |  Size: 547 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 458 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 355 KiB

After

Width:  |  Height:  |  Size: 561 KiB

+14 -3
View File
@@ -1,4 +1,4 @@
PSGFX 1.2
PSGFX 2.0
Custom icons and backgrounds for your PS5 homebrew and games, and your home-screen layout.
BEFORE YOU START
@@ -11,15 +11,26 @@ STEPS
1. Double-click PSGFX.exe. PSGFX opens in your browser.
(If Windows SmartScreen warns, click "More info" > "Run anyway".
If the firewall asks, allow it on private networks.)
2. Type your PS5's IP address and click Connect.
2. PSGFX asks for your PS5's IP address. Type it and click Connect.
(Next time it connects by itself. Click the connection button at the top to change it.)
3. Pick a homebrew app or an installed game from the list.
4. Drop an image on the preview's tile (icon) or background (background),
or use the "Choose image" buttons. Any PNG or JPEG works.
5. Close that app or game on the PS5, then click "Apply to PS5".
6. Restart the PS5 to see the new art.
COMMUNITY ICONS (new in 2.0)
- Pick an app or game: the Icon tab shows icons other people shared for it.
Click one to use it, then Apply to PS5.
- To share yours, choose an icon, click "Share your icon" and accept the guidelines.
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
+179 -25
View File
@@ -10,6 +10,7 @@
#include "imaging.h"
#include "ps5client.h"
#include "layout.h"
#include "lib/at9/at9.h"
#include "lib/json.hpp"
#include <atomic>
@@ -27,7 +28,11 @@
#include <shellapi.h>
#include <tlhelp32.h>
#endif
#define STUDIO_VERSION "1.2"
#define STUDIO_VERSION "2.0"
// Community icons server (community-server/ in this repo). psgfx.json "community" overrides it; empty hides the feature.
#ifndef PSGFX_COMMUNITY
#define PSGFX_COMMUNITY "https://ps5gfx.elripalda.com/"
#endif
using json = nlohmann::json;
@@ -40,10 +45,16 @@ 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;
static std::string g_engine; // PS5 Upload's engine, "host:port"; empty = 127.0.0.1:19113
static std::string g_community = PSGFX_COMMUNITY, g_community_set; // the server, and the psgfx.json override if any
static std::map<std::string, Staged> g_staged; // "icon" | "background"
static std::map<std::string, std::vector<uint8_t>> g_icon_cache;
static std::string g_config_path = "psgfx.json";
@@ -54,12 +65,17 @@ static void load_config() {
std::ifstream f(g_config_path);
if (!f && !g_legacy_config_path.empty()) f.open(g_legacy_config_path);
if (!f) return;
try { json j; f >> j; g_ip = j.value("ip", ""); g_engine = j.value("engine", ""); } catch (...) {}
try {
json j; f >> j; g_ip = j.value("ip", ""); g_engine = j.value("engine", "");
g_community_set = j.value("community", "");
if (!g_community_set.empty()) g_community = g_community_set;
} catch (...) {}
}
static void save_config() {
std::ofstream f(g_config_path);
json j = {{"ip", g_ip}};
if (!g_engine.empty()) j["engine"] = g_engine;
if (!g_community_set.empty()) j["community"] = g_community_set;
f << j.dump(2);
}
@@ -385,7 +401,53 @@ 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}, {"loop", s.opt.loop},
{"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), length (seconds; 0 = the longest that fits in the PS5's 2 MB limit) and loop.
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));
s.opt.loop = req.value("loop", s.opt.loop); // off = no loop marker; the PS5 decides what happens at the end
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 +470,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 +481,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 +490,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 +570,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 +597,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 +629,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 +670,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 +684,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 +735,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 +793,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 +802,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 +851,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}};
}
@@ -847,7 +988,7 @@ static void handle(sock_t s, Req &r) {
else if (r.path == "/f/sora700.woff2") { d = sora700; n = sora700_len; }
if (d) { respond(s, 200, "font/woff2", d, n); return; }
}
if (r.path == "/api/config") { std::lock_guard<std::mutex> l(g_mu); respond_json(s, {{"ip", g_ip}}); return; }
if (r.path == "/api/config") { std::lock_guard<std::mutex> l(g_mu); respond_json(s, {{"ip", g_ip}, {"community", g_community}, {"version", STUDIO_VERSION}}); return; }
if (r.path == "/api/connect" && r.method == "POST") {
json j = json::parse(std::string(r.body.begin(), r.body.end()));
{ std::lock_guard<std::mutex> l(g_mu); g_ip = j.value("ip", ""); g_icon_cache.clear(); }
@@ -869,6 +1010,19 @@ 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 == "/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 == "/api/share/icon") { // the staged icon at full size, for sharing with the community
std::vector<uint8_t> b;
{ std::lock_guard<std::mutex> l(g_mu); auto it = g_staged.find("icon"); if (it != g_staged.end()) b = img::to_png(img::cover(it->second.src, 512, 512)); }
if (b.empty()) { respond(s, 404, "text/plain", "none", 4); return; }
respond(s, 200, "image/png", 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; }
+730 -301
View File
File diff suppressed because it is too large. Load diff
+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))