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

|
||||
|
||||
@@ -18,25 +18,42 @@ It works through [PS5 Upload](https://github.com/phantomptr/ps5upload)'s payload
|
||||
- **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.
|
||||
- **One-click restore.** The first time you change something, PSGFX saves the original next to it. **Restore original art** puts it back exactly.
|
||||
- **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** 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.
|
||||
- **Layout presets.** Save a layout when you apply it and re-apply it in one click after a firmware update or database rebuild resets the home screen.
|
||||
- **Home-screen backups.** PSGFX saves the home-screen database before every layout change, plus a copy of the very first one it read. Restore any of them from the Backups dialog.
|
||||
- **No setup.** A single portable Windows app that opens in your browser. It remembers your PS5's IP address.
|
||||
|
||||
## Requirements
|
||||
|
||||
- A jailbroken PS5 with **[PS5 Upload](https://github.com/phantomptr/ps5upload)**'s payload running (the same setup you use to upload homebrew).
|
||||
- **The PS5 Upload app, version 6 or newer, open on the same PC and connected to your PS5.** PSGFX 1.2 and later go through it; PSGFX 1.1 and older only work with PS5 Upload 5.x.
|
||||
- A Windows PC on the same network.
|
||||
|
||||
## How to use
|
||||
|
||||
1. Download `PSGFX.exe` from the [latest release](../../releases/latest) and double-click it. PSGFX opens in your browser.
|
||||
2. Enter your PS5's IP address (the same one PS5 Upload uses) and click **Connect**.
|
||||
3. Choose a homebrew app or an installed game from the list.
|
||||
4. Drop an image onto the preview's tile (**icon**) or background (**background**), or use the **Choose image** buttons.
|
||||
5. Close that app or game on the PS5, then click **Apply to PS5**.
|
||||
6. Restart the PS5 to see the new art on the home screen.
|
||||
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**.
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||

|
||||
|
||||
@@ -51,7 +68,7 @@ To undo, select the app and click **Restore original art**.
|
||||
|
||||
## Build from source
|
||||
|
||||
PSGFX is plain C++17 with no external dependencies. Everything it needs is in `src/lib`.
|
||||
PSGFX is plain C++17 with no external dependencies. Everything it needs is in `src/lib` (including the SQLite amalgamation used for Home layout).
|
||||
|
||||
```bash
|
||||
# Linux / WSL: produces build/PSGFX.exe
|
||||
@@ -66,22 +83,25 @@ 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. It talks to PS5 Upload's payload over its FTX2 protocol on ports 9113 and 9114. It uses the payload's existing commands to list apps, read files, upload them (BLAKE3-verified), copy, 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. 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_ps5.py` is a stand-in for the payload that serves a folder on your computer as if it were a PS5. Use it to develop without a console:
|
||||
`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:
|
||||
|
||||
```bash
|
||||
python3 tools/mock_ps5.py ./fake-ps5 39114 39113 &
|
||||
PS5AS_HOST=127.0.0.1 PS5AS_MGMT_PORT=39114 PS5AS_XFER_PORT=39113 ./build/psgfx
|
||||
python3 tools/mock_engine.py ./fake-ps5 39200 &
|
||||
PS5AS_ENGINE=127.0.0.1:39200 ./build/psgfx
|
||||
```
|
||||
|
||||
If PS5 Upload's engine runs somewhere else (a NAS or Docker), add `"engine": "host:port"` to `psgfx.json`.
|
||||
|
||||
## Credits
|
||||
|
||||
- [PS5 Upload](https://github.com/phantomptr/ps5upload) by phantomptr, whose payload PSGFX talks to
|
||||
- [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.
|
||||
@@ -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.
|
||||
|
After Width: | Height: | Size: 122 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 2.7 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 8.3 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 66 KiB |
@@ -8,13 +8,15 @@ cd "$(dirname "$0")"
|
||||
mkdir -p build
|
||||
|
||||
BLAKE3_FLAGS="-O2 -DBLAKE3_NO_SSE2 -DBLAKE3_NO_SSE41 -DBLAKE3_NO_AVX2 -DBLAKE3_NO_AVX512"
|
||||
SOURCES="src/main.cpp src/ui.cpp src/assets_embed.cpp src/lib/bc7enc.cpp src/lib/bc7decomp.cpp"
|
||||
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 src/presets_embed.cpp src/lib/at9/at9_encoder.cpp src/lib/at9/at9_snd0.cpp src/lib/at9/at9_decode.cpp src/lib/at9/at9_tables.cpp"
|
||||
|
||||
if [[ "${1:-}" == "linux" ]]; then
|
||||
for f in src/lib/blake3.c src/lib/blake3_dispatch.c src/lib/blake3_portable.c; do
|
||||
gcc $BLAKE3_FLAGS -c "$f" -o "build/$(basename "${f%.c}").o"
|
||||
done
|
||||
g++ -O2 -std=c++17 -pthread $SOURCES build/blake3*.o -o build/psgfx
|
||||
[[ -f build/sqlite3.o ]] || gcc $SQLITE_FLAGS -c src/lib/sqlite3.c -o build/sqlite3.o
|
||||
g++ -O2 -std=c++17 -pthread $SOURCES build/blake3*.o build/sqlite3.o -o build/psgfx
|
||||
echo "Built build/psgfx"
|
||||
exit 0
|
||||
fi
|
||||
@@ -23,8 +25,9 @@ if command -v x86_64-w64-mingw32-g++ >/dev/null; then P=x86_64-w64-mingw32-; els
|
||||
for f in src/lib/blake3.c src/lib/blake3_dispatch.c src/lib/blake3_portable.c; do
|
||||
${P}gcc $BLAKE3_FLAGS -c "$f" -o "build/$(basename "${f%.c}").o"
|
||||
done
|
||||
[[ -f build/sqlite3_win.o ]] || ${P}gcc $SQLITE_FLAGS -c src/lib/sqlite3.c -o build/sqlite3_win.o
|
||||
(cd src && ${P}windres psgfx.rc -O coff -o ../build/psgfx_res.o)
|
||||
${P}g++ -O2 -std=c++17 -static -static-libgcc -static-libstdc++ -pthread \
|
||||
$SOURCES build/blake3*.o build/psgfx_res.o -lws2_32 -lshell32 -o build/PSGFX.exe
|
||||
$SOURCES build/blake3*.o build/sqlite3_win.o build/psgfx_res.o -lws2_32 -lshell32 -o build/PSGFX.exe
|
||||
${P}strip build/PSGFX.exe
|
||||
echo "Built build/PSGFX.exe"
|
||||
@@ -1,26 +1,42 @@
|
||||
PSGFX 1.0
|
||||
Custom icons and backgrounds for your PS5 homebrew and games.
|
||||
|
||||
BEFORE YOU START
|
||||
- PS5 Upload's payload must be running on your PS5 (the same setup you use to upload homebrew).
|
||||
- Your PC and PS5 must be on the same network.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
UNDO
|
||||
- Select the app and click "Restore original art".
|
||||
|
||||
TIPS
|
||||
- Best results: icons 512x512 or larger, backgrounds 3840x2160.
|
||||
- A game update may bring back that game's original art. Just apply yours again.
|
||||
- Your PS5 IP is saved in psgfx.json next to PSGFX.exe.
|
||||
- To quit, close the black console window.
|
||||
PSGFX 1.3
|
||||
Custom icons and backgrounds for your PS5 homebrew and games, and your home-screen layout.
|
||||
|
||||
BEFORE YOU START
|
||||
- PS5 Upload's payload must be running on your PS5 (the same setup you use to upload homebrew).
|
||||
- The PS5 Upload app (version 6 or newer) must be open on this PC and connected
|
||||
to your PS5. PSGFX does its work through it.
|
||||
- Your PC and PS5 must be on the same network.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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".
|
||||
|
||||
HOME LAYOUT (new in 1.1)
|
||||
1. Connect, then click "Home layout" at the top.
|
||||
2. Select a tile: choose Games, Media or Hidden, or rename it.
|
||||
3. Drag games into order or use A-Z / Z-A. Tick "Lock order" to keep it.
|
||||
4. Click "Apply to PS5" (optionally save it as a preset), then restart the PS5.
|
||||
- Backups and presets live in the "PSGFX Layout" folder next to PSGFX.exe.
|
||||
Use "Backups" to undo, or Safe Mode > Rebuild Database as a last resort.
|
||||
- After a firmware update, open "Presets", load your layout and apply it again.
|
||||
|
||||
TIPS
|
||||
- Best results: icons 512x512 or larger, backgrounds 3840x2160.
|
||||
- A game update may bring back that game's original art. Just apply yours again.
|
||||
- Your PS5 IP is saved in psgfx.json next to PSGFX.exe.
|
||||
- To quit, close the black console window.
|
||||
@@ -0,0 +1,361 @@
|
||||
// Home layout: hide, rename, move between Games/Media and reorder home-screen tiles by
|
||||
// editing the console's home-screen database, /system_data/priv/mms/app.db.
|
||||
//
|
||||
// Schema (per console user <u>):
|
||||
// tbl_iconinfo_<u> one row per tile: titleId, titleName, dispLocation, visible,
|
||||
// lastAccessIndex/Time, lastPlayed*, recentActivity*
|
||||
// tbl_concepticoninfo_<u> per-concept name/art: conceptName, icon0Info, pic0Info
|
||||
// tbl_group_<u> groupName 'MyHome': which system tiles (PS Plus, Store,
|
||||
// Game Library) appear on the Games row
|
||||
// tbl_contentinfo, tbl_conceptmetadata global copies of name/location/recency
|
||||
// tbl_version counters: access_index, played_index
|
||||
// dispLocation is a bit field: 0x02 = Games home, 0x04 = Media home. Only those two
|
||||
// bits are ever changed. The home screen sorts by play history, so ordering sets every
|
||||
// recency field consistently.
|
||||
#pragma once
|
||||
#include "lib/sqlite3.h"
|
||||
#include "lib/json.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace layout {
|
||||
|
||||
using json = nlohmann::json;
|
||||
struct Error : std::runtime_error { using std::runtime_error::runtime_error; };
|
||||
|
||||
const char *const DB_PATH = "/system_data/priv/mms/app.db";
|
||||
const char *const DB_DIR = "/system_data/priv/mms";
|
||||
const char *const LIBRARY = "NPXS40071";
|
||||
constexpr int64_t BIT_GAMES = 0x02, BIT_MEDIA = 0x04;
|
||||
|
||||
// Disc placeholders and similar internal tiles; never shown.
|
||||
static const std::set<std::string> kInternal = {"NPXS40140", "NPXS40144", "NPXS40145", "NPXS40148",
|
||||
"NPXS40149", "NPXS40150", "NPXS40205", "NPXS40106", "NPXS40063"};
|
||||
|
||||
using Val = std::variant<std::nullptr_t, int64_t, std::string>;
|
||||
|
||||
// An app.db loaded into memory. Nothing touches a file until serialize().
|
||||
class DB {
|
||||
public:
|
||||
explicit DB(const std::vector<uint8_t> &data) {
|
||||
if (sqlite3_open(":memory:", &db_) != SQLITE_OK) throw Error("Couldn't start SQLite");
|
||||
auto *buf = (unsigned char *)sqlite3_malloc64(data.size());
|
||||
if (!buf) throw Error("Out of memory");
|
||||
memcpy(buf, data.data(), data.size());
|
||||
if (sqlite3_deserialize(db_, "main", buf, (sqlite3_int64)data.size(), (sqlite3_int64)data.size(),
|
||||
SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE) != SQLITE_OK)
|
||||
throw Error("That isn't a readable home-screen database");
|
||||
std::string ok = scalar_str("PRAGMA integrity_check");
|
||||
if (ok != "ok") throw Error("The home-screen database failed its integrity check: " + ok);
|
||||
}
|
||||
~DB() { if (db_) sqlite3_close(db_); }
|
||||
DB(const DB &) = delete; DB &operator=(const DB &) = delete;
|
||||
|
||||
std::vector<uint8_t> serialize() {
|
||||
sqlite3_int64 n = 0;
|
||||
unsigned char *p = sqlite3_serialize(db_, "main", &n, 0);
|
||||
if (!p) throw Error("Couldn't save the database");
|
||||
std::vector<uint8_t> out(p, p + n);
|
||||
sqlite3_free(p);
|
||||
return out;
|
||||
}
|
||||
|
||||
void exec(const std::string &sql, const std::vector<Val> &args = {}) {
|
||||
sqlite3_stmt *st = prepare(sql, args);
|
||||
int rc = sqlite3_step(st);
|
||||
sqlite3_finalize(st);
|
||||
if (rc != SQLITE_DONE && rc != SQLITE_ROW) throw Error(std::string("Database error: ") + sqlite3_errmsg(db_));
|
||||
}
|
||||
|
||||
// Runs a query, calling fn(stmt) for every row.
|
||||
template <class F> void each(const std::string &sql, const std::vector<Val> &args, F fn) {
|
||||
sqlite3_stmt *st = prepare(sql, args);
|
||||
int rc;
|
||||
while ((rc = sqlite3_step(st)) == SQLITE_ROW) fn(st);
|
||||
sqlite3_finalize(st);
|
||||
if (rc != SQLITE_DONE) throw Error(std::string("Database error: ") + sqlite3_errmsg(db_));
|
||||
}
|
||||
|
||||
std::string scalar_str(const std::string &sql, const std::vector<Val> &args = {}) {
|
||||
std::string out;
|
||||
each(sql, args, [&](sqlite3_stmt *st) { out = text(st, 0); });
|
||||
return out;
|
||||
}
|
||||
int64_t scalar_int(const std::string &sql, const std::vector<Val> &args = {}) {
|
||||
int64_t out = 0;
|
||||
each(sql, args, [&](sqlite3_stmt *st) { out = sqlite3_column_int64(st, 0); });
|
||||
return out;
|
||||
}
|
||||
|
||||
static std::string text(sqlite3_stmt *st, int i) {
|
||||
const unsigned char *t = sqlite3_column_text(st, i);
|
||||
return t ? std::string((const char *)t) : std::string();
|
||||
}
|
||||
static bool null(sqlite3_stmt *st, int i) { return sqlite3_column_type(st, i) == SQLITE_NULL; }
|
||||
|
||||
private:
|
||||
sqlite3 *db_ = nullptr;
|
||||
sqlite3_stmt *prepare(const std::string &sql, const std::vector<Val> &args) {
|
||||
sqlite3_stmt *st = nullptr;
|
||||
if (sqlite3_prepare_v2(db_, sql.c_str(), -1, &st, nullptr) != SQLITE_OK)
|
||||
throw Error(std::string("Database error: ") + sqlite3_errmsg(db_));
|
||||
for (size_t i = 0; i < args.size(); i++) {
|
||||
int k = (int)i + 1;
|
||||
if (auto *n = std::get_if<int64_t>(&args[i])) sqlite3_bind_int64(st, k, *n);
|
||||
else if (auto *s = std::get_if<std::string>(&args[i])) sqlite3_bind_text(st, k, s->c_str(), (int)s->size(), SQLITE_TRANSIENT);
|
||||
else sqlite3_bind_null(st, k);
|
||||
}
|
||||
return st;
|
||||
}
|
||||
};
|
||||
|
||||
inline std::string q(const std::string &id) {
|
||||
std::string o = "\"";
|
||||
for (char c : id) { if (c == '"') o += '"'; o += c; }
|
||||
return o + "\"";
|
||||
}
|
||||
inline std::string strip_query(const std::string &p) { size_t i = p.find('?'); return i == std::string::npos ? p : p.substr(0, i); }
|
||||
|
||||
struct Tile {
|
||||
std::string id, name, concept, kind, where, icon, bg;
|
||||
int64_t disp = 0, home_idx = 0, access = 0;
|
||||
bool visible = false, home = false;
|
||||
};
|
||||
|
||||
struct Info {
|
||||
std::string user, icon_t, concept_t, group_t;
|
||||
std::vector<std::string> users, warnings;
|
||||
std::vector<Tile> tiles;
|
||||
std::vector<std::pair<std::string, int64_t>> ghosts; // MyHome rows for titles not on the console
|
||||
std::map<std::string, std::set<std::string>> cols;
|
||||
bool has_content = false, has_meta = false, can_order = false;
|
||||
int64_t access_index = 0, played_index = 0;
|
||||
|
||||
const Tile *find(const std::string &id) const {
|
||||
for (auto &t : tiles) if (t.id == id) return &t;
|
||||
return nullptr;
|
||||
}
|
||||
json to_json() const {
|
||||
json ts = json::array();
|
||||
for (auto &t : tiles)
|
||||
ts.push_back({{"id", t.id}, {"name", t.name}, {"kind", t.kind}, {"where", t.where}, {"visible", t.visible},
|
||||
{"home", t.home}, {"homeIdx", t.home_idx}, {"access", t.access}, {"icon", t.icon}, {"bg", t.bg}});
|
||||
return {{"user", user}, {"users", users}, {"tiles", ts}, {"warnings", warnings}, {"canOrder", can_order}};
|
||||
}
|
||||
};
|
||||
|
||||
inline Info analyze(DB &db, const std::string &want_user = "") {
|
||||
Info info;
|
||||
std::set<std::string> tables;
|
||||
db.each("SELECT name FROM sqlite_master WHERE type='table'", {}, [&](sqlite3_stmt *st) { tables.insert(DB::text(st, 0)); });
|
||||
int best = -1;
|
||||
for (auto &t : tables) {
|
||||
if (t.rfind("tbl_iconinfo_", 0) != 0) continue;
|
||||
std::string u = t.substr(13);
|
||||
info.users.push_back(u);
|
||||
int n = (int)db.scalar_int("SELECT count(*) FROM " + q(t));
|
||||
if (u == want_user) { info.user = u; best = 1 << 30; }
|
||||
else if (want_user.empty() && n > best) { best = n; info.user = u; }
|
||||
}
|
||||
if (info.user.empty()) throw Error("This console's home-screen database has a layout PSGFX doesn't know yet (no tbl_iconinfo_ tables).");
|
||||
std::sort(info.users.begin(), info.users.end());
|
||||
info.icon_t = "tbl_iconinfo_" + info.user;
|
||||
info.concept_t = tables.count("tbl_concepticoninfo_" + info.user) ? "tbl_concepticoninfo_" + info.user : "";
|
||||
info.group_t = tables.count("tbl_group_" + info.user) ? "tbl_group_" + info.user : "";
|
||||
info.has_content = tables.count("tbl_contentinfo") > 0;
|
||||
info.has_meta = tables.count("tbl_conceptmetadata") > 0;
|
||||
if (info.users.size() > 1)
|
||||
info.warnings.push_back("This console has " + std::to_string(info.users.size()) + " user profiles. You're editing the one with the most tiles; switch with the profile menu.");
|
||||
if (tables.count("tbl_version")) {
|
||||
info.access_index = db.scalar_int("SELECT status FROM tbl_version WHERE category='access_index'");
|
||||
info.played_index = db.scalar_int("SELECT status FROM tbl_version WHERE category='played_index'");
|
||||
}
|
||||
for (auto &t : tables)
|
||||
db.each("SELECT name FROM pragma_table_info(?)", {t}, [&](sqlite3_stmt *st) { info.cols[t].insert(DB::text(st, 0)); });
|
||||
|
||||
struct Concept { std::string name, icon, bg; };
|
||||
std::map<std::string, Concept> concepts;
|
||||
if (!info.concept_t.empty())
|
||||
db.each("SELECT localConceptId, conceptName, icon0Info, pic0Info FROM " + q(info.concept_t), {}, [&](sqlite3_stmt *st) {
|
||||
concepts[DB::text(st, 0)] = {DB::text(st, 1), strip_query(DB::text(st, 2)), strip_query(DB::text(st, 3))};
|
||||
});
|
||||
std::map<std::string, int64_t> home;
|
||||
if (!info.group_t.empty())
|
||||
db.each("SELECT itemId, idx FROM " + q(info.group_t) + " WHERE groupName='MyHome' ORDER BY idx", {}, [&](sqlite3_stmt *st) {
|
||||
home[DB::text(st, 0)] = sqlite3_column_int64(st, 1);
|
||||
});
|
||||
|
||||
std::set<std::string> seen;
|
||||
db.each("SELECT titleId, titleName, localConceptId, dispLocation, visible, lastAccessIndex, installStatus FROM " + q(info.icon_t), {},
|
||||
[&](sqlite3_stmt *st) {
|
||||
Tile t;
|
||||
t.id = DB::text(st, 0);
|
||||
if (t.id.empty() || kInternal.count(t.id)) return;
|
||||
seen.insert(t.id);
|
||||
t.name = DB::text(st, 1); t.concept = DB::text(st, 2);
|
||||
t.disp = sqlite3_column_int64(st, 3); t.visible = sqlite3_column_int64(st, 4) == 1;
|
||||
t.access = sqlite3_column_int64(st, 5);
|
||||
int64_t install = sqlite3_column_int64(st, 6);
|
||||
auto c = concepts.find(t.concept);
|
||||
if (c != concepts.end()) { if (!c->second.name.empty()) t.name = c->second.name; t.icon = c->second.icon; t.bg = c->second.bg; }
|
||||
t.kind = t.id.rfind("NPXS", 0) == 0 ? "system" : "game";
|
||||
auto h = home.find(t.id); // the console only honours MyHome for its own system tiles
|
||||
if (h != home.end() && t.kind == "system") { t.home = true; t.home_idx = h->second; }
|
||||
if (t.home) t.where = "games";
|
||||
else if (!t.visible) t.where = "hidden";
|
||||
else if (t.disp & BIT_GAMES) t.where = "games";
|
||||
else if (t.disp & BIT_MEDIA) t.where = "media";
|
||||
else t.where = "hidden";
|
||||
if (t.where == "hidden" && install != 2) return; // uninstalled leftovers
|
||||
info.tiles.push_back(t);
|
||||
});
|
||||
for (auto &[id, idx] : home) if (!seen.count(id)) info.ghosts.push_back({id, idx});
|
||||
std::sort(info.ghosts.begin(), info.ghosts.end(), [](auto &a, auto &b) { return a.second < b.second; });
|
||||
std::stable_sort(info.tiles.begin(), info.tiles.end(), [](const Tile &a, const Tile &b) { return a.access > b.access; });
|
||||
info.can_order = info.access_index > 0;
|
||||
return info;
|
||||
}
|
||||
|
||||
inline std::string fmt_time(time_t t) {
|
||||
char b[32]; tm g{};
|
||||
#ifdef _WIN32
|
||||
gmtime_s(&g, &t);
|
||||
#else
|
||||
gmtime_r(&t, &g);
|
||||
#endif
|
||||
strftime(b, sizeof b, "%Y-%m-%d %H:%M:%S.000", &g);
|
||||
return b;
|
||||
}
|
||||
|
||||
inline void insert_before_library(std::vector<std::string> &v, const std::string &id) {
|
||||
if (std::find(v.begin(), v.end(), id) != v.end()) return;
|
||||
auto it = std::find(v.begin(), v.end(), LIBRARY);
|
||||
v.insert(it, id);
|
||||
}
|
||||
|
||||
// req: {edits: {id: {where?, name?}}, recent: [ids], recentChanged, lock}
|
||||
inline void apply(DB &db, const Info &info, const json &req, std::vector<std::string> &log) {
|
||||
db.exec("BEGIN");
|
||||
try {
|
||||
struct Target { std::string table, key; bool by_concept; };
|
||||
std::vector<Target> targets = {{info.icon_t, "titleId", false}};
|
||||
if (!info.concept_t.empty()) targets.push_back({info.concept_t, "localConceptId", true});
|
||||
if (info.has_content) targets.push_back({"tbl_contentinfo", "titleId", false});
|
||||
if (info.has_meta) targets.push_back({"tbl_conceptmetadata", "localConceptId", true});
|
||||
auto key_of = [](const Tile &t, const Target &tg) { return tg.by_concept ? t.concept : t.id; };
|
||||
auto has = [&](const std::string &table, const std::string &col) {
|
||||
auto it = info.cols.find(table); return it != info.cols.end() && it->second.count(col) > 0;
|
||||
};
|
||||
|
||||
std::vector<std::string> home_order;
|
||||
for (auto &t : info.tiles) if (t.home) home_order.push_back(t.id);
|
||||
std::sort(home_order.begin(), home_order.end(), [&](auto &a, auto &b) { return info.find(a)->home_idx < info.find(b)->home_idx; });
|
||||
bool home_changed = false;
|
||||
|
||||
const json edits = req.value("edits", json::object());
|
||||
for (auto &[id, e] : edits.items()) {
|
||||
const Tile *t = info.find(id);
|
||||
if (!t || !e.is_object()) continue;
|
||||
std::vector<std::string> did;
|
||||
std::string where = e.value("where", "");
|
||||
if (where == "hidden") {
|
||||
if (t->home) { home_order.erase(std::remove(home_order.begin(), home_order.end(), id), home_order.end()); home_changed = true; }
|
||||
db.exec("UPDATE " + q(info.icon_t) + " SET visible=0 WHERE titleId=?", {id});
|
||||
did.push_back("hidden");
|
||||
} else if (where == "games" || where == "media") {
|
||||
int64_t set = where == "games" ? BIT_GAMES : BIT_MEDIA, clr = where == "games" ? BIT_MEDIA : BIT_GAMES;
|
||||
for (auto &tg : targets)
|
||||
if (has(tg.table, "dispLocation"))
|
||||
db.exec("UPDATE " + q(tg.table) + " SET dispLocation=((dispLocation | ?) & ~?) WHERE " + q(tg.key) + "=?", {set, clr, key_of(*t, tg)});
|
||||
db.exec("UPDATE " + q(info.icon_t) + " SET visible=1 WHERE titleId=?", {id});
|
||||
if (t->kind == "system" && where == "games" && !t->home) { insert_before_library(home_order, id); home_changed = true; }
|
||||
did.push_back("shown on " + where);
|
||||
}
|
||||
if (e.contains("name") && e["name"].is_string()) {
|
||||
std::string n = e["name"].get<std::string>();
|
||||
while (!n.empty() && n.back() == ' ') n.pop_back();
|
||||
if (!n.empty()) {
|
||||
db.exec("UPDATE " + q(info.icon_t) + " SET titleName=? WHERE titleId=?", {n, id});
|
||||
if (!info.concept_t.empty()) {
|
||||
std::string set = "conceptName=?";
|
||||
std::vector<Val> args = {n};
|
||||
if (has(info.concept_t, "primaryTitleName")) { set += ", primaryTitleName=?"; args.push_back(n); }
|
||||
if (has(info.concept_t, "ucmConceptName")) { set += ", ucmConceptName=CASE WHEN ucmConceptName IS NULL THEN NULL ELSE ? END"; args.push_back(n); }
|
||||
args.push_back(t->concept);
|
||||
db.exec("UPDATE " + q(info.concept_t) + " SET " + set + " WHERE localConceptId=?", args);
|
||||
}
|
||||
if (info.has_content) db.exec("UPDATE tbl_contentinfo SET titleName=? WHERE titleId=?", {n, id});
|
||||
if (info.has_meta) db.exec("UPDATE tbl_conceptmetadata SET conceptName=? WHERE localConceptId=?", {n, t->concept});
|
||||
did.push_back("renamed to \"" + n + "\"");
|
||||
}
|
||||
}
|
||||
if (!did.empty()) {
|
||||
std::string s; for (auto &d : did) s += (s.empty() ? "" : ", ") + d;
|
||||
log.push_back(t->name + ": " + s);
|
||||
}
|
||||
}
|
||||
|
||||
if (home_changed && !info.group_t.empty()) {
|
||||
std::vector<std::string> fin = home_order;
|
||||
for (auto &g : info.ghosts) {
|
||||
if (!fin.empty() && fin.front() == LIBRARY) fin.push_back(g.first);
|
||||
else insert_before_library(fin, g.first);
|
||||
}
|
||||
db.exec("DELETE FROM " + q(info.group_t) + " WHERE groupName='MyHome'");
|
||||
for (size_t i = 0; i < fin.size(); i++)
|
||||
db.exec("INSERT INTO " + q(info.group_t) + " (itemId, groupName, type, idx, lastModifiedDate) VALUES (?, 'MyHome', 'title', ?, NULL)",
|
||||
{fin[i], (int64_t)i + 1});
|
||||
}
|
||||
|
||||
std::vector<std::string> recent;
|
||||
const json recent_in = req.value("recent", json::array());
|
||||
for (auto &x : recent_in) if (x.is_string()) recent.push_back(x.get<std::string>());
|
||||
if (req.value("recentChanged", false) && info.can_order && !recent.empty()) {
|
||||
bool lock = req.value("lock", false);
|
||||
int64_t n = (int64_t)recent.size();
|
||||
time_t base = time(nullptr);
|
||||
int64_t acc = info.access_index + n, played = info.played_index + n;
|
||||
if (lock) { base = 4102401600; acc = 1000000000; played = 1000000000; } // 2099-12-31 12:00 UTC
|
||||
static const char *always[] = {"lastAccessTime", "recentActivityDatePlayedOrInstalled", "lastInteractedTime"};
|
||||
static const char *played_only[] = {"lastPlayedDate", "lastPlayedDateOnConsole", "recentActivityDatePlayedOrPurchased"};
|
||||
std::string first;
|
||||
for (int64_t i = 0; i < n; i++) {
|
||||
const Tile *t = info.find(recent[(size_t)i]);
|
||||
if (!t) continue;
|
||||
if (first.size() < 120) first += (first.empty() ? "" : " > ") + t->name;
|
||||
std::string when = fmt_time(base - i * 60);
|
||||
for (auto &tg : targets) {
|
||||
std::string set; std::vector<Val> args;
|
||||
auto add = [&](const std::string &s, Val v) { set += (set.empty() ? "" : ", ") + s; args.push_back(std::move(v)); };
|
||||
if (has(tg.table, "lastAccessIndex")) add("lastAccessIndex=?", acc - i);
|
||||
if (has(tg.table, "lastPlayedIndex")) add("lastPlayedIndex=CASE WHEN lastPlayedIndex IS NULL THEN NULL ELSE ? END", played - i);
|
||||
for (auto c : always) if (has(tg.table, c)) add(q(c) + "=?", when);
|
||||
for (auto c : played_only) if (has(tg.table, c)) add(q(c) + "=CASE WHEN " + q(c) + " IS NULL THEN NULL ELSE ? END", when);
|
||||
if (set.empty()) continue;
|
||||
args.push_back(key_of(*t, tg));
|
||||
db.exec("UPDATE " + q(tg.table) + " SET " + set + " WHERE " + q(tg.key) + "=?", args);
|
||||
}
|
||||
}
|
||||
if (!lock) {
|
||||
db.exec("UPDATE tbl_version SET status=? WHERE category='access_index'", {acc});
|
||||
db.exec("UPDATE tbl_version SET status=? WHERE category='played_index'", {played});
|
||||
}
|
||||
log.push_back(std::string(lock ? "Order locked" : "Order set") + " for " + std::to_string(n) + " tiles: " + first + (n > 4 ? " > ..." : ""));
|
||||
}
|
||||
db.exec("COMMIT");
|
||||
} catch (...) {
|
||||
try { db.exec("ROLLBACK"); } catch (...) {}
|
||||
throw;
|
||||
}
|
||||
std::string ok = db.scalar_str("PRAGMA integrity_check");
|
||||
if (ok != "ok") throw Error("The edited database failed its integrity check, so nothing was uploaded: " + ok);
|
||||
}
|
||||
|
||||
} // namespace layout
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -1,13 +1,17 @@
|
||||
// PSGFX - change the home-screen icon and background of PS5 homebrew and installed games,
|
||||
// through PS5 Upload's payload.
|
||||
// through PS5 Upload.
|
||||
// Runs a tiny local web server and opens the UI in the default browser.
|
||||
// Talks to PS5 Upload's resident payload (ports 9114 / 9113); nothing is installed on the PS5.
|
||||
// Talks to the PS5 through the PS5 Upload app's local engine (see ps5client.h); nothing is
|
||||
// installed on the PS5.
|
||||
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#define STB_IMAGE_RESIZE_IMPLEMENTATION
|
||||
#define STB_IMAGE_WRITE_IMPLEMENTATION
|
||||
#include "imaging.h"
|
||||
#include "ps5client.h"
|
||||
#include "layout.h"
|
||||
#include "lib/at9/at9.h"
|
||||
#include "presets.h"
|
||||
#include "lib/json.hpp"
|
||||
|
||||
#include <atomic>
|
||||
@@ -18,11 +22,14 @@
|
||||
#include <set>
|
||||
#include <algorithm>
|
||||
#include <sstream>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#ifdef _WIN32
|
||||
#include <shellapi.h>
|
||||
#include <tlhelp32.h>
|
||||
#endif
|
||||
#define STUDIO_VERSION "1.0"
|
||||
#define STUDIO_VERSION "1.3"
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
@@ -35,51 +42,78 @@ 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::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";
|
||||
static std::string g_legacy_config_path; // pre-1.0 name, read once if present
|
||||
static std::string g_data_dir = "PSGFX Layout"; // home-layout backups and presets, next to the exe
|
||||
|
||||
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", ""); } catch (...) {}
|
||||
try { json j; f >> j; g_ip = j.value("ip", ""); g_engine = j.value("engine", ""); } catch (...) {}
|
||||
}
|
||||
static void save_config() {
|
||||
std::ofstream f(g_config_path);
|
||||
f << json{{"ip", g_ip}}.dump(2);
|
||||
json j = {{"ip", g_ip}};
|
||||
if (!g_engine.empty()) j["engine"] = g_engine;
|
||||
f << j.dump(2);
|
||||
}
|
||||
|
||||
static ps5::Client client() {
|
||||
ps5::Client c; c.host = g_ip;
|
||||
if (const char *e = getenv("PS5AS_HOST")) c.host = e; // test hooks (mock PS5)
|
||||
if (const char *e = getenv("PS5AS_MGMT_PORT")) c.mgmt_port = atoi(e);
|
||||
if (const char *e = getenv("PS5AS_XFER_PORT")) c.xfer_port = atoi(e);
|
||||
std::string eng = g_engine;
|
||||
if (const char *e = getenv("PS5AS_ENGINE")) eng = e; // test hook (tools/mock_engine.py)
|
||||
if (!eng.empty()) {
|
||||
size_t colon = eng.rfind(':');
|
||||
c.engine_host = eng.substr(0, colon);
|
||||
if (colon != std::string::npos) c.engine_port = atoi(eng.c_str() + colon + 1);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
static std::string lower(std::string s) { for (auto &ch : s) ch = (char)tolower((unsigned char)ch); return s; }
|
||||
static bool ends_with(const std::string &s, const std::string &t) { return s.size() >= t.size() && s.compare(s.size() - t.size(), t.size(), t) == 0; }
|
||||
static std::string appmeta(const std::string &id) { return "/user/appmeta/" + id; }
|
||||
// Games PS5 Upload runs from a mounted image (ShadowMount+, or its own mounts). Their sce_sys is
|
||||
// inside the image, read-only or nearly full, so their art is changed like an installed game's.
|
||||
static bool mounted_image(const std::string &src) {
|
||||
return src.rfind("/mnt/shadowmnt/", 0) == 0 || src.rfind("/mnt/ps5upload/", 0) == 0;
|
||||
}
|
||||
|
||||
// ─────────────────────────────── PS5 file helpers ─────────────────────
|
||||
static json list_dir(ps5::Client &c, const std::string &dir) {
|
||||
try {
|
||||
json j = json::parse(c.call_str(ps5::FS_LIST_DIR, json{{"path", dir}, {"limit", 4096}}.dump(), ps5::FS_LIST_DIR_ACK));
|
||||
return j.value("entries", json::array());
|
||||
json all = json::array();
|
||||
for (uint64_t off = 0;;) { // the console answers at most 256 entries a call
|
||||
json j = json::parse(c.call_str(ps5::FS_LIST, json{{"path", dir}, {"offset", off}, {"limit", 256}}.dump()));
|
||||
auto e = j.value("entries", json::array());
|
||||
for (auto &x : e) all.push_back(x);
|
||||
if (!j.value("truncated", false) || e.empty()) break;
|
||||
off += e.size();
|
||||
}
|
||||
return all;
|
||||
} catch (...) { return json::array(); }
|
||||
}
|
||||
static bool exists(ps5::Client &c, const std::string &dir, const std::string &name) {
|
||||
for (auto &e : list_dir(c, dir)) if (e.value("name", "") == name) return true;
|
||||
return false;
|
||||
}
|
||||
// FS_COPY's "overwrite" must be a number: the payload reads it as an integer field.
|
||||
static void copy_file(ps5::Client &c, const std::string &from, const std::string &to, bool overwrite) {
|
||||
c.call(ps5::FS_COPY, json{{"from", from}, {"to", to}, {"overwrite", overwrite ? 1 : 0}}.dump(), ps5::FS_COPY_ACK, 30000);
|
||||
// Art files are small, so a copy is a read and a write (PS5 Upload's own copy runs as a job).
|
||||
static void copy_file(ps5::Client &c, const std::string &from, const std::string &to) {
|
||||
auto data = c.read_file(from, 16u << 20);
|
||||
try { c.call(ps5::FS_MKDIR, json{{"path", to.substr(0, to.find_last_of('/'))}}.dump()); } catch (...) {}
|
||||
c.upload(to, data);
|
||||
}
|
||||
|
||||
// Title name from a PS4 param.sfo.
|
||||
@@ -112,27 +146,195 @@ static std::string meta_title(ps5::Client &c, const std::string &id) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// ─────────────────────────────── home layout ──────────────────────────
|
||||
// Edits the home-screen database, /system_data/priv/mms/app.db. PS5 Upload reads it directly,
|
||||
// but only writes under /data, /user and drives, so a new database goes to /data/psgfx first
|
||||
// and PS5 Upload's console shell copies it into place (see push_db).
|
||||
// Every apply re-downloads the database, saves it to PSGFX Layout/backups first, edits
|
||||
// a copy in memory, checks it, then uploads it.
|
||||
namespace fs = std::filesystem;
|
||||
static std::mutex g_layout_mu; // one layout operation at a time
|
||||
static std::string g_layout_user;
|
||||
static std::map<std::string, std::vector<uint8_t>> g_tile_img_cache;
|
||||
|
||||
static fs::path data_path(const std::string &sub) { fs::path p = fs::path(g_data_dir) / sub; fs::create_directories(p); return p; }
|
||||
|
||||
static std::string now_stamp(const char *fmt) {
|
||||
auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
|
||||
tm l{};
|
||||
#ifdef _WIN32
|
||||
localtime_s(&l, &t);
|
||||
#else
|
||||
localtime_r(&t, &l);
|
||||
#endif
|
||||
char b[64]; strftime(b, sizeof b, fmt, &l); return b;
|
||||
}
|
||||
|
||||
static std::vector<uint8_t> read_local(const fs::path &p) {
|
||||
std::ifstream f(p, std::ios::binary);
|
||||
return std::vector<uint8_t>((std::istreambuf_iterator<char>(f)), {});
|
||||
}
|
||||
static void write_local(const fs::path &p, const std::vector<uint8_t> &d) {
|
||||
std::ofstream f(p, std::ios::binary); f.write((const char *)d.data(), (std::streamsize)d.size());
|
||||
if (!f) throw ps5::Error("Couldn't save " + p.u8string());
|
||||
}
|
||||
|
||||
static std::string make_backup(const std::vector<uint8_t> &db, const std::string &label) {
|
||||
std::string id = now_stamp("%Y-%m-%d_%H%M%S");
|
||||
fs::path dir = data_path("backups") / id;
|
||||
for (int n = 2; fs::exists(dir); n++) dir = data_path("backups") / (id + "_" + std::to_string(n));
|
||||
fs::create_directories(dir);
|
||||
write_local(dir / "app.db", db);
|
||||
json m = {{"id", dir.filename().u8string()}, {"label", label}, {"ps5", g_ip}, {"created", now_stamp("%Y-%m-%d %H:%M:%S")}};
|
||||
std::ofstream(dir / "backup.json") << m.dump(2);
|
||||
return dir.filename().u8string();
|
||||
}
|
||||
|
||||
static json layout_state(const std::vector<uint8_t> &db_bytes, std::vector<std::string> extra_warn = {}) {
|
||||
layout::DB db(db_bytes);
|
||||
auto info = layout::analyze(db, g_layout_user);
|
||||
json j = info.to_json();
|
||||
for (auto &w : extra_warn) j["warnings"].push_back(w);
|
||||
j["ok"] = true;
|
||||
return j;
|
||||
}
|
||||
|
||||
static std::vector<uint8_t> pull_db(std::vector<std::string> *warn = nullptr) {
|
||||
auto c = client();
|
||||
if (warn)
|
||||
for (auto &e : list_dir(c, layout::DB_DIR)) {
|
||||
std::string n = e.value("name", "");
|
||||
if ((n == "app.db-wal" || n == "app.db-journal") && e.value("size", 0) > 0)
|
||||
warn->push_back("The console has unsaved home-screen changes (" + n + "). For the most accurate result, restart the PS5 and reconnect.");
|
||||
}
|
||||
auto b = c.read_file(layout::DB_PATH);
|
||||
if (b.empty()) throw ps5::Error("The PS5 sent an empty home-screen database.");
|
||||
return b;
|
||||
}
|
||||
|
||||
// Puts a new database in place: upload to /data/psgfx, copy over app.db with PS5 Upload's
|
||||
// shell `cp` (which keeps the file, so the system's open handle sees the new contents), then
|
||||
// read it back to be sure.
|
||||
static void push_db(const std::vector<uint8_t> &db) {
|
||||
auto c = client();
|
||||
const std::string tmp = "/data/psgfx/app.db.upload";
|
||||
try { c.call(ps5::FS_MKDIR, json{{"path", "/data/psgfx"}}.dump()); } catch (...) {}
|
||||
c.upload(tmp, db);
|
||||
json r = c.shell("cp " + tmp + " " + layout::DB_PATH);
|
||||
if (r.value("exit_code", -1) != 0)
|
||||
throw ps5::Error("The PS5 didn't accept the new home-screen database: " +
|
||||
(r.contains("stdout") ? r.value("stdout", "") : r.dump()) + " Nothing was changed.");
|
||||
try { c.remove(tmp); } catch (...) {}
|
||||
if (c.read_file(layout::DB_PATH) != db)
|
||||
throw ps5::Error("The home-screen database on the PS5 doesn't match what PSGFX sent. Restore a backup from the Backups list.");
|
||||
}
|
||||
|
||||
static json layout_load(const std::string &user) {
|
||||
std::lock_guard<std::mutex> l(g_layout_mu);
|
||||
g_layout_user = user;
|
||||
{ std::lock_guard<std::mutex> c(g_mu); g_tile_img_cache.clear(); }
|
||||
std::vector<std::string> warn;
|
||||
auto db = pull_db(&warn);
|
||||
fs::path marker = data_path("backups") / (".original-" + g_ip);
|
||||
if (!fs::exists(marker)) { make_backup(db, "Original - first time PSGFX read this console"); std::ofstream(marker) << "1"; }
|
||||
return layout_state(db, warn);
|
||||
}
|
||||
|
||||
static std::vector<uint8_t> tile_image(const std::string &path) {
|
||||
if (path.empty() || path[0] != '/' || path.find("..") != std::string::npos) return {};
|
||||
std::string ext = lower(path.substr(path.find_last_of('.') + 1));
|
||||
if (ext != "png" && ext != "dds" && ext != "jpg") return {};
|
||||
{
|
||||
std::lock_guard<std::mutex> l(g_mu);
|
||||
auto it = g_tile_img_cache.find(path);
|
||||
if (it != g_tile_img_cache.end()) return it->second;
|
||||
}
|
||||
std::vector<uint8_t> out;
|
||||
try {
|
||||
auto b = client().read_file(path);
|
||||
img::Image im;
|
||||
if (ext == "dds") { if (img::from_bc7_dds(b, im)) out = img::to_png(img::resize(im, 960, 540)); }
|
||||
else out = std::move(b);
|
||||
} catch (...) {}
|
||||
std::lock_guard<std::mutex> l(g_mu);
|
||||
g_tile_img_cache[path] = out;
|
||||
return out;
|
||||
}
|
||||
|
||||
static json layout_apply(const json &req) {
|
||||
std::lock_guard<std::mutex> l(g_layout_mu);
|
||||
auto orig = pull_db();
|
||||
std::string backup = make_backup(orig, "Before changes");
|
||||
std::vector<std::string> log = {"Backup saved: " + backup};
|
||||
layout::DB db(orig);
|
||||
auto info = layout::analyze(db, g_layout_user);
|
||||
layout::apply(db, info, req, log);
|
||||
auto out = db.serialize();
|
||||
push_db(out);
|
||||
log.push_back("Uploaded. Restart the PS5 to see the new home screen.");
|
||||
return {{"ok", true}, {"log", log}, {"backup", backup}, {"layout", layout_state(out)}};
|
||||
}
|
||||
|
||||
static json layout_backups() {
|
||||
json out = json::array();
|
||||
std::vector<fs::path> dirs;
|
||||
for (auto &e : fs::directory_iterator(data_path("backups"))) if (e.is_directory()) dirs.push_back(e.path());
|
||||
std::sort(dirs.rbegin(), dirs.rend());
|
||||
for (auto &d : dirs) {
|
||||
try { std::ifstream f(d / "backup.json"); json m; f >> m; out.push_back(m); } catch (...) {}
|
||||
}
|
||||
return {{"ok", true}, {"backups", out}};
|
||||
}
|
||||
|
||||
static json layout_restore(const std::string &id) {
|
||||
std::lock_guard<std::mutex> l(g_layout_mu);
|
||||
if (id.empty() || id.find_first_of("/\\") != std::string::npos || id.find("..") != std::string::npos) throw ps5::Error("Unknown backup.");
|
||||
auto db = read_local(data_path("backups") / fs::u8path(id) / "app.db");
|
||||
if (db.empty()) throw ps5::Error("That backup is missing its database file.");
|
||||
{ layout::DB check(db); } // throws if it isn't a healthy database
|
||||
push_db(db);
|
||||
return {{"ok", true}, {"layout", layout_state(db)}};
|
||||
}
|
||||
|
||||
static std::string preset_file(std::string name) {
|
||||
std::string o;
|
||||
for (char c : name) o += (isalnum((unsigned char)c) || c == ' ' || c == '-' || c == '_') ? c : '_';
|
||||
while (!o.empty() && o.back() == ' ') o.pop_back();
|
||||
if (o.empty()) throw ps5::Error("Give the preset a name.");
|
||||
return o;
|
||||
}
|
||||
static json layout_presets() {
|
||||
json names = json::array();
|
||||
for (auto &e : fs::directory_iterator(data_path("presets")))
|
||||
if (e.path().extension() == ".json") names.push_back(e.path().stem().u8string());
|
||||
return {{"ok", true}, {"presets", names}};
|
||||
}
|
||||
|
||||
// ─────────────────────────────── actions ──────────────────────────────
|
||||
// Homebrew registered by PS5 Upload (we know its folder) + installed games (edited in
|
||||
// /user/appmeta/<id>, where the home screen reads its art). System apps and nameless
|
||||
// leftovers are marked hidden so the list stays clean.
|
||||
// Homebrew registered by PS5 Upload (we know its folder) + installed games (in Sony's app
|
||||
// list or with a /user/appmeta/<id> folder). System apps and nameless leftovers are
|
||||
// marked hidden so the list stays clean.
|
||||
static json list_apps() {
|
||||
auto c = client();
|
||||
std::map<std::string, std::string> src, name;
|
||||
json reg = json::parse(c.call_str(ps5::APP_LIST_REGISTERED, "", ps5::APP_LIST_REGISTERED_ACK));
|
||||
std::set<std::string> mounted;
|
||||
json reg = json::parse(c.call_str(ps5::APP_LIST, "{}", 120000)); // 10-75 s on firmware 13.60
|
||||
for (auto &a : reg.value("apps", json::array())) {
|
||||
std::string id = a.value("title_id", "");
|
||||
src[id] = a.value("src", "");
|
||||
if (a.value("image_backed", false) || mounted_image(src[id])) mounted.insert(id);
|
||||
std::string n = a.value("title_name", "");
|
||||
if (n != id) name[id] = n;
|
||||
}
|
||||
bool have_db = false;
|
||||
std::set<std::string> in_db;
|
||||
try { // Sony's app list with real names (newer PS5 Upload payloads)
|
||||
json db = json::parse(c.call_str(ps5::APPDB_QUERY, "{}", ps5::APPDB_QUERY_ACK));
|
||||
json db = json::parse(c.call_str(ps5::APP_DB_QUERY, "{}", 120000));
|
||||
for (auto &a : db.value("apps", json::array())) {
|
||||
std::string id = a.value("title_id", ""), n = a.value("name", "");
|
||||
if (id.empty()) continue;
|
||||
have_db = true;
|
||||
in_db.insert(id);
|
||||
if (!src.count(id)) src[id] = "";
|
||||
if (!n.empty() && !name.count(id)) name[id] = n;
|
||||
}
|
||||
@@ -142,8 +344,8 @@ static json list_apps() {
|
||||
|
||||
json out = json::array();
|
||||
for (auto &[id, s] : src) {
|
||||
std::string kind = !s.empty() ? "homebrew"
|
||||
: (metas.count(id) && id.rfind("NPXS", 0) != 0) ? "game" : "other";
|
||||
std::string kind = mounted.count(id) ? "game" : !s.empty() ? "homebrew"
|
||||
: ((metas.count(id) || in_db.count(id)) && id.rfind("NPXS", 0) != 0) ? "game" : "other";
|
||||
std::string n = name.count(id) ? name[id] : "";
|
||||
if (n.empty() && kind != "other" && !have_db) n = meta_title(c, id);
|
||||
bool hidden = kind == "other" || (kind == "game" && n.empty());
|
||||
@@ -190,7 +392,52 @@ static std::vector<uint8_t> fetch_background(const std::string &id, const std::s
|
||||
return {};
|
||||
}
|
||||
|
||||
static std::string secs(double v) { char b[32]; snprintf(b, sizeof b, "%d:%02d", (int)v / 60, (int)v % 60); return b; }
|
||||
|
||||
// Cuts, levels and encodes the clip; the result is what Apply uploads, so size problems show up now.
|
||||
static void encode_music(Staged &s) {
|
||||
s.enc = at9::make_snd0(s.audio, s.opt);
|
||||
s.preview_wav = at9::wav_bytes(s.enc.processed);
|
||||
double total = (double)s.audio.pcm.size() / std::max(1, s.audio.channels) / std::max(1, s.audio.rate);
|
||||
s.note = "";
|
||||
if (s.opt.start_sec + 0.5 >= total) s.note = "The start is past the end of the song.";
|
||||
}
|
||||
static json music_json(const Staged &s) {
|
||||
double total = (double)s.audio.pcm.size() / std::max(1, s.audio.channels) / std::max(1, s.audio.rate);
|
||||
return {{"ok", true}, {"note", s.note}, {"seconds", s.enc.seconds}, {"total", total}, {"kb", (int)(s.enc.at9.size() / 1024)},
|
||||
{"start", s.opt.start_sec}, {"duration", s.opt.duration_sec},
|
||||
{"summary", secs(s.opt.start_sec) + " to " + secs(s.opt.start_sec + s.enc.seconds) + ", " + std::to_string(s.enc.at9.size() / 1024) + " KB"}};
|
||||
}
|
||||
static json stage_music(const std::vector<uint8_t> &bytes) {
|
||||
Staged s;
|
||||
std::string err;
|
||||
if (!at9::decode_file(bytes, s.audio, err)) throw ps5::Error("That file isn't an MP3, WAV or FLAC PSGFX can read" + (err.empty() ? std::string(".") : " (" + err + ")."));
|
||||
encode_music(s);
|
||||
json j = music_json(s);
|
||||
std::lock_guard<std::mutex> l(g_mu);
|
||||
g_staged["music"] = std::move(s);
|
||||
return j;
|
||||
}
|
||||
// Start (seconds) and length (seconds; 0 = the longest that fits in the PS5's 2 MB limit).
|
||||
static json music_clip(const json &req) {
|
||||
Staged s;
|
||||
{
|
||||
std::lock_guard<std::mutex> l(g_mu);
|
||||
auto it = g_staged.find("music");
|
||||
if (it == g_staged.end()) throw ps5::Error("Add a song first.");
|
||||
s = it->second;
|
||||
}
|
||||
s.opt.start_sec = std::max(0.0, req.value("start", s.opt.start_sec));
|
||||
s.opt.duration_sec = std::max(0.0, req.value("duration", s.opt.duration_sec));
|
||||
encode_music(s);
|
||||
json j = music_json(s);
|
||||
std::lock_guard<std::mutex> l(g_mu);
|
||||
g_staged["music"] = std::move(s);
|
||||
return j;
|
||||
}
|
||||
|
||||
static json stage(const std::string &kind, const std::vector<uint8_t> &bytes) {
|
||||
if (kind == "music") return stage_music(bytes);
|
||||
Staged s;
|
||||
if (!img::decode(bytes, s.src)) throw ps5::Error("That file isn't a PNG or JPEG image.");
|
||||
const img::Image &src = s.src;
|
||||
@@ -213,8 +460,9 @@ static json stage(const std::string &kind, const std::vector<uint8_t> &bytes) {
|
||||
// A file on the PS5 we're going to replace, and the format it has to stay in.
|
||||
struct Target { std::string name; bool dds = false; int w = 0, h = 0; };
|
||||
|
||||
static std::vector<uint8_t> encode_for(const std::string &kind, const img::Image &src, const Target &t) {
|
||||
img::Image im = img::cover(src, t.w, t.h);
|
||||
static std::vector<uint8_t> encode_for(const std::string &kind, const Staged &s, const Target &t) {
|
||||
if (kind == "music") return s.enc.at9;
|
||||
img::Image im = img::cover(s.src, t.w, t.h);
|
||||
img::opaque(im);
|
||||
return t.dds ? img::to_bc7_dds(im) : img::to_png(im);
|
||||
}
|
||||
@@ -223,6 +471,7 @@ static std::vector<uint8_t> encode_for(const std::string &kind, const img::Image
|
||||
static std::vector<Target> homebrew_targets(const std::string &kind) {
|
||||
if (kind == "icon") return {{"icon0.png", false, 512, 512}};
|
||||
if (kind == "background") return {{"pic0.dds", true, 3840, 2160}, {"pic1.dds", true, 3840, 2160}};
|
||||
if (kind == "music") return {{"snd0.at9"}};
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -231,9 +480,11 @@ 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);
|
||||
if (e.value("kind", "") != "file") continue;
|
||||
std::string ek = e.value("kind", "");
|
||||
if (ek != "file") { if (ek == "link") seen.push_back(name + " (link)"); continue; }
|
||||
seen.push_back(name);
|
||||
bool png = ends_with(ln, ".png"), dds = ends_with(ln, ".dds");
|
||||
if (!png && !dds) continue;
|
||||
@@ -241,7 +492,7 @@ static std::vector<Target> game_targets(ps5::Client &c, const std::string &id, c
|
||||
: (ln.rfind("pic0", 0) == 0 || ln.rfind("pic1", 0) == 0);
|
||||
if (!want) continue;
|
||||
std::vector<uint8_t> h;
|
||||
try { h = c.call(ps5::FS_READ, json{{"path", appmeta(id) + "/" + name}, {"offset", 0}, {"limit", 160}}.dump(), ps5::FS_READ_ACK); }
|
||||
try { h = c.read(appmeta(id) + "/" + name, 0, 160); }
|
||||
catch (...) { continue; }
|
||||
Target t; t.name = name; t.dds = dds;
|
||||
if (png && h.size() >= 24 && memcmp(h.data(), "\x89PNG", 4) == 0) {
|
||||
@@ -266,8 +517,8 @@ static std::vector<Target> game_targets(ps5::Client &c, const std::string &id, c
|
||||
// Keep the first original as <name>.bak; mark files we create with <name>.added.
|
||||
static void backup_once(ps5::Client &c, const std::string &dir, const std::string &name, json &log) {
|
||||
if (exists(c, dir, name + ".bak") || exists(c, dir, name + ".added")) return;
|
||||
if (exists(c, dir, name)) { copy_file(c, dir + "/" + name, dir + "/" + name + ".bak", false); log.push_back("Backed up " + name); }
|
||||
else c.call(ps5::FS_WRITE_BYTES, json{{"path", dir + "/" + name + ".added"}, {"bytes", "MQ=="}}.dump(), ps5::FS_WRITE_BYTES_ACK);
|
||||
if (exists(c, dir, name)) { copy_file(c, dir + "/" + name, dir + "/" + name + ".bak"); log.push_back("Backed up " + name); }
|
||||
else c.upload(dir + "/" + name + ".added", {'1'});
|
||||
}
|
||||
|
||||
// Homebrew: copy the app's sce_sys art to where the home screen reads it, then ask PS5 Upload
|
||||
@@ -284,12 +535,12 @@ static void sync_home(ps5::Client &c, const std::string &id, const std::string &
|
||||
std::vector<std::string> dests = {appmeta(id) + "/" + name, "/user/app/" + id + "/sce_sys/" + name};
|
||||
if (name == "icon0.png") dests.push_back("/user/app/" + id + "/icon0.png");
|
||||
for (auto &d : dests) {
|
||||
try { copy_file(c, dir + "/" + name, d, true); }
|
||||
try { copy_file(c, dir + "/" + name, d); }
|
||||
catch (const std::exception &e) { log.push_back("Couldn't update " + d + ": " + e.what()); }
|
||||
}
|
||||
}
|
||||
try {
|
||||
c.call_str(ps5::APP_REGISTER, json{{"src_path", src}}.dump(), ps5::APP_REGISTER_ACK, 60000);
|
||||
c.call_str(ps5::APP_REGISTER, json{{"src_path", src}}.dump(), 60000);
|
||||
log.push_back("Refreshed the home screen. If the old art still shows, restart the PS5.");
|
||||
} catch (const std::exception &e) {
|
||||
std::string m = e.what();
|
||||
@@ -300,33 +551,239 @@ static void sync_home(ps5::Client &c, const std::string &id, const std::string &
|
||||
}
|
||||
}
|
||||
|
||||
static json do_apply(const std::string &id, const std::string &src, const std::string &kind_of_app) {
|
||||
// ── Installed games: the art the home screen actually draws ──
|
||||
// The home screen draws each tile from the paths in its app.db concept row (icon0Info,
|
||||
// pic0Info). For many installed games those point into the game's own read-only package,
|
||||
// not /user/appmeta, so replacing files in the game's art folder can't change what's shown.
|
||||
// For those, PSGFX writes the new image to /user/appmeta/<id>/psgfx_<name>_<time> and points
|
||||
// the database at it. The original paths are kept in psgfx_original.json in that folder for
|
||||
// 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) {
|
||||
if (h.size() >= 24 && memcmp(h.data(), "\x89PNG", 4) == 0) {
|
||||
t.dds = false;
|
||||
t.w = (int)(h[16] << 24 | h[17] << 16 | h[18] << 8 | h[19]);
|
||||
t.h = (int)(h[20] << 24 | h[21] << 16 | h[22] << 8 | h[23]);
|
||||
} else if (h.size() >= 20 && memcmp(h.data(), "DDS ", 4) == 0) {
|
||||
t.dds = true; t.h = (int)ps5::get32(&h[12]); t.w = (int)ps5::get32(&h[16]);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return t.w >= 16 && t.h >= 16 && t.w <= 8192 && t.h <= 8192 && (!t.dds || (t.w % 4 == 0 && t.h % 4 == 0));
|
||||
}
|
||||
|
||||
static std::vector<uint8_t> read_head(ps5::Client &c, const std::string &path) {
|
||||
try { return c.read(path, 0, 160); }
|
||||
catch (...) { return {}; }
|
||||
}
|
||||
|
||||
// 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=?", {v, concept});
|
||||
else if (cols.count("titleId"))
|
||||
db.exec("UPDATE " + layout::q(table) + " SET " + layout::q(col) + "=? WHERE titleId=?", {v, id});
|
||||
}
|
||||
}
|
||||
|
||||
static std::string concept_of(layout::DB &db, const layout::Info &info, const std::string &id) {
|
||||
return db.scalar_str("SELECT localConceptId FROM " + layout::q(info.icon_t) + " WHERE titleId=?", {id});
|
||||
}
|
||||
|
||||
static void upload_db(const std::vector<uint8_t> &orig, layout::DB &db, const std::string &label, json &log) {
|
||||
std::string backup = make_backup(orig, label);
|
||||
auto out = db.serialize();
|
||||
{ layout::DB check(out); } // throws if the edit broke it; nothing is uploaded then
|
||||
push_db(out);
|
||||
{ std::lock_guard<std::mutex> l(g_mu); g_tile_img_cache.clear(); }
|
||||
log.push_back("Home-screen database updated (backup " + backup + ")");
|
||||
}
|
||||
|
||||
static json read_originals(ps5::Client &c, const std::string &id) {
|
||||
if (!exists(c, appmeta(id), ORIGINALS)) return json::object();
|
||||
try { auto b = c.read_file(appmeta(id) + "/" + ORIGINALS, 1u << 20); return json::parse(b.begin(), b.end()); }
|
||||
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;
|
||||
std::lock_guard<std::mutex> l(g_layout_mu);
|
||||
std::vector<uint8_t> orig;
|
||||
try { orig = pull_db(); }
|
||||
catch (const std::exception &e) {
|
||||
log.push_back(std::string("Couldn't read the home-screen database (") + e.what() + "), so only the game's art folder was checked.");
|
||||
return done;
|
||||
}
|
||||
layout::DB db(orig);
|
||||
auto info = layout::analyze(db, g_layout_user);
|
||||
if (info.concept_t.empty()) return done;
|
||||
std::string concept = concept_of(db, info, id);
|
||||
if (concept.empty()) return done;
|
||||
|
||||
const std::string dir = appmeta(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 = 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);
|
||||
// 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
|
||||
bool regular = false;
|
||||
for (auto &e : list_dir(c, dir)) if (e.value("name", "") == base && e.value("kind", "") == "file") regular = true;
|
||||
if (regular) continue;
|
||||
}
|
||||
Target t;
|
||||
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) + ")");
|
||||
}
|
||||
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 ? ts_query() : value.substr(qp)));
|
||||
done.insert(kind);
|
||||
}
|
||||
if (done.empty()) return done;
|
||||
std::string o = originals.dump(2);
|
||||
c.upload(dir + "/" + ORIGINALS, std::vector<uint8_t>(o.begin(), o.end()));
|
||||
upload_db(orig, db, "Before new art for " + id, log);
|
||||
for (auto &p : replaced) try { c.remove(p); } catch (...) {}
|
||||
return done;
|
||||
}
|
||||
|
||||
// Points the database back at the game's own art. False if PSGFX never repointed it.
|
||||
static bool game_restore_db(ps5::Client &c, const std::string &id, json &log) {
|
||||
json originals = read_originals(c, id);
|
||||
if (originals.empty()) return false;
|
||||
{
|
||||
std::lock_guard<std::mutex> l(g_layout_mu);
|
||||
auto orig = pull_db();
|
||||
layout::DB db(orig);
|
||||
auto info = layout::analyze(db, g_layout_user);
|
||||
std::string concept = concept_of(db, info, id);
|
||||
for (auto &[col, value] : originals.items())
|
||||
if (value.is_string()) set_art_column(db, info, id, concept, col, value.get<std::string>());
|
||||
upload_db(orig, db, "Before restoring art for " + id, log);
|
||||
}
|
||||
for (auto &e : list_dir(c, appmeta(id))) {
|
||||
std::string n = e.value("name", "");
|
||||
if (n.rfind("psgfx_", 0) == 0) try { c.remove(appmeta(id) + "/" + n); } catch (...) {}
|
||||
}
|
||||
log.push_back("Pointed the home screen back at the game's own art");
|
||||
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 ¶m_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") {
|
||||
int written = 0;
|
||||
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++;
|
||||
}
|
||||
}
|
||||
if (!written) {
|
||||
std::string list; std::sort(seen.begin(), seen.end()); seen.erase(std::unique(seen.begin(), seen.end()), seen.end());
|
||||
for (auto &n : seen) list += (list.empty() ? "" : ", ") + n;
|
||||
throw ps5::Error("Nothing was changed. Files in this game's art folder: " + (list.empty() ? std::string("(none)") : list));
|
||||
std::string notes;
|
||||
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";
|
||||
@@ -335,50 +792,112 @@ static json do_apply(const std::string &id, const std::string &src, const std::s
|
||||
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}};
|
||||
}
|
||||
|
||||
static json do_restore(const std::string &id, const std::string &src, const std::string &kind_of_app) {
|
||||
static json do_restore(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();
|
||||
auto c = client();
|
||||
const std::string dir = kind_of_app == "game" ? appmeta(id) : src + "/sce_sys";
|
||||
if (kind_of_app != "game" && src.empty()) throw ps5::Error("This app's folder is unknown.");
|
||||
bool repointed = kind_of_app == "game" && game_restore_db(c, id, log);
|
||||
std::vector<std::string> names;
|
||||
for (auto &e : list_dir(c, dir)) {
|
||||
std::string n = e.value("name", "");
|
||||
if (ends_with(n, ".bak")) names.push_back(n.substr(0, n.size() - 4));
|
||||
else if (ends_with(n, ".added")) names.push_back(n.substr(0, n.size() - 6));
|
||||
}
|
||||
if (names.empty()) throw ps5::Error("Nothing to restore - this still has its original art.");
|
||||
if (names.empty() && !repointed) throw ps5::Error("Nothing to restore - this still has its original art.");
|
||||
for (auto &name : names) {
|
||||
const std::string path = dir + "/" + name;
|
||||
if (exists(c, dir, name + ".bak")) {
|
||||
copy_file(c, path + ".bak", path, true);
|
||||
c.call(ps5::FS_DELETE, json{{"path", path + ".bak"}}.dump(), ps5::FS_DELETE_ACK);
|
||||
copy_file(c, path + ".bak", path);
|
||||
c.remove(path + ".bak");
|
||||
log.push_back("Restored " + name);
|
||||
} else {
|
||||
try { c.call(ps5::FS_DELETE, json{{"path", path}}.dump(), ps5::FS_DELETE_ACK); } catch (...) {}
|
||||
c.call(ps5::FS_DELETE, json{{"path", path + ".added"}}.dump(), ps5::FS_DELETE_ACK);
|
||||
try { c.remove(path); } catch (...) {}
|
||||
c.remove(path + ".added");
|
||||
if (kind_of_app != "game") // registering copied it here too, and never deletes
|
||||
for (const std::string © : {appmeta(id) + "/" + name, "/user/app/" + id + "/sce_sys/" + name})
|
||||
try { c.call(ps5::FS_DELETE, json{{"path", copy}}.dump(), ps5::FS_DELETE_ACK); } catch (...) {}
|
||||
try { c.remove(copy); } catch (...) {}
|
||||
log.push_back("Removed " + name + " (it wasn't there originally)");
|
||||
}
|
||||
}
|
||||
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}};
|
||||
}
|
||||
|
||||
// Homebrew keeps its name in sce_sys/param.json, and re-registering (which Apply does) copies
|
||||
// it to the home screen. Update it there too, so changing art later doesn't undo a rename.
|
||||
// The first original is kept as param.json.orig (not .bak, so Restore original art leaves it).
|
||||
static void rename_homebrew_param(ps5::Client &c, const std::string &id, const std::string &src, const std::string &name, json &log) {
|
||||
const std::string dir = src + "/sce_sys";
|
||||
try {
|
||||
auto b = c.read_file(dir + "/param.json", 1u << 20);
|
||||
auto j = nlohmann::ordered_json::parse(b.begin(), b.end());
|
||||
int n = 0;
|
||||
if (j.contains("localizedParameters") && j["localizedParameters"].is_object())
|
||||
for (auto &[lang, v] : j["localizedParameters"].items())
|
||||
if (v.is_object() && v.contains("titleName")) { v["titleName"] = name; n++; }
|
||||
if (!n) { log.push_back("This app's param.json has no name to update; only the home screen was renamed."); return; }
|
||||
if (!exists(c, dir, "param.json.orig")) copy_file(c, dir + "/param.json", dir + "/param.json.orig");
|
||||
std::string out = j.dump(2);
|
||||
c.upload(dir + "/param.json", std::vector<uint8_t>(out.begin(), out.end()));
|
||||
for (auto &d : {appmeta(id) + "/param.json", "/user/app/" + id + "/sce_sys/param.json"})
|
||||
try { if (exists(c, d.substr(0, d.find_last_of('/')), "param.json")) copy_file(c, dir + "/param.json", d); } catch (...) {}
|
||||
log.push_back("Updated the name in the app's param.json");
|
||||
} catch (const std::exception &e) {
|
||||
log.push_back(std::string("Couldn't update the app's param.json (") + e.what() + "). Changing its art later may bring back the old name.");
|
||||
}
|
||||
}
|
||||
|
||||
// Renames a title on the home screen with the same database edit Home layout uses.
|
||||
static json do_rename(const std::string &id, const std::string &src, const std::string &kind_of_app, std::string name) {
|
||||
while (!name.empty() && isspace((unsigned char)name.back())) name.pop_back();
|
||||
while (!name.empty() && isspace((unsigned char)name.front())) name.erase(0, 1);
|
||||
if (name.empty()) throw ps5::Error("Enter a name.");
|
||||
json log = json::array();
|
||||
auto c = client();
|
||||
{
|
||||
std::lock_guard<std::mutex> l(g_layout_mu);
|
||||
auto orig = pull_db();
|
||||
layout::DB db(orig);
|
||||
auto info = layout::analyze(db, g_layout_user);
|
||||
const layout::Tile *t = info.find(id);
|
||||
if (!t) throw ps5::Error("This title isn't in the home screen's list, so it can't be renamed there.");
|
||||
std::vector<std::string> lines;
|
||||
layout::apply(db, info, json{{"edits", {{id, {{"name", name}}}}}}, lines);
|
||||
for (auto &x : lines) log.push_back(x);
|
||||
upload_db(orig, db, "Before renaming " + t->name, log);
|
||||
}
|
||||
if (kind_of_app == "homebrew" && !src.empty() && !mounted_image(src)) rename_homebrew_param(c, id, src, name, log);
|
||||
log.push_back("Done. Restart the PS5 to see the new name.");
|
||||
return {{"ok", true}, {"log", log}, {"name", name}};
|
||||
}
|
||||
|
||||
// ─────────────────────────────── tiny HTTP server ─────────────────────
|
||||
struct Req { std::string method, path, query; std::map<std::string, std::string> q; std::vector<uint8_t> body; };
|
||||
|
||||
@@ -481,6 +1000,25 @@ static void handle(sock_t s, Req &r) {
|
||||
}
|
||||
if (r.path.rfind("/api/stage/", 0) == 0 && r.method == "POST") { respond_json(s, stage(r.path.substr(11), r.body)); return; }
|
||||
if (r.path.rfind("/api/unstage/", 0) == 0) { std::lock_guard<std::mutex> l(g_mu); g_staged.erase(r.path.substr(13)); respond_json(s, {{"ok", true}}); return; }
|
||||
if (r.path.rfind("/api/presets/", 0) == 0) { // /api/presets/<title id> -> the built-in icons for it
|
||||
std::string id = r.path.substr(13);
|
||||
json list = json::array();
|
||||
for (size_t i = 0; i < PRESETS_COUNT; i++) if (id == PRESETS[i].title_id) list.push_back({{"i", i}, {"app", PRESETS[i].app}});
|
||||
respond_json(s, {{"ok", true}, {"presets", list}}); return;
|
||||
}
|
||||
if (r.path.rfind("/api/preset/", 0) == 0) { // /api/preset/<index>: the image; POST stages it as the icon
|
||||
size_t i = (size_t)strtoull(r.path.c_str() + 12, nullptr, 10);
|
||||
if (i >= PRESETS_COUNT) { respond(s, 404, "text/plain", "none", 4); return; }
|
||||
if (r.method == "POST") { respond_json(s, stage("icon", std::vector<uint8_t>(PRESETS[i].data, PRESETS[i].data + PRESETS[i].len))); return; }
|
||||
respond(s, 200, "image/png", PRESETS[i].data, PRESETS[i].len); return;
|
||||
}
|
||||
if (r.path == "/api/music/clip" && r.method == "POST") { respond_json(s, music_clip(json::parse(std::string(r.body.begin(), r.body.end())))); return; }
|
||||
if (r.path == "/api/staged/music") {
|
||||
std::vector<uint8_t> b;
|
||||
{ std::lock_guard<std::mutex> l(g_mu); auto it = g_staged.find("music"); if (it != g_staged.end()) b = it->second.preview_wav; }
|
||||
if (b.empty()) { respond(s, 404, "text/plain", "none", 4); return; }
|
||||
respond(s, 200, "audio/wav", b.data(), b.size()); return;
|
||||
}
|
||||
if (r.path.rfind("/api/staged/", 0) == 0) {
|
||||
std::vector<uint8_t> b;
|
||||
{ std::lock_guard<std::mutex> l(g_mu); auto it = g_staged.find(r.path.substr(12)); if (it != g_staged.end()) b = it->second.preview_png; }
|
||||
@@ -492,6 +1030,39 @@ static void handle(sock_t s, Req &r) {
|
||||
auto id = j.value("title_id", ""), src = j.value("src", ""), kind = j.value("kind", "homebrew");
|
||||
respond_json(s, r.path == "/api/apply" ? do_apply(id, src, kind) : do_restore(id, src, kind)); return;
|
||||
}
|
||||
if (r.path == "/api/rename" && r.method == "POST") {
|
||||
json j = json::parse(std::string(r.body.begin(), r.body.end()));
|
||||
respond_json(s, do_rename(j.value("title_id", ""), j.value("src", ""), j.value("kind", "homebrew"), j.value("name", ""))); return;
|
||||
}
|
||||
if (r.path == "/api/layout/load" && r.method == "POST") {
|
||||
json j = json::parse(std::string(r.body.begin(), r.body.end()));
|
||||
respond_json(s, layout_load(j.value("user", ""))); return;
|
||||
}
|
||||
if (r.path == "/api/layout/img") {
|
||||
auto b = tile_image(r.q["p"]);
|
||||
if (b.empty()) { respond(s, 404, "text/plain", "none", 4); return; }
|
||||
respond(s, 200, "image/png", b.data(), b.size()); return;
|
||||
}
|
||||
if (r.path == "/api/layout/apply" && r.method == "POST") { respond_json(s, layout_apply(json::parse(std::string(r.body.begin(), r.body.end())))); return; }
|
||||
if (r.path == "/api/layout/backups") { respond_json(s, layout_backups()); return; }
|
||||
if (r.path == "/api/layout/restore" && r.method == "POST") {
|
||||
json j = json::parse(std::string(r.body.begin(), r.body.end()));
|
||||
respond_json(s, layout_restore(j.value("id", ""))); return;
|
||||
}
|
||||
if (r.path == "/api/layout/presets") { respond_json(s, layout_presets()); return; }
|
||||
if (r.path == "/api/layout/preset/save" && r.method == "POST") {
|
||||
json j = json::parse(std::string(r.body.begin(), r.body.end()));
|
||||
std::string name = preset_file(j.value("name", ""));
|
||||
std::ofstream(data_path("presets") / fs::u8path(name + ".json")) << j.value("data", json::object()).dump(2);
|
||||
respond_json(s, {{"ok", true}, {"name", name}}); return;
|
||||
}
|
||||
if (r.path == "/api/layout/preset/load" && r.method == "POST") {
|
||||
json j = json::parse(std::string(r.body.begin(), r.body.end()));
|
||||
std::ifstream f(data_path("presets") / fs::u8path(preset_file(j.value("name", "")) + ".json"));
|
||||
if (!f) throw ps5::Error("Preset not found.");
|
||||
json d; f >> d;
|
||||
respond_json(s, {{"ok", true}, {"data", d}}); return;
|
||||
}
|
||||
respond(s, 404, "text/plain", "not found", 9);
|
||||
} catch (std::exception &e) {
|
||||
respond_json(s, {{"ok", false}, {"error", e.what()}}, 200);
|
||||
@@ -504,6 +1075,7 @@ int main(int argc, char **argv) {
|
||||
char exe[MAX_PATH]; GetModuleFileNameA(nullptr, exe, MAX_PATH);
|
||||
std::string ep = exe; std::string exedir = ep.substr(0, ep.find_last_of("\\/") + 1);
|
||||
g_config_path = exedir + "psgfx.json"; g_legacy_config_path = exedir + "ps5-art-studio.json";
|
||||
g_data_dir = exedir + "PSGFX Layout";
|
||||
// Close any other running copy (e.g. an older version still open in its console window),
|
||||
// so the browser can only ever talk to this one.
|
||||
{
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
// Preset icons built into PSGFX, by title ID (assets/presets, embedded by tools/embed_presets.py).
|
||||
#pragma once
|
||||
#include <cstddef>
|
||||
|
||||
struct Preset { const char *app; const char *title_id; const unsigned char *data; size_t len; };
|
||||
extern const Preset PRESETS[];
|
||||
extern const size_t PRESETS_COUNT;
|
||||
@@ -1,15 +1,17 @@
|
||||
// Minimal client for PS5 Upload's resident payload (FTX2 protocol).
|
||||
// port 9114: management (JSON request -> ACK)
|
||||
// port 9113: transfers (BeginTx -> StreamShard -> CommitTx)
|
||||
// Frame = 28-byte little-endian header + body.
|
||||
// Minimal client for the PS5, through the PS5 Upload app on this PC.
|
||||
//
|
||||
// PS5 Upload 6.0 replaced its old protocol (FTX2, ports 9113/9114) with AVA1: one encrypted
|
||||
// port (9120) that the console only opens to a paired app. Rather than pair a second app,
|
||||
// PSGFX hands its calls to PS5 Upload's local engine (http://127.0.0.1:19113), which already
|
||||
// holds the paired session: POST /api/mgmt/call runs one management call on the console, with
|
||||
// the same JSON bodies the old protocol used. So PS5 Upload has to be open on this PC.
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <random>
|
||||
#include "lib/blake3.h"
|
||||
#include "lib/json.hpp"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
@@ -32,180 +34,167 @@ typedef int sock_t;
|
||||
|
||||
namespace ps5 {
|
||||
|
||||
enum Frame : uint16_t {
|
||||
ERROR_ = 3,
|
||||
BEGIN_TX = 10, BEGIN_TX_ACK = 11, COMMIT_TX = 14, COMMIT_TX_ACK = 15,
|
||||
ABORT_TX = 16, ABORT_TX_ACK = 17,
|
||||
STREAM_SHARD = 30, SHARD_ACK = 31,
|
||||
FS_LIST_DIR = 36, FS_LIST_DIR_ACK = 37,
|
||||
FS_DELETE = 40, FS_DELETE_ACK = 41,
|
||||
FS_READ = 48, FS_READ_ACK = 49,
|
||||
FS_COPY = 50, FS_COPY_ACK = 51,
|
||||
APP_REGISTER = 56, APP_REGISTER_ACK = 57,
|
||||
APP_LIST_REGISTERED = 62, APP_LIST_REGISTERED_ACK = 63,
|
||||
APPDB_QUERY = 120, APPDB_QUERY_ACK = 121,
|
||||
FS_WRITE_BYTES = 130, FS_WRITE_BYTES_ACK = 131,
|
||||
};
|
||||
// AVA1 management methods (PS5 Upload's protocol/ava1 schema) and the labels its errors carry.
|
||||
struct Method { uint16_t id; const char *label; };
|
||||
constexpr Method FS_LIST{33, "FS_LIST_DIR"}, FS_MKDIR{35, "FS_MKDIR"}, FS_READ{38, "FS_READ"},
|
||||
FS_WRITE{39, "FS_WRITE_BYTES"}, APP_REGISTER{48, "APP_REGISTER"},
|
||||
APP_LIST{51, "APP_LIST_REGISTERED"}, APP_DB_QUERY{56, "APP_DB_QUERY"},
|
||||
SHELL_EXEC{87, "SHELL_EXEC"};
|
||||
constexpr uint8_t JOB_DELETE = 1;
|
||||
|
||||
struct Error : std::runtime_error { using std::runtime_error::runtime_error; };
|
||||
|
||||
inline void put16(uint8_t *p, uint16_t v) { p[0] = v & 255; p[1] = v >> 8; }
|
||||
inline void put32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); }
|
||||
inline void put64(uint8_t *p, uint64_t v) { for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); }
|
||||
inline uint64_t get64(const uint8_t *p) { uint64_t v = 0; for (int i = 7; i >= 0; i--) v = (v << 8) | p[i]; return v; }
|
||||
inline uint32_t get32(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; }
|
||||
|
||||
class Conn {
|
||||
public:
|
||||
Conn(const std::string &host, int port, int timeout_ms) {
|
||||
addrinfo hints{}, *res = nullptr;
|
||||
hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM;
|
||||
if (getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &res) != 0 || !res)
|
||||
throw Error("Can't resolve " + host);
|
||||
s_ = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
|
||||
if (s_ == SOCK_BAD) { freeaddrinfo(res); throw Error("socket() failed"); }
|
||||
set_timeout(timeout_ms);
|
||||
int one = 1; setsockopt(s_, IPPROTO_TCP, TCP_NODELAY, (const char *)&one, sizeof one);
|
||||
if (connect(s_, res->ai_addr, (int)res->ai_addrlen) != 0) {
|
||||
freeaddrinfo(res); sock_close(s_); s_ = SOCK_BAD;
|
||||
throw Error("Can't reach the PS5 at " + host + ":" + std::to_string(port) +
|
||||
" - is PS5 Upload's payload running?");
|
||||
}
|
||||
freeaddrinfo(res);
|
||||
inline std::string b64_encode(const uint8_t *d, size_t n) {
|
||||
static const char *T = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
std::string o; o.reserve((n + 2) / 3 * 4);
|
||||
for (size_t i = 0; i < n; i += 3) {
|
||||
uint32_t v = (uint32_t)d[i] << 16 | (i + 1 < n ? (uint32_t)d[i + 1] << 8 : 0) | (i + 2 < n ? d[i + 2] : 0);
|
||||
o += T[v >> 18 & 63]; o += T[v >> 12 & 63];
|
||||
o += i + 1 < n ? T[v >> 6 & 63] : '='; o += i + 2 < n ? T[v & 63] : '=';
|
||||
}
|
||||
~Conn() { if (s_ != SOCK_BAD) sock_close(s_); }
|
||||
Conn(const Conn &) = delete; Conn &operator=(const Conn &) = delete;
|
||||
return o;
|
||||
}
|
||||
inline std::string b64_encode(const std::string &s) { return b64_encode((const uint8_t *)s.data(), s.size()); }
|
||||
inline std::vector<uint8_t> b64_decode(const std::string &s) {
|
||||
std::vector<uint8_t> o; o.reserve(s.size() / 4 * 3);
|
||||
uint32_t v = 0; int bits = 0;
|
||||
for (char ch : s) {
|
||||
int x = ch >= 'A' && ch <= 'Z' ? ch - 'A' : ch >= 'a' && ch <= 'z' ? ch - 'a' + 26
|
||||
: ch >= '0' && ch <= '9' ? ch - '0' + 52 : ch == '+' ? 62 : ch == '/' ? 63 : -1;
|
||||
if (x < 0) continue;
|
||||
v = v << 6 | (uint32_t)x; bits += 6;
|
||||
if (bits >= 8) { bits -= 8; o.push_back((uint8_t)(v >> bits)); }
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
void set_timeout(int ms) {
|
||||
// One HTTP/1.1 request to the local engine (Connection: close). Returns (status, body).
|
||||
inline std::pair<int, std::string> http(const std::string &host, int port, const std::string &method,
|
||||
const std::string &path, const std::string &body, int timeout_ms) {
|
||||
addrinfo hints{}, *res = nullptr;
|
||||
hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM;
|
||||
if (getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &res) != 0 || !res)
|
||||
throw Error("Can't resolve " + host);
|
||||
sock_t s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
|
||||
if (s == SOCK_BAD) { freeaddrinfo(res); throw Error("socket() failed"); }
|
||||
#ifdef _WIN32
|
||||
DWORD t = (DWORD)ms;
|
||||
DWORD t = (DWORD)timeout_ms;
|
||||
#else
|
||||
timeval t{ms / 1000, (ms % 1000) * 1000};
|
||||
timeval t{timeout_ms / 1000, (timeout_ms % 1000) * 1000};
|
||||
#endif
|
||||
setsockopt(s_, SOL_SOCKET, SO_RCVTIMEO, (const char *)&t, sizeof t);
|
||||
setsockopt(s_, SOL_SOCKET, SO_SNDTIMEO, (const char *)&t, sizeof t);
|
||||
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&t, sizeof t);
|
||||
setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (const char *)&t, sizeof t);
|
||||
if (connect(s, res->ai_addr, (int)res->ai_addrlen) != 0) {
|
||||
freeaddrinfo(res); sock_close(s);
|
||||
throw Error("PSGFX talks to your PS5 through the PS5 Upload app, and it isn't running on this PC. "
|
||||
"Open PS5 Upload (version 6 or newer), make sure it's connected to your PS5, then click Connect again.");
|
||||
}
|
||||
|
||||
void send_frame(uint16_t type, const uint8_t *a, size_t alen, const uint8_t *b = nullptr, size_t blen = 0) {
|
||||
uint8_t h[28] = {0};
|
||||
put32(h, 0x32585446u); // "FTX2"
|
||||
put16(h + 4, 1); // version
|
||||
put16(h + 6, type);
|
||||
put32(h + 8, 0); // flags
|
||||
put64(h + 12, (uint64_t)(alen + blen));
|
||||
put64(h + 20, 0); // trace id 0 = untracked fast path
|
||||
send_all(h, 28);
|
||||
if (alen) send_all(a, alen);
|
||||
if (blen) send_all(b, blen);
|
||||
freeaddrinfo(res);
|
||||
std::string req = method + " " + path + " HTTP/1.1\r\nHost: " + host + ":" + std::to_string(port) +
|
||||
"\r\nContent-Type: application/json\r\nContent-Length: " + std::to_string(body.size()) +
|
||||
"\r\nConnection: close\r\n\r\n" + body;
|
||||
for (size_t off = 0; off < req.size();) {
|
||||
int w = ::send(s, req.data() + off, (int)std::min<size_t>(req.size() - off, 1 << 20), 0);
|
||||
if (w <= 0) { sock_close(s); throw Error("The connection to PS5 Upload dropped."); }
|
||||
off += (size_t)w;
|
||||
}
|
||||
|
||||
// Returns (frame_type, body). Throws on transport errors.
|
||||
std::pair<uint16_t, std::vector<uint8_t>> recv_frame() {
|
||||
uint8_t h[28];
|
||||
recv_all(h, 28);
|
||||
if (get32(h) != 0x32585446u) throw Error("Unexpected reply from the PS5 (not PS5 Upload's payload?)");
|
||||
uint16_t type = (uint16_t)(h[6] | h[7] << 8);
|
||||
uint64_t len = get64(h + 12);
|
||||
if (len > (256ull << 20)) throw Error("Reply too large");
|
||||
std::vector<uint8_t> body((size_t)len);
|
||||
if (len) recv_all(body.data(), (size_t)len);
|
||||
return {type, std::move(body)};
|
||||
std::string resp; char buf[1 << 16];
|
||||
for (;;) {
|
||||
int r = ::recv(s, buf, sizeof buf, 0);
|
||||
if (r == 0) break;
|
||||
if (r < 0) { sock_close(s); throw Error("PS5 Upload didn't answer in time."); }
|
||||
resp.append(buf, (size_t)r);
|
||||
}
|
||||
|
||||
private:
|
||||
sock_t s_ = SOCK_BAD;
|
||||
void send_all(const uint8_t *p, size_t n) {
|
||||
while (n) {
|
||||
int w = ::send(s_, (const char *)p, (int)std::min<size_t>(n, 1 << 20), 0);
|
||||
if (w <= 0) throw Error("Connection to the PS5 dropped while sending");
|
||||
p += w; n -= (size_t)w;
|
||||
sock_close(s);
|
||||
size_t he = resp.find("\r\n\r\n");
|
||||
if (resp.compare(0, 5, "HTTP/") != 0 || he == std::string::npos) throw Error("Unexpected reply from PS5 Upload.");
|
||||
int status = atoi(resp.c_str() + resp.find(' ') + 1);
|
||||
std::string head = resp.substr(0, he), out = resp.substr(he + 4);
|
||||
for (auto &ch : head) ch = (char)tolower((unsigned char)ch);
|
||||
if (head.find("transfer-encoding: chunked") != std::string::npos) {
|
||||
std::string d; size_t p = 0;
|
||||
for (;;) {
|
||||
size_t e = out.find("\r\n", p);
|
||||
if (e == std::string::npos) break;
|
||||
size_t n = strtoull(out.c_str() + p, nullptr, 16);
|
||||
if (n == 0 || e + 2 + n > out.size()) break;
|
||||
d.append(out, e + 2, n);
|
||||
p = e + 2 + n + 2;
|
||||
}
|
||||
out.swap(d);
|
||||
}
|
||||
void recv_all(uint8_t *p, size_t n) {
|
||||
while (n) {
|
||||
int r = ::recv(s_, (char *)p, (int)std::min<size_t>(n, 1 << 20), 0);
|
||||
if (r <= 0) throw Error("The PS5 didn't answer in time");
|
||||
p += r; n -= (size_t)r;
|
||||
}
|
||||
}
|
||||
};
|
||||
return {status, out};
|
||||
}
|
||||
|
||||
struct Client {
|
||||
std::string host;
|
||||
int mgmt_port = 9114, xfer_port = 9113;
|
||||
std::string host; // the PS5's IP
|
||||
std::string engine_host = "127.0.0.1"; int engine_port = 19113;
|
||||
|
||||
// One management round-trip. `expect` is the ACK frame type.
|
||||
std::vector<uint8_t> call(uint16_t type, const std::string &json, uint16_t expect, int timeout_ms = 15000) {
|
||||
Conn c(host, mgmt_port, timeout_ms);
|
||||
c.send_frame(type, (const uint8_t *)json.data(), json.size());
|
||||
auto [ft, body] = c.recv_frame();
|
||||
if (ft == ERROR_) throw Error(std::string(body.begin(), body.end()));
|
||||
if (ft != expect) throw Error("Unexpected reply type " + std::to_string(ft));
|
||||
return body;
|
||||
// One management call on the console. Throws ps5::Error with a readable message.
|
||||
std::vector<uint8_t> call(Method m, const std::string &body, int timeout_ms = 15000) {
|
||||
return proxy({{"op", "call"}, {"addr", host}, {"method", m.id}, {"label", m.label},
|
||||
{"body_b64", b64_encode(body)}, {"timeout_ms", timeout_ms}}, m.label, timeout_ms);
|
||||
}
|
||||
std::string call_str(uint16_t type, const std::string &json, uint16_t expect, int timeout_ms = 15000) {
|
||||
auto b = call(type, json, expect, timeout_ms);
|
||||
std::string call_str(Method m, const std::string &body, int timeout_ms = 15000) {
|
||||
auto b = call(m, body, timeout_ms);
|
||||
return std::string(b.begin(), b.end());
|
||||
}
|
||||
|
||||
// Whole file (<= 64 MiB) in one transaction with a single BLAKE3-verified shard.
|
||||
void upload(const std::string &dest, const std::vector<uint8_t> &data) {
|
||||
uint8_t tx[16];
|
||||
std::random_device rd; for (auto &b : tx) b = (uint8_t)rd();
|
||||
Conn c(host, xfer_port, 60000);
|
||||
|
||||
std::string manifest = "{\"dest_root\":\"" + json_escape(dest) + "\",\"file_count\":1,\"total_bytes\":" +
|
||||
std::to_string(data.size()) + ",\"total_shards\":1}";
|
||||
std::vector<uint8_t> begin(24);
|
||||
memcpy(begin.data(), tx, 16); put32(&begin[16], 1); put32(&begin[20], 0);
|
||||
begin.insert(begin.end(), manifest.begin(), manifest.end());
|
||||
c.send_frame(BEGIN_TX, begin.data(), begin.size());
|
||||
expect_ack(c, BEGIN_TX_ACK, "start upload");
|
||||
|
||||
uint8_t sh[64] = {0};
|
||||
memcpy(sh, tx, 16); put64(sh + 16, 1);
|
||||
blake3_hasher hs; blake3_hasher_init(&hs);
|
||||
if (!data.empty()) blake3_hasher_update(&hs, data.data(), data.size());
|
||||
blake3_hasher_finalize(&hs, sh + 24, 32);
|
||||
put32(sh + 56, 1); put32(sh + 60, 0);
|
||||
c.send_frame(STREAM_SHARD, sh, 64, data.data(), data.size());
|
||||
expect_ack(c, SHARD_ACK, "send data");
|
||||
|
||||
uint8_t commit[24] = {0};
|
||||
memcpy(commit, tx, 16);
|
||||
c.send_frame(COMMIT_TX, commit, 24);
|
||||
expect_ack(c, COMMIT_TX_ACK, "finish upload");
|
||||
void remove(const std::string &path) {
|
||||
std::string body = nlohmann::json{{"path", path}}.dump();
|
||||
proxy({{"op", "run_job"}, {"addr", host}, {"job_op", JOB_DELETE}, {"label", "FS_DELETE"},
|
||||
{"body_b64", b64_encode(body)}, {"op_id", 0}, {"subject", path}, {"deadline_ms", 30000}}, "FS_DELETE", 30000);
|
||||
}
|
||||
|
||||
// Read a whole file in <= 2 MiB pieces.
|
||||
// Whole file, up to 16 MiB (PS5 Upload sends it in pieces and commits it once).
|
||||
void upload(const std::string &dest, const std::vector<uint8_t> &data) {
|
||||
if (data.size() > (16u << 20)) throw Error("That file is too large to send (over 16 MB).");
|
||||
call(FS_WRITE, nlohmann::json{{"path", dest}, {"bytes", b64_encode(data.data(), data.size())},
|
||||
{"mode", "overwrite"}, {"large", true}}.dump(), 60000);
|
||||
}
|
||||
|
||||
// Up to `limit` bytes from `offset`. "unsafe" lets reads reach /system_data (app.db); the
|
||||
// payload still refuses anything outside its readable roots.
|
||||
std::vector<uint8_t> read(const std::string &path, uint64_t offset, uint64_t limit, int timeout_ms = 20000) {
|
||||
return call(FS_READ, nlohmann::json{{"path", path}, {"offset", offset}, {"limit", limit}, {"unsafe", true}}.dump(), timeout_ms);
|
||||
}
|
||||
std::vector<uint8_t> read_file(const std::string &path, size_t max_total = 64u << 20) {
|
||||
std::vector<uint8_t> out;
|
||||
const size_t piece = 2u << 20; // PS5 Upload caps one fs.read at 2 MiB
|
||||
for (;;) {
|
||||
auto part = call(FS_READ, "{\"path\":\"" + json_escape(path) + "\",\"offset\":" + std::to_string(out.size()) +
|
||||
",\"limit\":2097152}", FS_READ_ACK, 20000);
|
||||
if (part.empty()) break;
|
||||
auto part = read(path, out.size(), piece, 60000);
|
||||
out.insert(out.end(), part.begin(), part.end());
|
||||
if (part.size() < 2097152 || out.size() >= max_total) break;
|
||||
if (part.size() < piece || out.size() >= max_total) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static std::string json_escape(const std::string &s) {
|
||||
std::string o;
|
||||
for (char ch : s) {
|
||||
if (ch == '"' || ch == '\\') { o += '\\'; o += ch; }
|
||||
else if ((unsigned char)ch < 0x20) { char b[8]; snprintf(b, sizeof b, "\\u%04x", ch); o += b; }
|
||||
else o += ch;
|
||||
}
|
||||
return o;
|
||||
// PS5 Upload's console shell (its own built-in commands; there is no real shell on a PS5).
|
||||
nlohmann::json shell(const std::string &cmd, int timeout_ms = 30000) {
|
||||
return nlohmann::json::parse(call_str(SHELL_EXEC, nlohmann::json{{"cmd", cmd}, {"cwd", "/"}}.dump(), timeout_ms));
|
||||
}
|
||||
|
||||
private:
|
||||
static void expect_ack(Conn &c, uint16_t want, const char *what) {
|
||||
auto [ft, body] = c.recv_frame();
|
||||
if (ft == ERROR_) throw Error(std::string("PS5 refused to ") + what + ": " + std::string(body.begin(), body.end()));
|
||||
if (ft != want) throw Error(std::string("Unexpected reply during ") + what);
|
||||
std::vector<uint8_t> proxy(const nlohmann::json &req, const std::string &label, int timeout_ms) {
|
||||
auto [status, body] = http(engine_host, engine_port, "POST", "/api/mgmt/call", req.dump(), timeout_ms + 10000);
|
||||
if (status == 404) throw Error("This version of PS5 Upload is too old for PSGFX. Update PS5 Upload to version 6 or newer.");
|
||||
nlohmann::json j;
|
||||
try { j = nlohmann::json::parse(body); }
|
||||
catch (...) { throw Error("PS5 Upload refused the request (HTTP " + std::to_string(status) + "): " + body.substr(0, 300)); }
|
||||
if (j.value("ok", false)) return b64_decode(j["result"].value("body_b64", ""));
|
||||
auto e = j.value("error", nlohmann::json::object());
|
||||
std::string cause = e.value("cause", e.value("message", std::string("unknown error")));
|
||||
if (cause.find("not_paired") != std::string::npos)
|
||||
throw Error("Your PS5 hasn't accepted PS5 Upload yet. Pair them on PS5 Upload's Connection screen, then try again.");
|
||||
if (cause.find("helper_not_ava1") != std::string::npos)
|
||||
throw Error("PS5 Upload's payload isn't running on the PS5 at " + host + " (or it's an old version). "
|
||||
"Send it from PS5 Upload's Connection screen, then try again.");
|
||||
if (cause.find("ava1_unreachable") != std::string::npos || cause.find("did not answer") != std::string::npos)
|
||||
throw Error("Can't reach the PS5 at " + host + ". Check the IP, and that PS5 Upload can see the console.");
|
||||
throw Error(label + ": " + cause);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace ps5
|
||||
} // namespace ps5
|
||||
@@ -2,8 +2,8 @@
|
||||
IDI_ICON1 ICON "../assets/psgfx.ico"
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION 1,0,0,0
|
||||
PRODUCTVERSION 1,0,0,0
|
||||
FILEVERSION 1,1,0,0
|
||||
PRODUCTVERSION 1,1,0,0
|
||||
FILEOS VOS_NT_WINDOWS32
|
||||
FILETYPE VFT_APP
|
||||
BEGIN
|
||||
@@ -11,10 +11,10 @@ BEGIN
|
||||
BEGIN
|
||||
BLOCK "040904b0"
|
||||
BEGIN
|
||||
VALUE "FileDescription", "PSGFX - custom icons and backgrounds for your PS5"
|
||||
VALUE "FileVersion", "1.0.0"
|
||||
VALUE "FileDescription", "PSGFX - custom art and home-screen layout for your PS5"
|
||||
VALUE "FileVersion", "1.1.0"
|
||||
VALUE "ProductName", "PSGFX"
|
||||
VALUE "ProductVersion", "1.0.0"
|
||||
VALUE "ProductVersion", "1.1.0"
|
||||
VALUE "OriginalFilename", "PSGFX.exe"
|
||||
END
|
||||
END
|
||||
|
||||
@@ -22,6 +22,13 @@ html,body{margin:0;min-height:100%}
|
||||
body{background:radial-gradient(1200px 700px at 70% -10%,#13244a 0%,transparent 60%),var(--bg);background-attachment:fixed;color:var(--text);font-size:14px;line-height:1.5}
|
||||
button,input{font:inherit;color:inherit}
|
||||
:focus-visible{outline:2px solid var(--blue-hi);outline-offset:2px}
|
||||
/* Scrollbars in the app's own style, not the browser's grey ones. */
|
||||
::-webkit-scrollbar{width:12px;height:12px}
|
||||
::-webkit-scrollbar-track,::-webkit-scrollbar-corner{background:transparent}
|
||||
::-webkit-scrollbar-thumb{background:rgba(160,190,255,.2);border-radius:12px;border:3px solid transparent;background-clip:padding-box}
|
||||
::-webkit-scrollbar-thumb:hover{background-color:rgba(160,190,255,.3)}
|
||||
::-webkit-scrollbar-thumb:active{background-color:var(--blue)}
|
||||
@supports not selector(::-webkit-scrollbar){*{scrollbar-width:thin;scrollbar-color:rgba(160,190,255,.22) transparent}}
|
||||
|
||||
.top{display:flex;align-items:center;gap:20px;padding:16px 24px;border-bottom:1px solid var(--line)}
|
||||
.brand{display:flex;align-items:flex-end;gap:10px}
|
||||
@@ -54,7 +61,7 @@ button,input{font:inherit;color:inherit}
|
||||
.app.locked{opacity:.5}
|
||||
.empty{color:var(--muted);padding:8px;font-size:13px}
|
||||
|
||||
main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:column;gap:20px;max-width:1180px}
|
||||
main{border-left:1px solid var(--line);padding:24px max(24px,calc((100% - 1132px)/2));display:flex;flex-direction:column;gap:20px;min-width:0}
|
||||
|
||||
/* The PS5 home-screen replica: the one bold element. */
|
||||
.stage{position:relative;aspect-ratio:16/9;width:min(100%,calc((100vh - 330px)*16/9));min-width:min(100%,520px);margin:0 auto;border-radius:var(--r-lg);overflow:hidden;background:linear-gradient(135deg,#101b33,#060913);border:1px solid var(--line);box-shadow:0 30px 80px rgba(0,0,0,.5)}
|
||||
@@ -76,10 +83,26 @@ main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:
|
||||
.stage-hint{position:absolute;right:2%;bottom:3%;font-size:12px;color:rgba(255,255,255,.75)}
|
||||
.staged-badge{position:absolute;top:3%;right:2%;padding:4px 10px;border-radius:999px;background:rgba(61,123,255,.85);font-size:12px;font-weight:600;display:none}
|
||||
|
||||
.namerow{display:grid;gap:6px;max-width:480px}
|
||||
.namerow label{font-size:12.5px;color:var(--muted)}
|
||||
.slots{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}
|
||||
.slot{background:var(--glass);border:1px solid var(--line);border-radius:var(--r-md);padding:14px;display:flex;gap:12px;align-items:center;min-height:92px}
|
||||
.slot .thumb{width:64px;height:64px;border-radius:10px;background:var(--bg2) center/cover no-repeat;flex:none;border:1px solid var(--line)}
|
||||
.slot.bgslot .thumb{width:96px;height:54px}
|
||||
.slot.musicslot{grid-column:1/-1;flex-wrap:wrap}
|
||||
.presets{grid-column:1/-1;background:var(--glass);border:1px solid var(--line);border-radius:var(--r-md);padding:14px}
|
||||
.presets .t{font-weight:600}.presets .s{color:var(--muted);font-size:12px}
|
||||
.presets .row{display:flex;gap:10px;flex-wrap:wrap;margin-top:10px}
|
||||
.presets button{width:72px;height:72px;padding:0;border-radius:12px;border:2px solid transparent;background:var(--bg2) center/cover no-repeat;cursor:pointer}
|
||||
.presets button:hover{border-color:var(--line)}
|
||||
.presets button[aria-pressed="true"]{border-color:var(--blue-hi)}
|
||||
.slot.musicslot .thumb{display:grid;place-items:center;font-size:26px;color:var(--muted)}
|
||||
.mclip{display:none;gap:10px;align-items:center;flex-wrap:wrap;width:100%;margin-top:4px}
|
||||
.mclip.on{display:flex}
|
||||
.mclip label{color:var(--muted);font-size:12px;display:flex;gap:6px;align-items:center}
|
||||
.mclip input,.mclip select{padding:5px 8px;border-radius:var(--r-sm);border:1px solid var(--line);background:var(--glass);color:var(--text);font-size:12px}
|
||||
.mclip input{width:70px}
|
||||
.mclip audio{height:32px;flex:1;min-width:220px}
|
||||
.slot .meta{min-width:0;flex:1}
|
||||
.slot .t{font-weight:600}
|
||||
.slot .s{color:var(--muted);font-size:12px}
|
||||
@@ -94,6 +117,79 @@ main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:
|
||||
.log.ok{border-color:rgba(61,220,151,.4)} .log.bad{border-color:rgba(255,107,107,.5);color:#ffd0d0}
|
||||
.welcome{max-width:560px;color:var(--muted)}
|
||||
.welcome h1{color:var(--text);font-size:26px;letter-spacing:-.02em;margin:0 0 8px}
|
||||
/* ── header views ── */
|
||||
.views{display:flex;gap:4px;margin-left:8px;padding:3px;border-radius:999px;background:var(--glass);border:1px solid var(--line)}
|
||||
.views button{border:0;background:none;padding:6px 14px;border-radius:999px;color:var(--muted);cursor:pointer;font-weight:600;font-size:13px}
|
||||
.views button[aria-pressed="true"]{background:var(--glass-hi);color:var(--text)}
|
||||
|
||||
/* ── home layout ── */
|
||||
.lv{display:grid;grid-template-columns:1fr 320px;min-height:calc(100vh - 66px)}
|
||||
.lv-main{padding:24px;display:flex;flex-direction:column;gap:16px;min-width:0}
|
||||
.lv-empty{max-width:560px;color:var(--muted)}
|
||||
.lv-empty h1{color:var(--text);font-size:26px;letter-spacing:-.02em;margin:0 0 8px}
|
||||
.lstage{position:relative;aspect-ratio:16/9;width:min(100%,calc((100vh - 470px)*16/9));min-width:min(100%,520px);margin:0 auto;border-radius:var(--r-lg);overflow:hidden;background:linear-gradient(135deg,#101b33,#060913);border:1px solid var(--line);box-shadow:0 30px 80px rgba(0,0,0,.5)}
|
||||
.lstage .bgimg{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
|
||||
.ltabs{position:absolute;left:4.5%;top:4%;display:flex;gap:clamp(14px,2.4vw,30px);font-size:clamp(11px,1.4vw,17px);color:rgba(255,255,255,.65)}
|
||||
.ltabs span{padding-bottom:3px;border-bottom:2px solid transparent;cursor:pointer}
|
||||
.ltabs span.on{color:#fff;border-color:#fff}
|
||||
.lrow{position:absolute;left:4.5%;right:0;top:14%;display:flex;gap:.9%;align-items:flex-start;overflow:hidden}
|
||||
.ltile{flex:none;width:6.2%;aspect-ratio:1;border-radius:8%;background:rgba(255,255,255,.12) center/cover;cursor:pointer;position:relative}
|
||||
.ltile.sel{width:12.5%;border-radius:7%;box-shadow:0 0 0 2px rgba(255,255,255,.9),0 8px 30px rgba(0,0,0,.5)}
|
||||
.ltile i,.lcard .im i{position:absolute;inset:0;display:grid;place-items:center;font-style:normal;font-weight:600;font-size:clamp(8px,1vw,14px);color:rgba(255,255,255,.8)}
|
||||
.ltitle{position:absolute;left:4.5%;top:42%;font-size:clamp(14px,2.2vw,30px);font-weight:600;text-shadow:0 2px 12px rgba(0,0,0,.6);max-width:60%}
|
||||
.lsub{position:absolute;left:4.5%;top:calc(42% + clamp(20px,3vw,40px));font-size:clamp(10px,1vw,13px);color:rgba(255,255,255,.7)}
|
||||
.lbar{display:flex;align-items:center;gap:4px;flex-wrap:wrap;width:min(100%,calc((100vh - 470px)*16/9));min-width:min(100%,520px);margin:0 auto}
|
||||
.ltab{border:0;background:none;padding:7px 12px;border-radius:var(--r-sm);color:var(--muted);cursor:pointer;font-weight:600}
|
||||
.ltab[aria-pressed="true"]{background:var(--glass-hi);color:var(--text)}
|
||||
.ltab small{font-weight:400;color:var(--muted);margin-left:4px}
|
||||
.lsorts{margin-left:auto;display:flex;align-items:center;gap:2px}
|
||||
.lsorts .btn{padding:5px 10px;font-size:12px}
|
||||
.lsorts label{display:flex;align-items:center;gap:6px;font-size:12.5px;color:var(--muted);margin-left:8px;cursor:pointer}
|
||||
.lstrip{display:flex;gap:16px;overflow-x:auto;padding:4px 2px 16px;width:min(100%,calc((100vh - 470px)*16/9));min-width:min(100%,520px);margin:0 auto}
|
||||
.lgrp{display:flex;flex-direction:column;gap:8px;flex:none}
|
||||
.lgrp + .lgrp{padding-left:16px;border-left:1px solid var(--line)}
|
||||
.lgrp>span{font-size:12px;color:var(--muted)}
|
||||
.lcards{display:flex;gap:10px}
|
||||
.lcard{flex:none;width:112px;padding:7px;border-radius:var(--r-md);border:1px solid transparent;background:var(--glass);cursor:pointer;position:relative;text-align:left}
|
||||
.lcard:hover{background:var(--glass-hi)}
|
||||
.lcard[aria-current="true"]{border-color:var(--blue-hi);background:var(--glass-hi)}
|
||||
.lcard.drag{opacity:.35}
|
||||
.lcard.over{box-shadow:-5px 0 0 -2px var(--blue-hi)}
|
||||
.lcard .im{aspect-ratio:1;border-radius:9px;background:var(--bg2) center/cover;position:relative}
|
||||
.lcard .nm{margin-top:6px;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.lcard .bd{position:absolute;top:12px;right:12px;font-size:10.5px;font-weight:600;padding:2px 6px;border-radius:999px;background:var(--warn);color:#2a1800}
|
||||
.lempty{color:var(--muted);padding:20px;border:1px dashed var(--line);border-radius:var(--r-md);flex:1;text-align:center}
|
||||
.lwarn{width:min(100%,calc((100vh - 470px)*16/9));margin:0 auto;padding:10px 14px;border-radius:var(--r-md);background:rgba(255,181,71,.08);border:1px solid rgba(255,181,71,.3);color:#ffd9a0;font-size:13px}
|
||||
.lside{border-left:1px solid var(--line);padding:20px;display:flex;flex-direction:column;gap:18px}
|
||||
.lside h2{font-size:18px;margin:0;letter-spacing:-.01em}
|
||||
.lside .id{font-size:12px;color:var(--muted)}
|
||||
.lsec{display:grid;gap:8px}
|
||||
.lsec>label,.lsec>.lbl{font-size:12.5px;color:var(--muted)}
|
||||
.lseg{display:grid;grid-template-columns:repeat(3,1fr);padding:3px;border-radius:var(--r-sm);background:var(--glass);border:1px solid var(--line)}
|
||||
.lseg button{border:0;background:none;padding:7px 0;border-radius:6px;color:var(--muted);cursor:pointer}
|
||||
.lseg button[aria-pressed="true"]{background:var(--glass-hi);color:var(--text)}
|
||||
.ltxt{width:100%;padding:9px 11px;border-radius:var(--r-sm);border:1px solid var(--line);background:var(--glass)}
|
||||
.lnote{font-size:12px;color:var(--muted)}
|
||||
.linker{border:0;background:none;color:var(--blue-hi);padding:0;cursor:pointer;justify-self:start;font-size:13px}
|
||||
.lfoot{position:sticky;bottom:0;display:flex;align-items:center;gap:10px;padding:12px 20px;border-top:1px solid var(--line);background:rgba(6,9,19,.92);backdrop-filter:blur(8px);grid-column:1/-1}
|
||||
.lfoot .pend{color:var(--muted);display:flex;align-items:center;gap:8px}
|
||||
.lfoot .pend b{width:8px;height:8px;border-radius:50%;background:#4a5570}
|
||||
.lfoot .pend.has{color:var(--text)} .lfoot .pend.has b{background:var(--warn)}
|
||||
.lfoot .sp{flex:1}
|
||||
.scrim{position:fixed;inset:0;display:none;place-items:center;background:rgba(3,5,10,.7);z-index:20}
|
||||
.scrim.open{display:grid}
|
||||
.dlg{width:min(560px,92vw);max-height:84vh;overflow:auto;background:#0c1426;border:1px solid var(--line);border-radius:var(--r-lg);padding:22px}
|
||||
.dlg h3{margin:0 0 6px;font-size:18px}
|
||||
.dlg p{margin:0 0 12px;color:var(--muted)}
|
||||
.dlg .li{display:flex;align-items:center;gap:12px;padding:10px 12px;border-radius:var(--r-sm);background:var(--glass);border:1px solid var(--line);margin-bottom:6px}
|
||||
.dlg .li div{flex:1;min-width:0}
|
||||
.dlg .li small{display:block;color:var(--muted)}
|
||||
.dlg .acts{display:flex;justify-content:flex-end;gap:8px;margin-top:16px}
|
||||
.dlg pre{white-space:pre-wrap;font-size:12px;background:var(--glass);border:1px solid var(--line);border-radius:var(--r-sm);padding:10px;color:var(--muted);max-height:240px;overflow:auto}
|
||||
.dlg .chk{display:flex;align-items:center;gap:8px;margin:14px 0 8px;cursor:pointer}
|
||||
.busyv{position:fixed;inset:0;display:none;place-items:center;background:rgba(3,5,10,.55);z-index:30;color:var(--muted)}
|
||||
.busyv.open{display:grid}
|
||||
@media (max-width:900px){.lv{grid-template-columns:1fr}.lside{border-left:0;border-top:1px solid var(--line)}}
|
||||
.hidden{display:none!important}
|
||||
@media (max-width:900px){.layout{grid-template-columns:1fr}.rail{max-height:none;position:static;border-bottom:1px solid var(--line)}main{border-left:0}.slots{grid-template-columns:1fr}}
|
||||
@media (prefers-reduced-motion:reduce){*{transition:none!important}}
|
||||
@@ -101,7 +197,8 @@ main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:
|
||||
</head>
|
||||
<body>
|
||||
<header class="top">
|
||||
<div class="brand"><img src="/wordmark.png" alt="PSGFX"><span>1.0</span></div>
|
||||
<div class="brand"><img src="/wordmark.png" alt="PSGFX"><span>1.3</span></div>
|
||||
<nav class="views" aria-label="View"><button data-v="art" aria-pressed="true">Art</button><button data-v="layout" aria-pressed="false">Home layout</button></nav>
|
||||
<form class="connect" id="cf">
|
||||
<span class="dot" id="dot" aria-hidden="true"></span>
|
||||
<label for="ip">PS5 IP</label>
|
||||
@@ -118,7 +215,7 @@ main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:
|
||||
<main>
|
||||
<section class="welcome" id="welcome">
|
||||
<h1>New art for your homebrew and games.</h1>
|
||||
<p>Make sure PS5 Upload's payload is running on your console, then enter your PS5's IP above. Pick an app or game, drop images onto the preview, and apply.</p>
|
||||
<p>Open the PS5 Upload app on this PC (version 6 or newer) and connect it to your console, then enter your PS5's IP above. Pick an app or game, drop images onto the preview, and apply.</p>
|
||||
</section>
|
||||
|
||||
<section id="editor" class="hidden" aria-label="Artwork editor">
|
||||
@@ -132,31 +229,86 @@ main{border-left:1px solid var(--line);padding:24px;display:flex;flex-direction:
|
||||
<div class="titlezone"><div class="tname" id="tname"></div></div>
|
||||
<div class="play" aria-hidden="true">Play</div>
|
||||
<div class="staged-badge" id="badge">Preview - not applied yet</div>
|
||||
<div class="stage-hint">Drop an image on the tile or the background</div>
|
||||
<div class="stage-hint">Drop an image on the tile or the background, or a song anywhere</div>
|
||||
<div class="drop d-bg" data-kind="background">Background</div>
|
||||
<div class="drop d-icon" data-kind="icon">Icon</div>
|
||||
</div>
|
||||
|
||||
<div class="namerow" style="margin-top:20px"><label for="aname">Name on the home screen</label><input class="ltxt" id="aname" maxlength="80" autocomplete="off"></div>
|
||||
|
||||
<div class="slots" style="margin-top:20px">
|
||||
<div class="slot" data-kind="icon"><div class="thumb"></div><div class="meta"><div class="t">Icon</div><div class="s">Square, 512 × 512 or larger</div><div class="row"><button class="btn pick">Choose image</button><button class="btn clear hidden">Remove</button></div></div></div>
|
||||
<div class="slot bgslot" data-kind="background"><div class="thumb"></div><div class="meta"><div class="t">Background</div><div class="s">16:9, ideally 3840 × 2160</div><div class="row"><button class="btn pick">Choose image</button><button class="btn clear hidden">Remove</button></div></div></div>
|
||||
<div class="presets hidden" id="presets"><div class="t">Preset icons</div><div class="s" id="presetsS"></div><div class="row" id="presetsRow"></div></div>
|
||||
<div class="slot musicslot" data-kind="music"><div class="thumb" aria-hidden="true">♫</div><div class="meta"><div class="t">Music</div><div class="s">MP3, WAV or FLAC. Plays when the tile is selected.</div><div class="row"><button class="btn pick">Choose song</button><button class="btn clear hidden">Remove</button></div></div>
|
||||
<div class="mclip" id="mclip">
|
||||
<label>Start <input id="mstart" value="0:00" inputmode="numeric" title="Where the clip starts in the song (m:ss)"></label>
|
||||
<label>Length <select id="mlen"><option value="15">15 s</option><option value="30">30 s</option><option value="60">60 s</option><option value="0">Longest that fits</option></select></label>
|
||||
<audio id="maudio" controls preload="none"></audio>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="actions" style="margin-top:20px">
|
||||
<button class="btn primary" id="apply" disabled>Apply to PS5</button>
|
||||
<button class="btn" id="restore">Restore original art</button>
|
||||
<button class="btn" id="restore">Restore original</button>
|
||||
<span class="note" id="anote">Close the app on your PS5 before applying.</span>
|
||||
</div>
|
||||
<ul class="log" id="log"></ul>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
<section class="lv hidden" id="lv" aria-label="Home layout">
|
||||
<div class="lv-main">
|
||||
<div class="lv-empty" id="lvEmpty">
|
||||
<h1>Arrange your home screen.</h1>
|
||||
<p>Hide tiles like the PlayStation Store, move apps between Games and Media, rename anything, and put your games in any order. Connect to your PS5 above to start. PSGFX backs up the home screen before every change.</p>
|
||||
</div>
|
||||
<div id="lvBody" class="hidden" style="display:contents">
|
||||
<div id="lvWarn"></div>
|
||||
<div class="lstage" id="lstage">
|
||||
<img class="bgimg hidden" id="lbg" alt="">
|
||||
<div class="shade" style="position:absolute;inset:0;background:linear-gradient(180deg,rgba(0,0,0,.45) 0%,transparent 30%,transparent 55%,rgba(0,0,0,.7) 100%)"></div>
|
||||
<div class="ltabs"><span data-w="games">Games</span><span data-w="media">Media</span></div>
|
||||
<div class="lrow" id="lrow"></div>
|
||||
<div class="ltitle" id="ltitle"></div>
|
||||
<div class="lsub" id="lsub"></div>
|
||||
</div>
|
||||
<div class="lbar">
|
||||
<button class="ltab" data-w="games">Games<small id="lcG"></small></button>
|
||||
<button class="ltab" data-w="media">Media<small id="lcM"></small></button>
|
||||
<button class="ltab" data-w="hidden">Hidden<small id="lcH"></small></button>
|
||||
<div class="lsorts" id="lsorts">
|
||||
<button class="btn" data-sort="az" title="Sort A to Z">A–Z</button>
|
||||
<button class="btn" data-sort="za" title="Sort Z to A">Z–A</button>
|
||||
<button class="btn" data-sort="recent" title="Back to recently played order">Recent</button>
|
||||
<label title="Keeps this order even after you play other games"><input type="checkbox" id="llock"> Lock order</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="lstrip" id="lstrip"></div>
|
||||
</div>
|
||||
</div>
|
||||
<aside class="lside" id="lside"><p class="lnote">Select a tile to change it.</p></aside>
|
||||
<footer class="lfoot">
|
||||
<div class="pend" id="lpend"><b></b><span>No changes</span></div>
|
||||
<span class="sp"></span>
|
||||
<button class="btn" id="lPresets">Presets</button>
|
||||
<button class="btn" id="lBackups">Backups</button>
|
||||
<button class="btn" id="lReload">Reload</button>
|
||||
<button class="btn" id="lDiscard" disabled>Discard</button>
|
||||
<button class="btn primary" id="lApply" disabled>Apply to PS5</button>
|
||||
</footer>
|
||||
</section>
|
||||
<div class="scrim" id="dlg"><div class="dlg" id="dlgBody"></div></div>
|
||||
<div class="busyv" id="busyv"><span id="busyT">Working…</span></div>
|
||||
<input type="file" id="file" accept="image/png,image/jpeg" hidden>
|
||||
<input type="file" id="afile" accept=".mp3,.wav,.flac,.aif,.aiff,audio/*" hidden>
|
||||
|
||||
<script>
|
||||
const $ = s => document.querySelector(s);
|
||||
const st = { apps: [], sel: null, staged: {} };
|
||||
const KINDS = ['icon','background'];
|
||||
const KINDS = ['icon','background','music'];
|
||||
const HINT = {icon:'Square, 512 × 512 or larger', background:'16:9, ideally 3840 × 2160', music:'MP3, WAV or FLAC. Plays when the tile is selected.'};
|
||||
|
||||
async function api(path, opts={}) {
|
||||
const r = await fetch(path, opts);
|
||||
@@ -174,6 +326,7 @@ $('#cf').addEventListener('submit', async e => {
|
||||
try {
|
||||
const j = await api('/api/connect', {method:'POST', body: JSON.stringify({ip})});
|
||||
st.apps = j.apps; setDot('ok'); renderApps();
|
||||
L.loaded = false; if (!$('#lv').classList.contains('hidden')) lload();
|
||||
} catch (err) {
|
||||
setDot(''); $('#apps').innerHTML = ''; const p=document.createElement('p'); p.className='empty'; p.textContent = err.message; $('#apps').appendChild(p);
|
||||
} finally { $('#cbtn').disabled = false; }
|
||||
@@ -225,9 +378,31 @@ async function select(a, btn){
|
||||
st.staged = {};
|
||||
$('#welcome').classList.add('hidden'); $('#editor').classList.remove('hidden'); $('#log').style.display='none';
|
||||
$('#tname').textContent = a.title_name || a.title_id;
|
||||
$('#aname').value = a.title_name || a.title_id;
|
||||
const game = a.kind === 'game';
|
||||
$('#anote').textContent = game ? 'Close the game first. The PS5 may put back its original art when the game updates.' : 'Close the app on your PS5 before applying.';
|
||||
refreshPreview(true);
|
||||
loadPresets(a);
|
||||
}
|
||||
|
||||
async function loadPresets(a){
|
||||
const box = $('#presets'), row = $('#presetsRow');
|
||||
box.classList.add('hidden'); row.innerHTML = '';
|
||||
let j; try { j = await api('/api/presets/' + encodeURIComponent(a.title_id)); } catch { return; }
|
||||
if (st.sel !== a || !j.presets.length) return;
|
||||
$('#presetsS').textContent = 'Made for ' + j.presets[0].app + '. Pick one to use it as the icon.';
|
||||
for (const p of j.presets) {
|
||||
const b = document.createElement('button');
|
||||
b.style.backgroundImage = `url(/api/preset/${p.i})`; b.title = p.app + ' preset ' + (row.children.length + 1);
|
||||
b.setAttribute('aria-label', b.title); b.setAttribute('aria-pressed', 'false');
|
||||
b.onclick = async () => {
|
||||
row.querySelectorAll('button').forEach(x => x.setAttribute('aria-pressed', 'false'));
|
||||
try { const r = await api('/api/preset/' + p.i, {method:'POST'}); st.staged.icon = {note: r.note || ''}; b.setAttribute('aria-pressed', 'true'); refreshPreview(false); }
|
||||
catch (err) { $('#presetsS').textContent = err.message; }
|
||||
};
|
||||
row.appendChild(b);
|
||||
}
|
||||
box.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function refreshPreview(loadCurrent){
|
||||
@@ -239,30 +414,60 @@ function refreshPreview(loadCurrent){
|
||||
bg.src = '/api/current/'+encodeURIComponent(a.title_id)+'?src='+encodeURIComponent(a.src)+'&t='+t; }
|
||||
document.querySelectorAll('.slot').forEach(sl => {
|
||||
const k = sl.dataset.kind, s = st.staged[k];
|
||||
sl.querySelector('.thumb').style.backgroundImage = s ? `url(/api/staged/${k}?t=${t})` : '';
|
||||
if (k !== 'music') sl.querySelector('.thumb').style.backgroundImage = s ? `url(/api/staged/${k}?t=${t})` : '';
|
||||
sl.querySelector('.clear').classList.toggle('hidden', !s);
|
||||
const sEl = sl.querySelector('.s');
|
||||
if (s && s.note) { sEl.textContent = s.note; sEl.classList.add('warn'); }
|
||||
else if (s) { sEl.textContent = 'Ready to apply'; sEl.classList.remove('warn'); }
|
||||
else { sEl.textContent = {icon:'Square, 512 × 512 or larger',background:'16:9, ideally 3840 × 2160'}[k]; sEl.classList.remove('warn'); }
|
||||
else if (s) { sEl.textContent = s.summary ? 'Ready to apply: ' + s.summary : 'Ready to apply'; sEl.classList.remove('warn'); }
|
||||
else { sEl.textContent = HINT[k]; sEl.classList.remove('warn'); }
|
||||
});
|
||||
const any = KINDS.some(k => st.staged[k]);
|
||||
const m = st.staged.music;
|
||||
$('#mclip').classList.toggle('on', !!m);
|
||||
if (m && m.fresh) { $('#maudio').src = '/api/staged/music?t='+t; m.fresh = false; }
|
||||
if (!m) $('#maudio').removeAttribute('src');
|
||||
updateApply();
|
||||
}
|
||||
const newName = () => { const v = $('#aname').value.trim(); return v && v !== (st.sel.title_name || st.sel.title_id) ? v : null; };
|
||||
function updateApply(){
|
||||
const any = KINDS.some(k => st.staged[k]) || !!newName();
|
||||
$('#apply').disabled = !any; $('#badge').style.display = any ? 'block' : 'none';
|
||||
}
|
||||
$('#aname').addEventListener('input', () => { $('#tname').textContent = $('#aname').value.trim() || st.sel.title_name || st.sel.title_id; updateApply(); });
|
||||
$('#aname').addEventListener('keydown', e => { if (e.key === 'Enter' && !$('#apply').disabled) $('#apply').click(); });
|
||||
|
||||
async function stage(kind, file){
|
||||
const sl = document.querySelector(`.slot[data-kind="${kind}"] .s`);
|
||||
sl.textContent = 'Loading…'; sl.classList.remove('warn');
|
||||
try {
|
||||
if (kind === 'music') sl.textContent = 'Converting… this takes a few seconds.';
|
||||
const j = await api('/api/stage/'+kind, {method:'POST', body: await file.arrayBuffer()});
|
||||
st.staged[kind] = {note: j.note || ''};
|
||||
st.staged[kind] = {note: j.note || '', summary: j.summary || '', fresh: true};
|
||||
if (kind === 'music') { $('#mstart').value = fmtTime(j.start); $('#mlen').value = String(j.duration); }
|
||||
} catch (err) { sl.textContent = err.message; sl.classList.add('warn'); return; }
|
||||
refreshPreview(false);
|
||||
}
|
||||
|
||||
const fmtTime = v => Math.floor(v/60) + ':' + String(Math.floor(v%60)).padStart(2,'0');
|
||||
const parseTime = v => { const p = String(v).trim().split(':').map(Number); if (p.some(isNaN)) return 0; return p.length > 1 ? p[0]*60 + p[1] : p[0]; };
|
||||
async function reclip(){
|
||||
const sl = document.querySelector('.slot[data-kind="music"] .s');
|
||||
sl.textContent = 'Converting…'; sl.classList.remove('warn');
|
||||
try {
|
||||
const j = await api('/api/music/clip', {method:'POST', body: JSON.stringify({start: parseTime($('#mstart').value), duration: Number($('#mlen').value)})});
|
||||
st.staged.music = {note: j.note || '', summary: j.summary || '', fresh: true};
|
||||
$('#mstart').value = fmtTime(j.start);
|
||||
} catch (err) { sl.textContent = err.message; sl.classList.add('warn'); return; }
|
||||
refreshPreview(false);
|
||||
}
|
||||
$('#mstart').addEventListener('change', reclip); $('#mlen').addEventListener('change', reclip);
|
||||
$('#afile').onchange = e => { const f = e.target.files[0]; if (f) stage('music', f); };
|
||||
const isAudio = f => /^audio\//.test(f.type) || /\.(mp3|wav|flac|aiff?)$/i.test(f.name);
|
||||
|
||||
let pickKind = null;
|
||||
document.querySelectorAll('.slot').forEach(sl => {
|
||||
sl.querySelector('.pick').onclick = () => { pickKind = sl.dataset.kind; $('#file').value=''; $('#file').click(); };
|
||||
sl.querySelector('.pick').onclick = () => {
|
||||
if (sl.dataset.kind === 'music') { $('#afile').value=''; $('#afile').click(); return; }
|
||||
pickKind = sl.dataset.kind; $('#file').value=''; $('#file').click(); };
|
||||
sl.querySelector('.clear').onclick = async () => { await api('/api/unstage/'+sl.dataset.kind); delete st.staged[sl.dataset.kind]; refreshPreview(true); };
|
||||
});
|
||||
$('#file').onchange = e => { const f = e.target.files[0]; if (f && pickKind) stage(pickKind, f); };
|
||||
@@ -282,20 +487,32 @@ stageEl.addEventListener('dragover', e => {
|
||||
});
|
||||
stageEl.addEventListener('drop', e => {
|
||||
e.preventDefault(); dragDepth=0; stageEl.classList.remove('dragging');
|
||||
const f = e.dataTransfer.files[0]; if (f) stage(zoneAt(e.clientX, e.clientY), f);
|
||||
const f = e.dataTransfer.files[0]; if (f) stage(isAudio(f) ? 'music' : zoneAt(e.clientX, e.clientY), f);
|
||||
});
|
||||
window.addEventListener('dragover', e => e.preventDefault()); window.addEventListener('drop', e => e.preventDefault());
|
||||
|
||||
$('#apply').onclick = async () => {
|
||||
const a = st.sel; $('#apply').disabled = true; showLog(['Converting and uploading to '+(a.title_name||a.title_id)+'…'], '');
|
||||
const a = st.sel, art = KINDS.some(k => st.staged[k]), name = newName(), lines = [];
|
||||
$('#apply').disabled = true; showLog([art ? 'Converting and uploading to '+(a.title_name||a.title_id)+'…' : 'Renaming '+(a.title_name||a.title_id)+'…'], '');
|
||||
const ids = {title_id:a.title_id, src:a.src, kind:a.kind};
|
||||
let artDone = false;
|
||||
try {
|
||||
const j = await api('/api/apply', {method:'POST', body: JSON.stringify({title_id:a.title_id, src:a.src, kind:a.kind})});
|
||||
showLog(j.log, 'ok'); st.staged = {}; refreshPreview(true);
|
||||
refreshRailIcon(a);
|
||||
} catch (err) { showLog(['Apply failed: '+err.message], 'bad'); $('#apply').disabled = false; }
|
||||
if (art) {
|
||||
const j = await api('/api/apply', {method:'POST', body: JSON.stringify(ids)});
|
||||
lines.push(...j.log); st.staged = {}; artDone = true; refreshRailIcon(a);
|
||||
}
|
||||
if (name) {
|
||||
const j = await api('/api/rename', {method:'POST', body: JSON.stringify({...ids, name})});
|
||||
lines.push(...j.log); a.title_name = j.name; L.loaded = false;
|
||||
const n = document.querySelector('.app[aria-current="true"] .n'); if (n) n.textContent = j.name;
|
||||
$('#aname').value = j.name; $('#tname').textContent = j.name;
|
||||
}
|
||||
showLog(lines, 'ok');
|
||||
} catch (err) { showLog([...lines, (art && !artDone ? 'Apply failed: ' : 'Rename failed: ')+err.message], 'bad'); }
|
||||
if (artDone) refreshPreview(true); else updateApply();
|
||||
};
|
||||
$('#restore').onclick = async () => {
|
||||
const a = st.sel; showLog(['Restoring original art…'], '');
|
||||
const a = st.sel; showLog(['Restoring the original art and music…'], '');
|
||||
try {
|
||||
const j = await api('/api/restore', {method:'POST', body: JSON.stringify({title_id:a.title_id, src:a.src, kind:a.kind})});
|
||||
showLog(j.log, 'ok'); refreshPreview(true);
|
||||
@@ -304,6 +521,249 @@ $('#restore').onclick = async () => {
|
||||
};
|
||||
function refreshRailIcon(a){ const im = document.querySelector('.app[aria-current="true"] .ic'); if (im) { im.classList.remove('none'); im.src = '/api/icon/'+encodeURIComponent(a.title_id)+'?t='+Date.now(); } }
|
||||
|
||||
// ─────────────────────────── Home layout ───────────────────────────
|
||||
const L = { info:null, edits:{}, order:[], base:[], dragged:false, w:'games', sel:null, focus:0, loaded:false, lastPreset:'' };
|
||||
const LIB = 'NPXS40071';
|
||||
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const limg = p => p ? '/api/layout/img?p=' + encodeURIComponent(p) : '';
|
||||
const ltiles = () => L.info?.tiles ?? [];
|
||||
const lbyId = id => ltiles().find(t => t.id === id);
|
||||
function leff(t){
|
||||
const e = L.edits[t.id] || {};
|
||||
return {...t, where: e.where ?? t.where, name: e.name ?? t.name, changed: !!L.edits[t.id]};
|
||||
}
|
||||
function lchanges(){ return Object.keys(L.edits).length + (L.dragged ? 1 : 0); }
|
||||
function lgroups(w){
|
||||
const all = ltiles().map(leff);
|
||||
if (w === 'hidden') return [{key:'hidden', label:'Hidden from the home screen', list: all.filter(t => t.where === 'hidden')}];
|
||||
const sys = all.filter(t => t.kind === 'system' && t.where === w).sort((a,b) => (b.home - a.home) || (a.homeIdx - b.homeIdx) || (b.access - a.access));
|
||||
return [{key:'system', label:'System', list: sys},
|
||||
{key:'mine', label: w === 'games' ? 'Games' : 'Apps', list: L.order.map(id => leff(lbyId(id))).filter(t => t.where === w)}];
|
||||
}
|
||||
function lrowFor(w){
|
||||
const [sys, mine] = lgroups(w).map(g => g.list);
|
||||
if (w === 'media') return [...mine, ...sys];
|
||||
const lib = sys.filter(t => t.id === LIB), lead = sys.filter(t => t.home && t.id !== LIB), rest = sys.filter(t => !t.home && t.id !== LIB);
|
||||
return [...lead, ...mine, ...lib, ...rest];
|
||||
}
|
||||
const initials = n => esc(String(n).replace(/[^\p{L}\p{N}\s]/gu, '').split(/\s+/).filter(Boolean).slice(0,2).map(x => x[0]).join('').toUpperCase());
|
||||
function setImg(el, src, name){
|
||||
el.innerHTML = `<i>${initials(name)}</i>`;
|
||||
if (!src) return;
|
||||
const im = new Image(); im.onload = () => { el.style.backgroundImage = `url('${src}')`; el.innerHTML = ''; }; im.src = src;
|
||||
}
|
||||
|
||||
function lrender(){
|
||||
const has = !!L.info;
|
||||
$('#lvEmpty').classList.toggle('hidden', has); $('#lvBody').classList.toggle('hidden', !has);
|
||||
lfooter();
|
||||
if (!has) { $('#lside').innerHTML = '<p class="lnote">Select a tile to change it.</p>'; return; }
|
||||
$('#lvWarn').innerHTML = (L.info.warnings || []).map(w => `<div class="lwarn">${esc(w)}</div>`).join('');
|
||||
document.querySelectorAll('.ltab').forEach(b => b.setAttribute('aria-pressed', b.dataset.w === L.w));
|
||||
$('#lcG').textContent = lgroups('games').reduce((n,g) => n + g.list.length, 0);
|
||||
$('#lcM').textContent = lgroups('media').reduce((n,g) => n + g.list.length, 0);
|
||||
$('#lcH').textContent = lgroups('hidden')[0].list.length;
|
||||
$('#lsorts').classList.toggle('hidden', !L.info.canOrder || L.w === 'hidden');
|
||||
// strip
|
||||
const gs = lgroups(L.w);
|
||||
const strip = $('#lstrip');
|
||||
if (!gs.some(g => g.list.length)) strip.innerHTML = `<div class="lempty">${L.w === 'hidden' ? 'Nothing is hidden. Select a tile and choose Hidden to take it off the home screen.' : 'No tiles here.'}</div>`;
|
||||
else {
|
||||
strip.innerHTML = gs.filter(g => g.list.length).map(g => `<div class="lgrp"><span>${g.label}</span><div class="lcards">${g.list.map(t =>
|
||||
`<button class="lcard" data-id="${t.id}" data-g="${g.key}" draggable="${g.key === 'mine' && L.info.canOrder}" ${t.id === L.sel ? 'aria-current="true"' : ''}>
|
||||
<div class="im" data-src="${esc(limg(t.icon))}" data-n="${esc(t.name)}"></div>${t.changed ? '<span class="bd">Edited</span>' : ''}
|
||||
<div class="nm" title="${esc(t.name)}">${esc(t.name)}</div></button>`).join('')}</div></div>`).join('');
|
||||
strip.querySelectorAll('.im').forEach(el => setImg(el, el.dataset.src, el.dataset.n));
|
||||
strip.querySelector('[aria-current="true"]')?.scrollIntoView({block:'nearest', inline:'nearest'});
|
||||
}
|
||||
// preview
|
||||
const pw = L.w === 'hidden' ? 'games' : L.w;
|
||||
document.querySelectorAll('.ltabs span').forEach(s => s.classList.toggle('on', s.dataset.w === pw));
|
||||
const row = lrowFor(pw);
|
||||
if (L.sel) { const i = row.findIndex(t => t.id === L.sel); if (i >= 0) L.focus = i; }
|
||||
L.focus = Math.max(0, Math.min(L.focus, row.length - 1));
|
||||
$('#lrow').innerHTML = row.slice(0, 16).map((t,i) => `<div class="ltile ${i === L.focus ? 'sel' : ''}" data-id="${t.id}" data-src="${esc(limg(t.icon))}" data-n="${esc(t.name)}"></div>`).join('');
|
||||
$('#lrow').querySelectorAll('.ltile').forEach(el => setImg(el, el.dataset.src, el.dataset.n));
|
||||
const f = row[L.focus];
|
||||
$('#ltitle').textContent = f ? f.name : 'Nothing on this tab';
|
||||
$('#lsub').textContent = f && f.kind === 'system' ? 'System' : '';
|
||||
const bg = $('#lbg');
|
||||
if (f && f.bg) { bg.onload = () => bg.classList.remove('hidden'); bg.onerror = () => bg.classList.add('hidden'); bg.src = limg(f.bg); }
|
||||
else bg.classList.add('hidden');
|
||||
lside();
|
||||
}
|
||||
|
||||
function lside(){
|
||||
const box = $('#lside'), t0 = L.sel && lbyId(L.sel);
|
||||
if (!t0) { box.innerHTML = '<p class="lnote">Select a tile to change it.</p>'; return; }
|
||||
const t = leff(t0), e = L.edits[t.id] || {};
|
||||
const art = st.apps.find(a => a.title_id === t.id && a.editable);
|
||||
box.innerHTML = `<div><h2>${esc(t.name)}</h2><div class="id">${esc(t.id)}${t.kind === 'system' ? ' · system tile' : ''}</div></div>
|
||||
<div class="lsec"><span class="lbl">Shows on</span><div class="lseg">${['games','media','hidden'].map(v =>
|
||||
`<button data-where="${v}" aria-pressed="${t.where === v}">${v[0].toUpperCase() + v.slice(1)}</button>`).join('')}</div></div>
|
||||
<div class="lsec"><label for="lname">Name on the home screen</label><input class="ltxt" id="lname" value="${esc(t.name)}" maxlength="80">
|
||||
${e.name != null ? '<button class="linker" id="lname0">Use original name</button>' : ''}</div>
|
||||
${art ? '<div class="lsec"><span class="lbl">Icon and background</span><button class="btn" id="lart">Edit art</button></div>' : ''}
|
||||
${t.changed ? '<button class="linker" id="lundo" style="color:var(--bad)">Undo changes to this tile</button>' : ''}`;
|
||||
}
|
||||
|
||||
function lfooter(){
|
||||
const n = lchanges(), p = $('#lpend');
|
||||
p.classList.toggle('has', n > 0);
|
||||
p.querySelector('span').textContent = n ? `${n} unsaved change${n > 1 ? 's' : ''}` : 'No changes';
|
||||
$('#lApply').disabled = !n || !L.info; $('#lDiscard').disabled = !n;
|
||||
['#lPresets','#lReload'].forEach(s => $(s).disabled = !L.info);
|
||||
}
|
||||
|
||||
function lsetEdit(id, key, val){
|
||||
const t = lbyId(id), e = L.edits[id] ||= {};
|
||||
if (val === t[key] || val === '' || val == null) delete e[key]; else e[key] = val;
|
||||
if (!Object.keys(e).length) delete L.edits[id];
|
||||
lrender();
|
||||
}
|
||||
function lreset(){
|
||||
L.order = ltiles().filter(t => t.kind !== 'system').sort((a,b) => b.access - a.access).map(t => t.id);
|
||||
L.base = [...L.order]; L.edits = {}; L.dragged = false; $('#llock').checked = false;
|
||||
}
|
||||
|
||||
function busyv(on, t){ $('#busyv').classList.toggle('open', on); if (t) $('#busyT').textContent = t; }
|
||||
function dlg(html){ $('#dlgBody').innerHTML = html; $('#dlg').classList.add('open'); }
|
||||
function dlgClose(){ $('#dlg').classList.remove('open'); }
|
||||
$('#dlg').addEventListener('click', e => { if (e.target.id === 'dlg' || e.target.closest('[data-close]')) dlgClose(); });
|
||||
|
||||
async function lload(){
|
||||
busyv(true, 'Reading your home screen…');
|
||||
try { L.info = await api('/api/layout/load', {method:'POST', body: JSON.stringify({})}); lreset(); L.loaded = true; }
|
||||
catch (err) { L.info = null; $('#lvEmpty').innerHTML = `<h1>Couldn't read the home screen</h1><p>${esc(err.message)}</p>`; }
|
||||
busyv(false); lrender();
|
||||
}
|
||||
|
||||
// views
|
||||
function setView(v){
|
||||
document.querySelectorAll('.views button').forEach(b => b.setAttribute('aria-pressed', b.dataset.v === v));
|
||||
document.querySelector('.layout').classList.toggle('hidden', v !== 'art');
|
||||
$('#lv').classList.toggle('hidden', v !== 'layout');
|
||||
if (v === 'layout' && !L.loaded && $('#dot').classList.contains('ok')) lload();
|
||||
lrender();
|
||||
}
|
||||
document.querySelectorAll('.views button').forEach(b => b.onclick = () => setView(b.dataset.v));
|
||||
|
||||
// interactions
|
||||
document.querySelectorAll('.ltab').forEach(b => b.onclick = () => { L.w = b.dataset.w; L.focus = 0; lrender(); });
|
||||
document.querySelectorAll('.ltabs span').forEach(s => s.onclick = () => { L.w = s.dataset.w; L.focus = 0; L.sel = null; lrender(); });
|
||||
$('#lstrip').addEventListener('click', e => { const c = e.target.closest('.lcard'); if (c) { L.sel = c.dataset.id; lrender(); } });
|
||||
$('#lrow').addEventListener('click', e => { const c = e.target.closest('.ltile'); if (c) { L.sel = c.dataset.id; lrender(); } });
|
||||
document.addEventListener('keydown', e => {
|
||||
if ($('#lv').classList.contains('hidden') || !L.info || /INPUT|TEXTAREA/.test(document.activeElement.tagName) || $('#dlg').classList.contains('open')) return;
|
||||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||||
const row = lrowFor(L.w === 'hidden' ? 'games' : L.w); if (!row.length) return;
|
||||
L.focus = Math.max(0, Math.min(row.length - 1, L.focus + (e.key === 'ArrowRight' ? 1 : -1)));
|
||||
L.sel = row[L.focus].id; lrender(); e.preventDefault();
|
||||
});
|
||||
$('#lside').addEventListener('click', e => {
|
||||
const id = L.sel; if (!id) return;
|
||||
const w = e.target.closest('[data-where]'); if (w) return lsetEdit(id, 'where', w.dataset.where);
|
||||
if (e.target.closest('#lname0')) return lsetEdit(id, 'name', null);
|
||||
if (e.target.closest('#lundo')) { delete L.edits[id]; return lrender(); }
|
||||
if (e.target.closest('#lart')) {
|
||||
setView('art');
|
||||
const btn = [...document.querySelectorAll('.app')].find(b => b.querySelector('.i').textContent.startsWith(id));
|
||||
const a = st.apps.find(x => x.title_id === id);
|
||||
if (a && a.hidden && !st.showHidden) { st.showHidden = true; renderApps(); }
|
||||
const b2 = [...document.querySelectorAll('.app')].find(b => b.querySelector('.i').textContent.startsWith(id)) || btn;
|
||||
if (a && b2) select(a, b2);
|
||||
}
|
||||
});
|
||||
$('#lside').addEventListener('change', e => { if (e.target.id === 'lname') lsetEdit(L.sel, 'name', e.target.value.trim()); });
|
||||
$('#lside').addEventListener('keydown', e => { if (e.target.id === 'lname' && e.key === 'Enter') e.target.blur(); });
|
||||
|
||||
let ldrag = null;
|
||||
$('#lstrip').addEventListener('dragstart', e => { const c = e.target.closest('.lcard'); if (!c || c.dataset.g !== 'mine') return; ldrag = c.dataset.id; c.classList.add('drag'); e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', ''); });
|
||||
$('#lstrip').addEventListener('dragend', () => { ldrag = null; document.querySelectorAll('.lcard').forEach(c => c.classList.remove('drag','over')); });
|
||||
$('#lstrip').addEventListener('dragover', e => { const c = e.target.closest('.lcard'); if (!ldrag || !c || c.dataset.g !== 'mine') return; e.preventDefault(); document.querySelectorAll('.lcard.over').forEach(x => x.classList.remove('over')); c.classList.add('over'); });
|
||||
$('#lstrip').addEventListener('drop', e => {
|
||||
e.preventDefault(); const c = e.target.closest('.lcard'); if (!ldrag || !c || c.dataset.g !== 'mine' || c.dataset.id === ldrag) return;
|
||||
L.order.splice(L.order.indexOf(ldrag), 1); L.order.splice(L.order.indexOf(c.dataset.id), 0, ldrag);
|
||||
L.dragged = true; L.sel = ldrag; lrender();
|
||||
});
|
||||
document.querySelectorAll('[data-sort]').forEach(b => b.onclick = () => {
|
||||
const k = b.dataset.sort;
|
||||
if (k === 'recent') { L.order = [...L.base]; L.dragged = false; return lrender(); }
|
||||
const key = id => leff(lbyId(id)).name.replace(/^[^\p{L}\p{N}]+/u, '').toLocaleLowerCase();
|
||||
L.order.sort((a,b) => key(a).localeCompare(key(b)) * (k === 'za' ? -1 : 1));
|
||||
L.dragged = true; lrender();
|
||||
});
|
||||
$('#lDiscard').onclick = () => { lreset(); lrender(); };
|
||||
$('#lReload').onclick = () => { if (lchanges() && !confirm('Reloading discards your unsaved changes. Continue?')) return; lload(); };
|
||||
|
||||
const presetData = () => ({edits: L.edits, order: L.order, dragged: L.dragged, lock: $('#llock').checked});
|
||||
function describe(e){
|
||||
const p = [];
|
||||
if (e.where) p.push(e.where === 'hidden' ? 'hide' : 'show on ' + e.where);
|
||||
if (e.name != null) p.push(`rename to “${e.name}”`);
|
||||
return p.join(', ');
|
||||
}
|
||||
$('#lApply').onclick = () => {
|
||||
const lines = Object.entries(L.edits).map(([id, e]) => `<div class="li"><div>${esc(lbyId(id).name)}<small>${esc(describe(e))}</small></div></div>`);
|
||||
if (L.dragged) lines.push(`<div class="li"><div>${$('#llock').checked ? 'Locked order' : 'New order'}<small>${esc(L.order.slice(0,6).map(id => leff(lbyId(id)).name).join(' → '))}${L.order.length > 6 ? ' …' : ''}</small></div></div>`);
|
||||
dlg(`<h3>Apply ${lchanges()} change${lchanges() > 1 ? 's' : ''} to your PS5?</h3>
|
||||
<p>PSGFX saves a backup of your current home screen first. Restart the PS5 afterwards to see the result.</p>
|
||||
${lines.join('')}
|
||||
<label class="chk"><input type="checkbox" id="dSave" checked> Also save this layout as a preset</label>
|
||||
<input class="ltxt" id="dName" value="${esc(L.lastPreset || 'My layout')}" maxlength="60" aria-label="Preset name">
|
||||
<p class="lnote" style="margin-top:6px">Re-apply it in one click after a firmware update or database rebuild resets your home screen.</p>
|
||||
<div class="acts"><button class="btn" data-close>Cancel</button><button class="btn primary" id="dGo">Apply changes</button></div>`);
|
||||
$('#dSave').onchange = e => $('#dName').disabled = !e.target.checked;
|
||||
$('#dGo').onclick = async () => {
|
||||
if ($('#dSave').checked) {
|
||||
const name = $('#dName').value.trim() || 'My layout';
|
||||
try { await api('/api/layout/preset/save', {method:'POST', body: JSON.stringify({name, data: presetData()})}); L.lastPreset = name; }
|
||||
catch (err) { if (!confirm(`Couldn't save the preset (${err.message}). Apply anyway?`)) return; }
|
||||
}
|
||||
dlgClose(); busyv(true, 'Backing up and applying…');
|
||||
const edits = {};
|
||||
for (const [id, e] of Object.entries(L.edits)) edits[id] = e;
|
||||
try {
|
||||
const j = await api('/api/layout/apply', {method:'POST', body: JSON.stringify({edits, recent: L.order, recentChanged: L.dragged, lock: $('#llock').checked})});
|
||||
L.info = j.layout; lreset(); lrender();
|
||||
dlg(`<h3>Changes applied</h3><p>Restart your PS5 to see the new home screen. If anything looks wrong, restore backup ${esc(j.backup)} from Backups.</p><pre>${esc(j.log.join('\n'))}</pre><div class="acts"><button class="btn primary" data-close>Done</button></div>`);
|
||||
} catch (err) {
|
||||
dlg(`<h3>Changes weren't applied</h3><p>${esc(err.message)}</p><div class="acts"><button class="btn primary" data-close>OK</button></div>`);
|
||||
}
|
||||
busyv(false);
|
||||
};
|
||||
};
|
||||
$('#lBackups').onclick = async () => {
|
||||
const j = await api('/api/layout/backups');
|
||||
dlg(`<h3>Home screen backups</h3><p>Saved in the "PSGFX Layout" folder next to PSGFX.exe, before every change, plus one of the very first home screen PSGFX read.</p>
|
||||
${j.backups.length ? j.backups.map(b => `<div class="li"><div>${esc(b.label)}<small>${esc(b.created)} · ${esc(b.ps5)}</small></div><button class="btn" data-restore="${esc(b.id)}" ${$('#dot').classList.contains('ok') ? '' : 'disabled'}>Restore</button></div>`).join('') : '<p class="lnote">No backups yet. One is made the first time you open Home layout.</p>'}
|
||||
<div class="acts"><button class="btn primary" data-close>Close</button></div>`);
|
||||
document.querySelectorAll('[data-restore]').forEach(b => b.onclick = async () => {
|
||||
if (!confirm('Upload this backup to your PS5? Your current home screen is replaced by it.')) return;
|
||||
dlgClose(); busyv(true, 'Restoring backup…');
|
||||
try { const r = await api('/api/layout/restore', {method:'POST', body: JSON.stringify({id: b.dataset.restore})}); L.info = r.layout; lreset(); lrender();
|
||||
dlg('<h3>Backup restored</h3><p>Restart your PS5 to load it.</p><div class="acts"><button class="btn primary" data-close>Done</button></div>'); }
|
||||
catch (err) { alert(err.message); }
|
||||
busyv(false);
|
||||
});
|
||||
};
|
||||
$('#lPresets').onclick = async () => {
|
||||
const j = await api('/api/layout/presets');
|
||||
dlg(`<h3>Layout presets</h3><p>Load one, check the preview, then Apply to PS5.</p>
|
||||
${j.presets.length ? j.presets.map(n => `<div class="li"><div>${esc(n)}</div><button class="btn" data-load="${esc(n)}">Load</button></div>`).join('') : '<p class="lnote">No presets yet. Tick "Also save this layout as a preset" when you apply.</p>'}
|
||||
<div class="acts"><button class="btn primary" data-close>Close</button></div>`);
|
||||
document.querySelectorAll('[data-load]').forEach(b => b.onclick = async () => {
|
||||
const p = (await api('/api/layout/preset/load', {method:'POST', body: JSON.stringify({name: b.dataset.load})})).data;
|
||||
lreset(); let n = 0;
|
||||
for (const [id, e] of Object.entries(p.edits || {})) if (lbyId(id)) { L.edits[id] = {...e}; n++; }
|
||||
if (p.dragged && p.order) { const known = p.order.filter(id => L.order.includes(id)); L.order = [...known, ...L.order.filter(id => !known.includes(id))]; L.dragged = true; }
|
||||
$('#llock').checked = !!p.lock; L.lastPreset = b.dataset.load;
|
||||
dlgClose(); lrender();
|
||||
dlg(`<h3>Preset loaded</h3><p>${n} tile${n === 1 ? '' : 's'} matched this console${p.dragged ? ', plus your order' : ''}. Check the preview, then Apply to PS5.</p><div class="acts"><button class="btn primary" data-close>OK</button></div>`);
|
||||
});
|
||||
};
|
||||
window.addEventListener('beforeunload', e => { if (lchanges()) { e.preventDefault(); e.returnValue = ''; } });
|
||||
|
||||
api('/api/config').then(j => { if (j.ip) { $('#ip').value = j.ip; $('#cf').requestSubmit(); } });
|
||||
</script>
|
||||
</body>
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
at9check
|
||||
at9check.exe
|
||||
__pycache__/
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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())
|
||||
@@ -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))
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate src/presets_embed.cpp from assets/presets/<App name>/<TITLE ID>/<n>.png (preset icons).
|
||||
Run from the repository root: python3 tools/embed_presets.py"""
|
||||
import os, re
|
||||
|
||||
root = "assets/presets"
|
||||
items = []
|
||||
for app in sorted(os.listdir(root)):
|
||||
for tid in sorted(os.listdir(os.path.join(root, app))):
|
||||
d = os.path.join(root, app, tid)
|
||||
if not os.path.isdir(d) or not re.fullmatch(r"[A-Z]{4}\d{5}", tid): continue
|
||||
names = sorted((n for n in os.listdir(d) if n.lower().endswith(".png")),
|
||||
key=lambda n: (int(m.group()) if (m := re.match(r"\d+", n)) else 1 << 30, n))
|
||||
for n in names: items.append((app, tid, os.path.join(d, n)))
|
||||
|
||||
out = ["// Generated by tools/embed_presets.py - do not edit.",
|
||||
"#include <cstddef>", '#include "presets.h"']
|
||||
for i, (_, _, path) in enumerate(items):
|
||||
data = open(path, "rb").read()
|
||||
out.append(f"static const unsigned char p{i}[] = {{")
|
||||
for j in range(0, len(data), 24):
|
||||
out.append(" " + ",".join(str(b) for b in data[j:j + 24]) + ",")
|
||||
out.append("};")
|
||||
out.append("extern const Preset PRESETS[] = {")
|
||||
for i, (app, tid, _) in enumerate(items):
|
||||
out.append(f' {{"{app}", "{tid}", p{i}, sizeof p{i}}},')
|
||||
out.append("};")
|
||||
out.append(f"extern const size_t PRESETS_COUNT = {len(items)};")
|
||||
open("src/presets_embed.cpp", "w").write("\n".join(out) + "\n")
|
||||
print(f"wrote src/presets_embed.cpp ({len(items)} icons)")
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""File-backed stand-in for the PS5 Upload app's local engine and the console behind it
|
||||
(development only), following the engine's POST /api/mgmt/call and the payload's runtime.c,
|
||||
register.c, mgmt_fs.c and shell builtins.
|
||||
Usage: python3 tools/mock_engine.py ROOT PORT (set MOCK_FW13=1 to mimic firmware 12/13 register behaviour,
|
||||
MOCK_NOT_PAIRED=1 for a console that hasn't accepted PS5 Upload)
|
||||
Paths map under ROOT. Writes are allowed under /data, /user and /mnt; reads also under /system*."""
|
||||
import base64, json, os, shutil, sys
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
ROOT = sys.argv[1]; PORT = int(sys.argv[2])
|
||||
WRITABLE = ("/data/", "/user/", "/mnt/")
|
||||
READABLE = WRITABLE + ("/system/", "/system_data/", "/system_ex/")
|
||||
|
||||
def P(p): return os.path.join(ROOT, p.lstrip("/"))
|
||||
def writable(p): return p.startswith(WRITABLE) and ".." not in p
|
||||
def readable(p, unsafe): return (p.startswith(READABLE if unsafe else WRITABLE)) and ".." not in p
|
||||
|
||||
class Refused(Exception): pass
|
||||
|
||||
def call(method, label, j):
|
||||
if method == 51: # app.list
|
||||
apps = []
|
||||
base = P("/user/app")
|
||||
for tid in sorted(os.listdir(base)) if os.path.isdir(base) else []:
|
||||
lnk = os.path.join(base, tid, "mount.lnk"); src = open(lnk).read() if os.path.exists(lnk) else ""
|
||||
name = tid
|
||||
pj = os.path.join(base, tid, "sce_sys", "param.json")
|
||||
if os.path.exists(pj):
|
||||
name = json.load(open(pj))["localizedParameters"]["en-US"]["titleName"]
|
||||
apps.append({"title_id": tid, "title_name": name, "src": src, "image_backed": False})
|
||||
return json.dumps({"apps": apps}).encode()
|
||||
if method == 56: # app.db_query - names from app.db (mocked by ROOT/appdb.json)
|
||||
dbp = os.path.join(ROOT, "appdb.json") # {"apps":[{"title_id":..,"app_id":..,"name":..}]}
|
||||
if os.environ.get("MOCK_NO_APPDB") or not os.path.exists(dbp): raise Refused("unsupported_in_mock")
|
||||
return open(dbp, "rb").read()
|
||||
if method == 38: # fs.read (the engine loops to the limit, capped at 2 MiB like LEGACY_READ_MAX)
|
||||
p = j.get("path", "")
|
||||
if not readable(p, j.get("unsafe", False)): raise Refused("fs_read_path_not_allowed")
|
||||
if not os.path.isfile(P(p)): raise Refused("fs_read_stat_failed")
|
||||
with open(P(p), "rb") as f: f.seek(j.get("offset", 0)); return f.read(min(j.get("limit", 2 << 20), 2 << 20))
|
||||
if method == 33: # fs.list, at most 256 a call
|
||||
p = j.get("path", "")
|
||||
if not os.path.isdir(P(p)): raise Refused("fs_list_dir_opendir_errno_2")
|
||||
names = sorted(os.listdir(P(p))); off = j.get("offset", 0); lim = min(j.get("limit", 256), 256)
|
||||
ents = [{"name": n, "kind": "dir" if os.path.isdir(os.path.join(P(p), n)) else "file",
|
||||
"size": os.path.getsize(os.path.join(P(p), n)), "mtime": 0} for n in names[off:off + lim]]
|
||||
return json.dumps({"path": p, "entries": ents, "returned": len(ents), "truncated": off + lim < len(names)}).encode()
|
||||
if method == 35: # fs.mkdir
|
||||
p = j.get("path", "")
|
||||
if not writable(p): raise Refused("path_unsafe")
|
||||
os.makedirs(P(p), exist_ok=True); return b""
|
||||
if method == 39: # fs.write: whole file, replaced atomically; the folder must exist
|
||||
p = j.get("path", "")
|
||||
if not writable(p): raise Refused("path_unsafe")
|
||||
data = base64.b64decode(j["bytes"])
|
||||
if len(data) > (16 << 20 if j.get("large") else 256 << 10): raise Refused("too_large")
|
||||
if not os.path.isdir(os.path.dirname(P(p))): raise Refused("open_failed")
|
||||
if j.get("mode") == "create" and os.path.exists(P(p)): raise Refused("exists")
|
||||
open(P(p) + ".tmp", "wb").write(data); os.replace(P(p) + ".tmp", P(p))
|
||||
print("WROTE", p, len(data), flush=True)
|
||||
return json.dumps({"ok": True, "size": len(data)}).encode()
|
||||
if method == 87: # shell.exec - only `cp SRC DST`, which (like the payload's) has no path policy
|
||||
a = j.get("cmd", "").split()
|
||||
if len(a) != 3 or a[0] != "cp": return json.dumps({"exit_code": 127, "timed_out": False, "stdout": "unsupported in mock\n"}).encode()
|
||||
if not os.path.isfile(P(a[1])): return json.dumps({"exit_code": 1, "timed_out": False, "stdout": "cp: %s: No such file or directory\n" % a[1]}).encode()
|
||||
with open(P(a[1]), "rb") as f, open(P(a[2]), "r+b" if os.path.exists(P(a[2])) else "wb") as g:
|
||||
g.truncate(0); g.write(f.read())
|
||||
print("CP", a[1], a[2], flush=True)
|
||||
return json.dumps({"exit_code": 0, "timed_out": False, "stdout": ""}).encode()
|
||||
if method == 48: # app.register - stage sce_sys like register.c
|
||||
src = j.get("src_path", "").rstrip("/")
|
||||
pj = json.load(open(P(src + "/sce_sys/param.json"))); tid = pj["titleId"]
|
||||
ua = P("/user/app/" + tid); meta = P("/user/appmeta/" + tid)
|
||||
os.makedirs(ua, exist_ok=True); os.makedirs(meta, exist_ok=True)
|
||||
shutil.copytree(P(src + "/sce_sys"), ua + "/sce_sys", dirs_exist_ok=True)
|
||||
if os.path.exists(P(src + "/sce_sys/icon0.png")): shutil.copyfile(P(src + "/sce_sys/icon0.png"), ua + "/icon0.png")
|
||||
for n in os.listdir(P(src + "/sce_sys")):
|
||||
if n == "param.json" or n.lower().endswith((".png", ".dds", ".at9")):
|
||||
shutil.copyfile(P(src + "/sce_sys/" + n), os.path.join(meta, n))
|
||||
open(ua + "/mount.lnk", "w").write(src)
|
||||
print("REGISTER", tid, "from", src, flush=True)
|
||||
if os.environ.get("MOCK_FW13"): raise Refused("register_install_api_unavailable")
|
||||
return json.dumps({"title_id": tid, "title_name": tid, "used_nullfs": True}).encode()
|
||||
raise Refused("unsupported_in_mock")
|
||||
|
||||
def job(op, j):
|
||||
if op == 1: # job.run DELETE
|
||||
p = j.get("path", "")
|
||||
if not writable(p): raise Refused("fs_delete_path_not_allowed")
|
||||
try: os.remove(P(p))
|
||||
except FileNotFoundError: raise Refused("fs_delete_failed")
|
||||
print("DELETED", p, flush=True)
|
||||
return json.dumps({"ok": True}).encode()
|
||||
raise Refused("unsupported_in_mock")
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a): pass
|
||||
def do_POST(self):
|
||||
if self.path != "/api/mgmt/call":
|
||||
self.send_response(404); self.end_headers(); return
|
||||
req = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||
label = req.get("label", "")
|
||||
try:
|
||||
if os.environ.get("MOCK_NOT_PAIRED"): raise Refused("not_paired")
|
||||
body = base64.b64decode(req.get("body_b64", ""))
|
||||
j = json.loads(body) if body[:1] == b"{" else {}
|
||||
out = call(req["method"], label, j) if req["op"] == "call" else job(req["job_op"], j)
|
||||
r = {"ok": True, "result": {"kind": "bytes", "body_b64": base64.b64encode(out).decode()}}
|
||||
except Refused as e:
|
||||
r = {"ok": False, "error": {"kind": "mgmt", "label": label, "status": 7, "cause": str(e)}}
|
||||
b = json.dumps(r).encode()
|
||||
self.send_response(200); self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
|
||||
|
||||
print("mock engine up", flush=True)
|
||||
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
|
||||
@@ -1,125 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""File-backed stand-in for PS5 Upload's payload (development only), following its runtime.c + register.c.
|
||||
Usage: python3 tools/mock_ps5.py ROOT MGMT_PORT XFER_PORT (set MOCK_FW13=1 to mimic firmware 12/13 register behaviour)
|
||||
Serves management (FTX2) and transfer frames on two ports; paths map under ROOT."""
|
||||
import base64, json, os, shutil, socket, struct, sys, threading
|
||||
|
||||
ROOT = sys.argv[1]; MPORT = int(sys.argv[2]); XPORT = int(sys.argv[3])
|
||||
ALLOWED = ("/data/", "/user/", "/mnt/")
|
||||
txs = {}
|
||||
|
||||
def P(p): return os.path.join(ROOT, p.lstrip("/"))
|
||||
def allowed(p): return p.startswith(ALLOWED) and ".." not in p
|
||||
|
||||
def recv_exact(s, n):
|
||||
b = b""
|
||||
while len(b) < n:
|
||||
c = s.recv(n - len(b))
|
||||
if not c: raise EOFError
|
||||
b += c
|
||||
return b
|
||||
|
||||
def send(s, t, body=b""):
|
||||
if isinstance(body, str): body = body.encode()
|
||||
s.sendall(struct.pack("<IHHIQQ", 0x32585446, 1, t, 0, len(body), 0) + body)
|
||||
|
||||
def err(s, m): send(s, 3, m)
|
||||
|
||||
def handle(s, t, body):
|
||||
j = {}
|
||||
if body[:1] == b"{":
|
||||
try: j = json.loads(body)
|
||||
except Exception: pass
|
||||
if t == 62: # APP_LIST_REGISTERED
|
||||
apps = []
|
||||
base = P("/user/app")
|
||||
for tid in sorted(os.listdir(base)) if os.path.isdir(base) else []:
|
||||
lnk = os.path.join(base, tid, "mount.lnk"); src = open(lnk).read() if os.path.exists(lnk) else ""
|
||||
name = tid
|
||||
pj = os.path.join(base, tid, "sce_sys", "param.json")
|
||||
if os.path.exists(pj):
|
||||
name = json.load(open(pj))["localizedParameters"]["en-US"]["titleName"]
|
||||
apps.append({"title_id": tid, "title_name": name, "src": src, "image_backed": False})
|
||||
return send(s, 63, json.dumps({"apps": apps}))
|
||||
if t == 120: # APPDB_QUERY - names from app.db (mocked by ROOT/appdb.json)
|
||||
dbp = os.path.join(ROOT, "appdb.json") # {"apps":[{"title_id":..,"app_id":..,"name":..}]}
|
||||
if os.environ.get("MOCK_NO_APPDB") or not os.path.exists(dbp): return err(s, "unsupported_in_mock")
|
||||
return send(s, 121, open(dbp).read())
|
||||
if t == 48: # FS_READ
|
||||
p = j.get("path", "")
|
||||
if not allowed(p): return err(s, "fs_read_path_not_allowed")
|
||||
if not os.path.isfile(P(p)): return err(s, "fs_read_stat_failed")
|
||||
off = j.get("offset", 0); lim = min(j.get("limit", 2 << 20) or (2 << 20), 2 << 20)
|
||||
with open(P(p), "rb") as f: f.seek(off); return send(s, 49, f.read(lim))
|
||||
if t == 36: # FS_LIST_DIR
|
||||
p = j.get("path", "")
|
||||
if not os.path.isdir(P(p)): return err(s, "fs_list_dir_opendir_errno_2")
|
||||
ents = [{"name": n, "kind": "dir" if os.path.isdir(os.path.join(P(p), n)) else "file",
|
||||
"size": os.path.getsize(os.path.join(P(p), n)), "mtime": 0} for n in sorted(os.listdir(P(p)))]
|
||||
return send(s, 37, json.dumps({"path": p, "entries": ents, "truncated": False}))
|
||||
if t == 50: # FS_COPY
|
||||
a, b = j.get("from", ""), j.get("to", "")
|
||||
if not (allowed(a) and allowed(b)): return err(s, "fs_copy_path_not_allowed")
|
||||
if not os.path.exists(P(a)): return err(s, "fs_copy_source_missing")
|
||||
ow = j.get("overwrite", 0)
|
||||
if os.path.exists(P(b)) and not (isinstance(ow, int) and not isinstance(ow, bool) and ow != 0): return err(s, "fs_copy_dest_exists")
|
||||
shutil.copyfile(P(a), P(b)); return send(s, 51)
|
||||
if t == 40: # FS_DELETE
|
||||
p = j.get("path", "")
|
||||
if not allowed(p): return err(s, "fs_delete_path_not_allowed")
|
||||
try: os.remove(P(p))
|
||||
except FileNotFoundError: return err(s, "fs_delete_failed")
|
||||
return send(s, 41)
|
||||
if t == 130: # FS_WRITE_BYTES
|
||||
p = j.get("path", "")
|
||||
if not allowed(p): return send(s, 131, '{"ok":false,"err":"path_unsafe"}')
|
||||
data = base64.b64decode(j["bytes"])
|
||||
open(P(p), "wb").write(data); return send(s, 131, '{"ok":true,"size":%d}' % len(data))
|
||||
if t == 56: # APP_REGISTER - stage sce_sys like register.c
|
||||
src = j.get("src_path", "").rstrip("/")
|
||||
pj = json.load(open(P(src + "/sce_sys/param.json"))); tid = pj["titleId"]
|
||||
ua = P("/user/app/" + tid); meta = P("/user/appmeta/" + tid)
|
||||
os.makedirs(ua, exist_ok=True); os.makedirs(meta, exist_ok=True)
|
||||
shutil.copytree(P(src + "/sce_sys"), ua + "/sce_sys", dirs_exist_ok=True)
|
||||
if os.path.exists(P(src + "/sce_sys/icon0.png")): shutil.copyfile(P(src + "/sce_sys/icon0.png"), ua + "/icon0.png")
|
||||
for n in os.listdir(P(src + "/sce_sys")):
|
||||
if n == "param.json" or n.lower().endswith((".png", ".dds", ".at9")):
|
||||
shutil.copyfile(P(src + "/sce_sys/" + n), os.path.join(meta, n))
|
||||
open(ua + "/mount.lnk", "w").write(src)
|
||||
print("REGISTER", tid, "from", src, flush=True)
|
||||
if os.environ.get("MOCK_FW13"): return err(s, "register_install_api_unavailable")
|
||||
return send(s, 57, json.dumps({"title_id": tid, "title_name": tid, "used_nullfs": True}))
|
||||
if t == 10: # BEGIN_TX
|
||||
tx = body[:16]; man = json.loads(body[24:])
|
||||
txs[tx] = {"dest": man["dest_root"], "data": b""}; return send(s, 11, '{"accepted":true,"last_acked_shard":0}')
|
||||
if t == 30: # STREAM_SHARD
|
||||
tx = body[:16]; txs[tx]["data"] += body[64:]
|
||||
return send(s, 31, tx + struct.pack("<Q", 1) + bytes([1]) + bytes(7) + struct.pack("<QQ", len(body) - 64, 1))
|
||||
if t == 14: # COMMIT_TX
|
||||
tx = body[:16]; d = txs.pop(tx)
|
||||
if not allowed(d["dest"]): return err(s, "path_not_allowed")
|
||||
os.makedirs(os.path.dirname(P(d["dest"])), exist_ok=True)
|
||||
open(P(d["dest"]), "wb").write(d["data"]); print("WROTE", d["dest"], len(d["data"]), flush=True)
|
||||
return send(s, 15, '{"committed":true}')
|
||||
return err(s, "unsupported_in_mock")
|
||||
|
||||
def serve_conn(s):
|
||||
try:
|
||||
while True:
|
||||
h = recv_exact(s, 28)
|
||||
magic, ver, t, flags, blen, trace = struct.unpack("<IHHIQQ", h)
|
||||
handle(s, t, recv_exact(s, blen) if blen else b"")
|
||||
except (EOFError, ConnectionResetError, BrokenPipeError):
|
||||
pass
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
def listen(port):
|
||||
ls = socket.socket(); ls.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
ls.bind(("127.0.0.1", port)); ls.listen(16)
|
||||
while True:
|
||||
c, _ = ls.accept(); threading.Thread(target=serve_conn, args=(c,), daemon=True).start()
|
||||
|
||||
threading.Thread(target=listen, args=(XPORT,), daemon=True).start()
|
||||
print("mock ps5 up", flush=True)
|
||||
listen(MPORT)
|
||||