feat: improve spektrafilm model accuracy

This commit is contained in:
zhoubinjia committed 2026-09-14 15:19:59 +08:00
1 parent a377781e9d
commit c7479060e8
72 files changed
+3360 -99738

No files matched your search

@@ -0,0 +1,5 @@
PhotonCamera native spectral model from Spektrafilm 0.3.4
Upstream: https://github.com/andreavolpato/spektrafilm/tree/3bb2c2d2801ff68b92019cf1dbcbb133d60832bc
Profiles and spectral data by Andrea Volpato and attributed contributors, CC BY-SA 4.0.
Source parameters stored as float64; shared half spectral grid stored losslessly as modular differences and byte planes.
No film/print RGB look LUTs are distributed; the native port generates the selected stages on demand.
@@ -0,0 +1,11 @@
Copyright 2013 Colour Developers
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,316 @@
{
"schemaVersion": 4,
"upstreamCommit": "3bb2c2d2801ff68b92019cf1dbcbb133d60832bc",
"upstreamVersion": "0.3.4",
"upstreamUrl": "https://github.com/andreavolpato/spektrafilm",
"encoding": "gzip-named-packed-le",
"runtimeAlgorithm": "spectral-v1",
"inputColorSpace": "ProPhoto RGB",
"outputColorSpace": "ProPhoto RGB",
"inputScale": 2.88,
"printInputScale": 1.5,
"lutSize": 65,
"lutMode": true,
"shared": {
"path": "model/shared.spkm",
"sha256": "25cfb67f8e9d36107fe0e72dffa2e5cc11d209f7fc16d023576defc4b21924cb",
"bytes": 2422200,
"uncompressedBytes": 5978445
},
"films": {
"fujifilm_c200": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/fujifilm_c200.spkm",
"sha256": "d4e7ef7d0af7754ee77221e3a6eff674e9823bb05e0c2080c667204583846c77",
"bytes": 13702,
"uncompressedBytes": 16556
}
},
"fujifilm_pro_400h": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/fujifilm_pro_400h.spkm",
"sha256": "4834bdf00008e584f3a2e267a3dc40a731f5daf39afecab91b37d21679c9f7db",
"bytes": 13664,
"uncompressedBytes": 16556
}
},
"fujifilm_provia_100f": {
"type": "positive",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/fujifilm_provia_100f.spkm",
"sha256": "38d4058e4eed31d03ab72df3e8b2412b936b7db4b182454a810d0a19aba47fd8",
"bytes": 13092,
"uncompressedBytes": 16010
}
},
"fujifilm_velvia_100": {
"type": "positive",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/fujifilm_velvia_100.spkm",
"sha256": "b8e5060532944c377cd638fdf2ca9dbb03119cdd2410a78621d0719f15dd8047",
"bytes": 12973,
"uncompressedBytes": 16010
}
},
"fujifilm_xtra_400": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/fujifilm_xtra_400.spkm",
"sha256": "341d8e6d76a33f2a26b43771f4080320f3c739e86da3328c3ada56dc9024cfad",
"bytes": 13741,
"uncompressedBytes": 16556
}
},
"kodak_ektachrome_100": {
"type": "positive",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_ektachrome_100.spkm",
"sha256": "00adceae8a1b205f134e13d358fe1ad28349bcaa7fb6e36b6c4c06899083fb6d",
"bytes": 13015,
"uncompressedBytes": 16010
}
},
"kodak_ektar_100": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_ektar_100.spkm",
"sha256": "245946ae79ffab00ed60edf5cbd466c765050fcffb3f7838f0c1f5770b48ca9f",
"bytes": 13638,
"uncompressedBytes": 16556
}
},
"kodak_gold_200": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_gold_200.spkm",
"sha256": "3c546d8dfd05a94b0799b8f98d30a744d4fb2279b595ed3695248942a15a4492",
"bytes": 13620,
"uncompressedBytes": 16556
}
},
"kodak_kodachrome_64": {
"type": "positive",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_kodachrome_64.spkm",
"sha256": "44df3fa97480e9a9cb07b03b8001eb56720a1c516f034a11b15aeebb7d359a99",
"bytes": 12818,
"uncompressedBytes": 16010
}
},
"kodak_portra_160": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_portra_160.spkm",
"sha256": "9d7669fd3991d6afc4142ea450ccff6b3a8234a3829451a7f897ffa03bd0bf2e",
"bytes": 13611,
"uncompressedBytes": 16556
}
},
"kodak_portra_400": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_portra_400.spkm",
"sha256": "0e647e105a7c81e05dfe558e2892b9c76d8dce5621cb4c898c44ddab7559e601",
"bytes": 13655,
"uncompressedBytes": 16556
}
},
"kodak_portra_800": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_portra_800.spkm",
"sha256": "f3542ea69dc4a61618aa20276c67093e38794b2a2f1222b82a10a0c9382fe2c4",
"bytes": 13655,
"uncompressedBytes": 16556
}
},
"kodak_portra_800_push1": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_portra_800_push1.spkm",
"sha256": "661a278825375a93b6194bf81484b7e675c57f834274eb098fc6cd582f9321d2",
"bytes": 13684,
"uncompressedBytes": 16556
}
},
"kodak_portra_800_push2": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_portra_800_push2.spkm",
"sha256": "0c3ab6f729bc2f6697902e10f7ad14c97a225d3c01c421debf938239d81d8354",
"bytes": 13694,
"uncompressedBytes": 16556
}
},
"kodak_ultramax_400": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_ultramax_400.spkm",
"sha256": "eeb9651c1e87bb93b9d3cfbc7f3cbb78cba2c110787f69727d51712bc6b1a74a",
"bytes": 13648,
"uncompressedBytes": 16556
}
},
"kodak_verita_200d": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_verita_200d.spkm",
"sha256": "e9e5af0b493452895913ef894b355ffc85f52016b431924175c9fa7dbd61789a",
"bytes": 13651,
"uncompressedBytes": 16556
}
},
"kodak_vision3_200t": {
"type": "negative",
"referenceIlluminant": "T",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_vision3_200t.spkm",
"sha256": "04c0920e64577173d07f19ddcd654803bbacd886718ddae5b43c8f71aa56295a",
"bytes": 13782,
"uncompressedBytes": 16556
}
},
"kodak_vision3_250d": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_vision3_250d.spkm",
"sha256": "32b7abf94b009c6a5b23b5c3e3f8ec8ad877683c4fdba845e8e7b117a9624d5a",
"bytes": 13829,
"uncompressedBytes": 16556
}
},
"kodak_vision3_500t": {
"type": "negative",
"referenceIlluminant": "T",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_vision3_500t.spkm",
"sha256": "0cec945418953e9e312a613c6f55a6cf8bdba0f756b5b418ab893dc5bc400e22",
"bytes": 13802,
"uncompressedBytes": 16556
}
},
"kodak_vision3_50d": {
"type": "negative",
"referenceIlluminant": "D55",
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_vision3_50d.spkm",
"sha256": "a0273756d668a64481fd20fb40e616a3b3044ed78e3b3d17012c5bc92def8f71",
"bytes": 13723,
"uncompressedBytes": 16556
}
}
},
"prints": {
"fujifilm_crystal_archive_typeii": {
"viewingIlluminant": "D50",
"model": {
"path": "model/fujifilm_crystal_archive_typeii.spkm",
"sha256": "372b253d1f6e7109808da0bdae920a2462dd0ca5e34a644f2d82661b24a3f9c9",
"bytes": 6188,
"uncompressedBytes": 8542
}
},
"kodak_2383": {
"viewingIlluminant": "K75P",
"model": {
"path": "model/kodak_2383.spkm",
"sha256": "c8c39fcba1e592b11b240e94e145067a801c0a38dbc798c91d92253b354b9407",
"bytes": 6426,
"uncompressedBytes": 8542
}
},
"kodak_2393": {
"viewingIlluminant": "K75P",
"model": {
"path": "model/kodak_2393.spkm",
"sha256": "332d778373f08d4a11e43e7a89be77542e93c25fe4c6f6ded09fc482eecace07",
"bytes": 6271,
"uncompressedBytes": 8542
}
},
"kodak_ektacolor_edge": {
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_ektacolor_edge.spkm",
"sha256": "f33d568b6e9cac7c8c7ca0e69187b61c882448f6af0fdb71d486805039ab4858",
"bytes": 6044,
"uncompressedBytes": 8542
}
},
"kodak_endura_premier": {
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_endura_premier.spkm",
"sha256": "aec10298877b80248e1e1686398c06963bcc63518603a17b3107fd1e5ab51506",
"bytes": 5989,
"uncompressedBytes": 8542
}
},
"kodak_portra_endura": {
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_portra_endura.spkm",
"sha256": "019c38eaa13b37f351923b802be5fc8ea9ca392eeea3a0440cbffe70f12306c8",
"bytes": 6085,
"uncompressedBytes": 8542
}
},
"kodak_supra_endura": {
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_supra_endura.spkm",
"sha256": "e894d2ddc1cf37e33090eb08446e935f469bc50b3ad91d1d1cfac7e5901c5d39",
"bytes": 6080,
"uncompressedBytes": 8542
}
},
"kodak_ultra_endura": {
"viewingIlluminant": "D50",
"model": {
"path": "model/kodak_ultra_endura.spkm",
"sha256": "fb0cb92259aae2552fc1a1f570a9d555ce8afe1601877fc5b163b8da4df7342b",
"bytes": 6050,
"uncompressedBytes": 8542
}
}
}
}
Binary file not shown.
@@ -1 +0,0 @@
{"version":1,"wavelengths":[380.0,385.0,390.0,395.0,400.0,405.0,410.0,415.0,420.0,425.0,430.0,435.0,440.0,445.0,450.0,455.0,460.0,465.0,470.0,475.0,480.0,485.0,490.0,495.0,500.0,505.0,510.0,515.0,520.0,525.0,530.0,535.0,540.0,545.0,550.0,555.0,560.0,565.0,570.0,575.0,580.0,585.0,590.0,595.0,600.0,605.0,610.0,615.0,620.0,625.0,630.0,635.0,640.0,645.0,650.0,655.0,660.0,665.0,670.0,675.0,680.0,685.0,690.0,695.0,700.0,705.0,710.0,715.0,720.0,725.0,730.0,735.0,740.0,745.0,750.0,755.0,760.0,765.0,770.0,775.0,780.0],"observerCmfs":[[0.001368,3.9e-05,0.00645],[0.002236,6.4e-05,0.01054999],[0.004243,0.00012,0.02005001],[0.00765,0.000217,0.03621],[0.01431,0.000396,0.06785001],[0.02319,0.00064,0.1102],[0.04351,0.00121,0.2074],[0.07763,0.00218,0.3713],[0.13438,0.004,0.6456],[0.21477,0.0073,1.0390501],[0.2839,0.0116,1.3856],[0.3285,0.01684,1.62296],[0.34828,0.023,1.74706],[0.34806,0.0298,1.7826],[0.3362,0.038,1.77211],[0.3187,0.048,1.7441],[0.2908,0.06,1.6692],[0.2511,0.0739,1.5281],[0.19536,0.09098,1.28764],[0.1421,0.1126,1.0419],[0.09564,0.13902,0.8129501],[0.05795001,0.1693,0.6162],[0.03201,0.20802,0.46518],[0.0147,0.2586,0.3533],[0.0049,0.323,0.272],[0.0024,0.4073,0.2123],[0.0093,0.503,0.1582],[0.0291,0.6082,0.1117],[0.06327,0.71,0.07824999],[0.1096,0.7932,0.05725001],[0.1655,0.862,0.04216],[0.2257499,0.9148501,0.02984],[0.2904,0.954,0.0203],[0.3597,0.9803,0.0134],[0.4334499,0.9949501,0.00875],[0.5120501,1.0,0.00575],[0.5945,0.995,0.0039],[0.6784,0.9786,0.00275],[0.7621,0.952,0.0021],[0.8425,0.9154,0.0018],[0.9163,0.87,0.00165],[0.9786,0.8163,0.0014],[1.0263,0.757,0.0011],[1.0567,0.6949,0.001],[1.0622,0.631,0.0008],[1.0456,0.5668,0.0006],[1.0026,0.503,0.00034],[0.9384,0.4412,0.00024],[0.8544499,0.381,0.00019],[0.7514,0.321,0.0001],[0.6424,0.265,5e-05],[0.5419,0.217,3e-05],[0.4479,0.175,2e-05],[0.3608,0.1382,1e-05],[0.2835,0.107,-0.0],[0.2187,0.0816,0.0],[0.1649,0.061,0.0],[0.1212,0.04458,0.0],[0.0874,0.032,0.0],[0.0636,0.0232,0.0],[0.04677,0.017,0.0],[0.0329,0.01192,0.0],[0.0227,0.00821,0.0],[0.01584,0.005723,0.0],[0.01135916,0.004102,0.0],[0.00811092,0.002929,0.0],[0.00579035,0.002091,0.0],[0.00410946,0.001484,0.0],[0.00289933,0.001047,0.0],[0.00204919,0.00074,0.0],[0.00143997,0.00052,0.0],[0.00099995,0.0003611,0.0],[0.00069008,0.0002492,0.0],[0.00047602,0.0001719,0.0],[0.0003323,0.00012,0.0],[0.00023483,8.48e-05,0.0],[0.00016615,6e-05,0.0],[0.00011741,4.24e-05,0.0],[8.308e-05,3e-05,0.0],[5.871e-05,2.12e-05,0.0],[4.151e-05,1.499e-05,0.0]],"viewingIlluminants":{"D50":[0.28500907,0.31632887,0.34766031,0.46076543,0.57388219,0.61580487,0.65773919,0.67822334,0.69871914,0.68582343,0.67292773,0.77189179,0.8708675,0.94315561,1.01544372,1.0350317,1.05460803,1.05900747,1.0634069,1.08517132,1.10694737,1.08863966,1.07033195,1.09221275,1.11410518,1.11928442,1.12445201,1.1274548,1.13045759,1.15937982,1.18830205,1.18048083,1.1726596,1.18174945,1.19083929,1.17736165,1.16387237,1.15069733,1.13751066,1.14440078,1.15127927,1.11973833,1.08820902,1.11258051,1.13696364,1.14615823,1.15536446,1.15403765,1.15272247,1.13340219,1.11408191,1.13233143,1.15056931,1.13200554,1.11344178,1.12812985,1.14280628,1.17082069,1.19882345,1.17630252,1.15378159,1.08539245,1.01700331,1.04157266,1.06615364,1.0736257,1.0811094,0.98780176,0.89448247,0.95068587,1.00687762,1.04220115,1.07751304,0.9940052,0.91049735,0.7909793,0.67146125,0.81828375,0.96511788,0.93806949,0.91100946],"K75P":[0.20035536,0.30265854,0.4125533,0.55894819,0.69999853,0.85021945,0.99679645,1.10301694,1.14838384,1.16645162,1.21798286,1.30628735,1.41536222,1.47612481,1.58182905,1.63745971,1.74179748,1.91913533,1.99687243,1.81801633,1.70329337,1.71461979,1.66576092,1.67921302,1.59913771,1.56892344,1.55055194,1.53716051,1.53142132,1.52091469,1.52091479,1.51068136,1.51028654,1.50169298,1.48617595,1.47399912,1.46516269,1.46200459,1.47894876,1.48395925,1.47913096,1.47172176,1.43576822,1.38536058,1.33877907,1.32256359,1.32292798,1.34166378,1.34867834,1.32678444,1.27598199,1.20316419,1.12475898,1.08245918,1.06773151,1.0412827,1.0496334,1.0495423,0.98574314,0.82143242,0.61655258,0.42885987,0.26509575,0.15523132,0.08982282,0.06249336,0.04571307,0.03847077,0.02714726,0.02576257,0.02350333,0.0213853,0.02095258,0.02241016,0.02179069,0.01802833,0.01590574,0.0268102,0.02732946,0.03086407,0.02568969]},"xyzToProPhoto":{"D50":[[1.34605116,-0.25549888,-0.05112002],[-0.54455372,1.50810289,0.02049794],[-1.05e-06,7e-08,1.21227471]],"K75P":[[1.39398641,-0.21427613,-0.10005299],[-0.53326684,1.49095608,0.0132944],[-0.00131311,-0.00372903,0.95086683]]},"films":{"fujifilm_c200":{"channelDensity":[[100.0,100.0,100.0],[0.21993411,0.06904575,0.197424],[0.18005467,0.06056765,0.2845401],[0.1417254,0.05080407,0.36881754],[0.10595972,0.04009277,0.45470649],[0.07340713,0.02908889,0.54561678],[0.04469805,0.01851432,0.64150849],[0.02051285,0.00884686,0.73986823],[0.00143889,0.00015216,0.83744987],[-0.01212942,-0.0078213,0.93072667],[-0.02013545,-0.01537526,1.01556781],[-0.02299449,-0.0225837,1.08729162],[-0.02153727,-0.029026Line truncated
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+17
View File
@@ -234,6 +234,12 @@ target_link_libraries(
)
add_library(my-native-lib SHARED
native-lib.cpp
spektrafilm/spectral_data.cpp
spektrafilm/spectral_filming.cpp
spektrafilm/spectral_gamut.cpp
spektrafilm/spectral_printing.cpp
spektrafilm/spectral_generator.cpp
spektrafilm/spectral_jni.cpp
gles_gpu_timer_query_jni.cpp
gles_hardware_buffer_jni.cpp
dng_hdrnet_pgtm_jni.cpp
@@ -264,6 +270,17 @@ add_library(my-native-lib SHARED
${ADOBE_DNG_SOURCES}
)
# Spectral curves/CAM16 and model validation require IEEE NaN/Inf semantics.
set_source_files_properties(
spektrafilm/spectral_data.cpp
spektrafilm/spectral_filming.cpp
spektrafilm/spectral_gamut.cpp
spektrafilm/spectral_printing.cpp
spektrafilm/spectral_generator.cpp
spektrafilm/spectral_jni.cpp
PROPERTIES COMPILE_OPTIONS "-fno-fast-math;-ffp-contract=off"
)
# Match the former Kotlin Float bilinear path exactly at Q8 rounding boundaries.
# This host-side scaler is deliberately independent of the MGC AOT/capsule sources.
set_source_files_properties(
@@ -0,0 +1,11 @@
Copyright 2013 Colour Developers
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,76 @@
#include "spectral_data.h"
#include <cmath>
#include <cstring>
#include <stdexcept>
namespace spektrafilm {
DataSet readDataSet(const uint8_t* bytes, size_t size) {
if (size < 12 || size > 64 * 1024 * 1024 || std::memcmp(bytes, "SPKDATA4", 8) != 0)
throw std::invalid_argument("Invalid Spektrafilm data header");
size_t offset = 8;
auto readU32 = [&]() -> uint32_t {
if (size - offset < 4) throw std::invalid_argument("Truncated spectral data");
uint32_t n = 0;
for (int b = 0; b < 4; ++b) n |= uint32_t(bytes[offset++]) << (b * 8);
return n;
};
const uint32_t fields = readU32();
if (fields == 0 || fields > 1024) throw std::invalid_argument("Invalid spectral tensor count");
DataSet result;
for (uint32_t i = 0; i < fields; ++i) {
const uint32_t keySize = readU32();
if (keySize == 0 || keySize > 256 || keySize > size - offset)
throw std::invalid_argument("Invalid spectral tensor key");
std::string key(reinterpret_cast<const char*>(bytes + offset), keySize);
offset += keySize;
const uint32_t encoding = readU32();
const uint32_t count = readU32();
if (count > 4 * 1024 * 1024)
throw std::invalid_argument("Invalid spectral tensor length");
std::vector<double> values;
if (encoding == 0) {
if (count > (size - offset) / 8) throw std::invalid_argument("Truncated spectral tensor");
values.resize(count);
for (double& v : values) {
uint64_t bits = 0;
for (int b = 0; b < 8; ++b) bits |= uint64_t(bytes[offset++]) << (b * 8);
std::memcpy(&v, &bits, 8);
if (!std::isfinite(v)) throw std::invalid_argument("Non-finite spectral tensor value");
}
} else if (encoding == 1) {
const uint32_t rows = readU32(), columns = readU32(), channels = readU32();
if (rows == 0 || columns == 0 || channels == 0 || rows > 4096 ||
columns > 4096 || channels > 4096 || uint64_t(rows) * columns * channels != count ||
count > (size - offset) / 2)
throw std::invalid_argument("Invalid packed spectral grid dimensions");
values.resize(count);
// Wavelength-major rows, then separate low/high byte planes. Restore
// half words modulo 65536 before any floating-point conversion.
size_t packed = 0;
for (uint32_t c = 0; c < channels; ++c) for (uint32_t r = 0; r < rows; ++r) {
uint16_t previous = 0;
for (uint32_t x = 0; x < columns; ++x, ++packed) {
const uint16_t difference = uint16_t(bytes[offset + packed]) |
(uint16_t(bytes[offset + count + packed]) << 8);
const uint16_t bits = uint16_t(previous + difference);
previous = bits;
const int exponent = (bits >> 10) & 31;
const int mantissa = bits & 1023;
if (exponent == 31) throw std::invalid_argument("Non-finite packed spectral value");
double value = exponent == 0 ? std::ldexp(double(mantissa), -24) :
std::ldexp(double(1024 + mantissa), exponent - 25);
if (bits & 0x8000) value = -value;
values[(size_t(r) * columns + x) * channels + c] = value;
}
}
offset += size_t(count) * 2;
} else {
throw std::invalid_argument("Unsupported spectral tensor encoding");
}
if (!result.emplace(std::move(key), std::move(values)).second)
throw std::invalid_argument("Duplicate spectral tensor key");
}
if (offset != size) throw std::invalid_argument("Excess spectral data payload");
return result;
}
}
@@ -0,0 +1,14 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <string>
#include <unordered_map>
#include <vector>
namespace spektrafilm {
using Vec3 = std::array<double, 3>;
using DataSet = std::unordered_map<std::string, std::vector<double>>;
DataSet readDataSet(const uint8_t* bytes, size_t size);
}
@@ -0,0 +1,302 @@
// Port of Spektrafilm 0.3.4 filming, Hanatos adaptation and DIR chemistry.
// Upstream commit 3bb2c2d2801ff68b92019cf1dbcbb133d60832bc; see LICENSE.spektrafilm.
#include "spectral_filming.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <stdexcept>
namespace spektrafilm {
namespace {
using Vec2 = std::array<double, 2>;
const std::vector<double>& data(const DataSet& set, const char* key, size_t size = 0) {
auto found = set.find(key);
if (found == set.end() || (size && found->second.size() != size))
throw std::invalid_argument(std::string("Invalid filming model tensor: ") + key);
for (double value : found->second)
if (!std::isfinite(value)) throw std::invalid_argument(std::string("Non-finite filming model: ") + key);
return found->second;
}
template<size_t N> std::array<double, N> fixed(const DataSet& set, const char* key) {
std::array<double, N> result{};
const auto& values = data(set, key, N);
std::copy(values.begin(), values.end(), result.begin());
return result;
}
Vec2 tri2quad(const Vec2& xy) {
double denominator = std::fmax(1.0 - xy[0], 1e-10);
return {std::clamp((1.0 - xy[0]) * (1.0 - xy[0]), 0.0, 1.0),
std::clamp(xy[1] / denominator, 0.0, 1.0)};
}
Vec2 quad2tri(const Vec2& tc) {
double root = std::sqrt(tc[0]);
return {1.0 - root, tc[1] * root};
}
Vec3 bilinear(const std::vector<double>& lut, int size, const Vec2& tc) {
double x = std::clamp(tc[0] * (size - 1), 0.0, double(size - 1));
double y = std::clamp(tc[1] * (size - 1), 0.0, double(size - 1));
int x0 = int(std::floor(x)), y0 = int(std::floor(y));
int x1 = std::min(x0 + 1, size - 1), y1 = std::min(y0 + 1, size - 1);
Vec3 out{};
for (int i = 0; i < 2; ++i) for (int j = 0; j < 2; ++j) {
double weight = (i ? x - x0 : 1.0 - (x - x0)) * (j ? y - y0 : 1.0 - (y - y0));
size_t offset = (size_t(i ? x1 : x0) * size + (j ? y1 : y0)) * 3;
for (int c = 0; c < 3; ++c) out[c] += weight * lut[offset + c];
}
return out;
}
double mitchell(double t) {
constexpr double B = 1.0 / 3.0, C = 1.0 / 3.0;
double x = std::abs(t);
if (x < 1.0) return ((12-9*B-6*C)*x*x*x + (-18+12*B+6*C)*x*x + (6-2*B)) / 6.0;
if (x < 2.0) return ((-B-6*C)*x*x*x + (6*B+30*C)*x*x + (-12*B-48*C)*x + (8*B+24*C)) / 6.0;
return 0.0;
}
int mirror(int index, int size) {
if (index < 0) return -index;
if (index >= size) return 2 * (size - 1) - index;
return index;
}
Vec3 cubic(const std::vector<double>& lut, int size, const Vec2& tc) {
double x = std::clamp(tc[0] * (size - 1), 0.0, double(size - 1));
double y = std::clamp(tc[1] * (size - 1), 0.0, double(size - 1));
int xb = std::min(int(std::floor(x)), size - 2), yb = std::min(int(std::floor(y)), size - 2);
double xf = x - xb, yf = y - yb;
Vec3 out{};
double weights = 0;
for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) {
double weight = mitchell(xf + 1 - i) * mitchell(yf + 1 - j);
weights += weight;
size_t offset = (size_t(mirror(xb - 1 + i, size)) * size + mirror(yb - 1 + j, size)) * 3;
for (int c = 0; c < 3; ++c) out[c] += weight * lut[offset + c];
}
if (weights != 0) for (double& value : out) value /= weights;
return out;
}
Vec2 compressXy(const Vec2& xy, const Vec2& white, const Vec3& knee, const std::vector<double>& locus) {
Vec2 delta{xy[0] - white[0], xy[1] - white[1]};
double distance = std::hypot(delta[0], delta[1]);
if (distance < 1e-9) return xy;
Vec2 direction{delta[0] / std::fmax(distance, 1e-12), delta[1] / std::fmax(distance, 1e-12)};
double boundary = std::numeric_limits<double>::infinity();
for (size_t k = 0; k + 3 < locus.size(); k += 2) {
double ex = locus[k+2]-locus[k], ey = locus[k+3]-locus[k+1];
double denominator = direction[0]*ey-direction[1]*ex;
if (std::abs(denominator) <= 1e-12) continue;
double ox = white[0]-locus[k], oy = white[1]-locus[k+1];
double t = (-ox*ey+oy*ex)/denominator;
double s = (-ox*direction[1]+oy*direction[0])/denominator;
if (t > 1e-9 && s >= 0 && s <= 1) boundary = std::min(boundary, t);
}
if (!std::isfinite(boundary)) throw std::runtime_error("Film gamut ray misses spectral locus");
double normalized = distance / std::fmax(boundary, 1e-12);
if (normalized > knee[0]) {
double scale = knee[1]-knee[0];
double n = (normalized-knee[0])/scale;
normalized = knee[0] + scale*n/std::pow(1.0+std::pow(n,knee[2]),1.0/knee[2]);
}
return {white[0]+direction[0]*normalized*boundary, white[1]+direction[1]*normalized*boundary};
}
double poly4(const Vec2& tc, const Vec2& center, const double* p) {
double x = tc[0]-center[0], y = tc[1]-center[1];
double x2=x*x, y2=y*y, x3=x2*x, y3=y2*y;
// The fitted constant is deliberately excluded to preserve the white anchor.
return p[1]*x+p[2]*y+p[3]*x2+p[4]*y2+p[5]*x*y+
p[6]*x3+p[7]*y3+p[8]*x2*y+p[9]*x*y2+
p[10]*x2*x2+p[11]*y2*y2+p[12]*x3*y+p[13]*x2*y2+p[14]*x*y3;
}
// NumPy interp's right-biased exact match and endpoint behavior.
double interp(double value, const std::vector<double>& x, const std::vector<double>& y, int channel) {
size_t n = x.size();
if (value <= x.front()) return y[channel];
if (value >= x.back()) return y[(n-1)*3+channel];
auto high = std::upper_bound(x.begin(), x.end(), value);
size_t low = size_t(high-x.begin()-1);
double dx=x[low+1]-x[low];
double t = (value-x[low]) * (dx != 0 ? 1.0/dx : 0.0);
return y[low*3+channel] + t*(y[(low+1)*3+channel]-y[low*3+channel]);
}
int reflectSpectral(int index, int size) {
while (index < 0 || index >= size) {
if (index < 0) index = -index - 1;
else index = 2 * size - index - 1;
}
return index;
}
} // namespace
Filming::Filming(const DataSet& shared, const DataSet& film) {
const auto shape = fixed<3>(shared, "hanatos_shape");
tcSize_ = int(shape[0]);
const int wavelengths = int(shape[2]);
if (tcSize_ < 2 || tcSize_ > 1024 || shape[1] != tcSize_ || shape[0] != tcSize_ ||
wavelengths < 2 || wavelengths > 1024 || shape[2] != wavelengths)
throw std::invalid_argument("Invalid Hanatos spectral basis dimensions");
const auto& basis = data(shared, "hanatos_basis", size_t(tcSize_)*tcSize_*wavelengths);
const auto& wl = data(shared, "wavelengths", wavelengths);
const auto& locus = data(shared, "spectral_locus_xy");
if (locus.size() < 8 || locus.size()%2) throw std::invalid_argument("Invalid spectral locus");
const auto& flags = data(film, "filming_flags", 6);
positive_ = flags[0] != 0;
dirActive_ = flags[4] != 0;
const auto& sensitivity = data(film, "filming_sensitivity", wavelengths*3);
const auto& illuminant = data(film, "filming_reference_illuminant", wavelengths);
const auto reference = fixed<2>(film, "filming_reference_xy");
const auto center = tri2quad(reference);
const auto& windowParams = data(film, "filming_window", 4);
const auto& surfaceParams = data(film, "filming_surface", 45);
const auto knee = fixed<3>(film, "filming_knee");
if (knee[0] < 0 || knee[0] >= 1 || knee[1] <= knee[0] || knee[2] <= 0)
throw std::invalid_argument("Invalid input gamut knee");
proPhotoMatrix_ = fixed<9>(film, "filming_prophoto_to_xyz");
srgbMatrix_ = fixed<9>(film, "filming_srgb_to_xyz");
dirMatrix_ = fixed<9>(film, "filming_dir_matrix");
gamma_ = fixed<3>(film, "filming_gamma");
for (double g : gamma_) if (g <= 0) throw std::invalid_argument("Invalid film curve gamma");
std::vector<double> response = sensitivity;
if (flags[1] != 0) {
if (windowParams[1] <= 0 || windowParams[3] <= 0) throw std::invalid_argument("Invalid film window sigma");
std::vector<double> window(wavelengths);
for (int w=0; w<wavelengths; ++w) {
double uv=0.5*(1+std::erf((wl[w]-windowParams[0])/(windowParams[1]*std::sqrt(2.0))));
double ir=0.5*(1-std::erf((wl[w]-windowParams[2])/(windowParams[3]*std::sqrt(2.0))));
window[w]=uv*ir;
}
for (int c=0; c<3; ++c) {
double numerator=0, denominator=0;
for (int w=0; w<wavelengths; ++w) {
numerator += sensitivity[w*3+c]*illuminant[w]*window[w];
denominator += sensitivity[w*3+c]*illuminant[w];
}
double normalization=numerator/denominator;
if (!std::isfinite(normalization) || normalization <= 0) throw std::invalid_argument("Invalid film window normalization");
for (int w=0; w<wavelengths; ++w) response[w*3+c] *= window[w]/normalization;
}
}
// scipy.ndimage.gaussian_filter(..., sigma=(0,0,sigma)) uses half-sample
// symmetric reflection and a four-sigma kernel on the spectral axis.
double sigma=flags[3];
if (sigma < 0 || sigma > 100) throw std::invalid_argument("Invalid spectral blur sigma");
int radius=int(4*sigma+0.5);
std::vector<double> kernel;
if (sigma > 0) {
kernel.resize(radius*2+1);
double sum=0;
for (int k=-radius; k<=radius; ++k) { kernel[k+radius]=std::exp(-0.5*k*k/(sigma*sigma)); sum+=kernel[k+radius]; }
for (double& v:kernel) v/=sum;
}
tcLut_.resize(size_t(tcSize_)*tcSize_*3);
for (int i=0; i<tcSize_; ++i) for (int j=0; j<tcSize_; ++j) {
size_t pixel=size_t(i)*tcSize_+j;
Vec3 raw{};
for (int w=0; w<wavelengths; ++w) {
double spectrum=basis[pixel*wavelengths+w];
if (sigma > 0) {
spectrum=0;
for (int k=-radius; k<=radius; ++k)
spectrum+=kernel[k+radius]*basis[pixel*wavelengths+reflectSpectral(w+k,wavelengths)];
}
for (int c=0; c<3; ++c) raw[c]+=spectrum*response[w*3+c];
}
Vec2 tc{double(i)/(tcSize_-1), double(j)/(tcSize_-1)};
for (int c=0; c<3; ++c) {
if (flags[2] != 0) {
double surface=poly4(tc,center,surfaceParams.data()+c*15);
surface/=std::sqrt(1+(surface/2)*(surface/2));
raw[c]*=std::exp2(surface);
}
tcLut_[pixel*3+c]=raw[c];
}
}
if (flags[5] != 0) {
std::vector<double> remapped(tcLut_.size());
for (int i=0; i<tcSize_; ++i) for (int j=0; j<tcSize_; ++j) {
Vec2 tc{double(i)/(tcSize_-1),double(j)/(tcSize_-1)};
Vec2 compressed=compressXy(quad2tri(tc),reference,knee,locus);
Vec3 value=bilinear(tcLut_,tcSize_,tri2quad(compressed));
for (int c=0; c<3; ++c) remapped[(size_t(i)*tcSize_+j)*3+c]=value[c];
}
tcLut_=std::move(remapped);
}
logExposure_=data(film,"filming_log_exposure");
if (logExposure_.size()<2 || !std::is_sorted(logExposure_.begin(),logExposure_.end()))
throw std::invalid_argument("Invalid film exposure axis");
originalCurves_=data(film,"filming_curves",logExposure_.size()*3);
normalizedCurves_=originalCurves_;
for (int c=0; c<3; ++c) {
curveMin_[c]=std::numeric_limits<double>::infinity();
curveMax_[c]=-std::numeric_limits<double>::infinity();
for (size_t k=0; k<logExposure_.size(); ++k) {
curveMin_[c]=std::min(curveMin_[c],originalCurves_[k*3+c]);
curveMax_[c]=std::max(curveMax_[c],originalCurves_[k*3+c]);
}
densityMax_[c]=curveMax_[c]-curveMin_[c];
for (size_t k=0; k<logExposure_.size(); ++k) normalizedCurves_[k*3+c]-=curveMin_[c];
}
if (dirActive_) {
beforeDirCurves_.resize(normalizedCurves_.size());
for (int receiver=0; receiver<3; ++receiver) {
std::vector<double> axis(logExposure_.size());
for (size_t k=0; k<axis.size(); ++k) {
double correction=0;
for (int donor=0; donor<3; ++donor) {
double silver=normalizedCurves_[k*3+donor];
if (positive_) silver=densityMax_[donor]-silver;
correction+=silver*dirMatrix_[donor*3+receiver];
}
axis[k]=logExposure_[k]-correction;
}
for (size_t k=0; k<axis.size(); ++k)
beforeDirCurves_[k*3+receiver]=interp(logExposure_[k],axis,normalizedCurves_,receiver);
}
}
}
Vec3 Filming::expose(const Vec3& rgb, const std::array<double,9>& matrix) const {
Vec3 xyz{};
for (int row=0; row<3; ++row) for (int c=0; c<3; ++c) xyz[row]+=matrix[row*3+c]*rgb[c];
double brightness=xyz[0]+xyz[1]+xyz[2];
Vec2 xy{xyz[0]/std::fmax(brightness,1e-10), xyz[1]/std::fmax(brightness,1e-10)};
Vec3 raw=cubic(tcLut_,tcSize_,tri2quad(xy));
for (double& value:raw) value*=brightness;
return raw;
}
Vec3 Filming::interpolate(const Vec3& logRaw,const std::vector<double>& curves) const {
Vec3 result{};
for (int c=0; c<3; ++c) result[c]=interp(logRaw[c]*gamma_[c],logExposure_,curves,c);
return result;
}
Vec3 Filming::develop(const Vec3& linearProPhoto) const {
Vec3 raw=expose(linearProPhoto,proPhotoMatrix_);
Vec3 logRaw{};
for (int c=0; c<3; ++c) logRaw[c]=std::log10(std::fmax(raw[c],0.0)+1e-10);
Vec3 density=interpolate(logRaw,normalizedCurves_);
if (!dirActive_) return density;
Vec3 silver=density;
if (positive_) for (int c=0; c<3; ++c) silver[c]=densityMax_[c]-silver[c];
for (int receiver=0; receiver<3; ++receiver)
for (int donor=0; donor<3; ++donor) logRaw[receiver]-=silver[donor]*dirMatrix_[donor*3+receiver];
return interpolate(logRaw,beforeDirCurves_);
}
Vec3 Filming::midgrayDensity() const {
Vec3 raw=expose({0.184,0.184,0.184},srgbMatrix_);
Vec3 logRaw{};
for (int c=0; c<3; ++c) logRaw[c]=std::log10(raw[c]+1e-10);
return interpolate(logRaw,originalCurves_);
}
} // namespace spektrafilm
@@ -0,0 +1,30 @@
#pragma once
#include "spectral_data.h"
namespace spektrafilm {
/** Deterministic upstream lut_mode filming, from linear ProPhoto RGB to CMY. */
class Filming {
public:
Filming(const DataSet& shared, const DataSet& film);
Vec3 develop(const Vec3& linearProPhoto) const;
// Upstream enlarger balance uses unnormalised stock curves, without DIR,
// and its default sRGB .184 reference rather than ProPhoto .184.
Vec3 midgrayDensity() const;
bool positive() const { return positive_; }
const Vec3& curveMin() const { return curveMin_; }
const Vec3& curveMax() const { return curveMax_; }
private:
Vec3 expose(const Vec3& rgb, const std::array<double, 9>& matrix) const;
Vec3 interpolate(const Vec3& logRaw, const std::vector<double>& curves) const;
int tcSize_ = 0;
bool positive_ = false;
bool dirActive_ = false;
Vec3 curveMin_{}, curveMax_{}, densityMax_{}, gamma_{};
std::array<double, 9> proPhotoMatrix_{}, srgbMatrix_{}, dirMatrix_{};
std::vector<double> tcLut_, logExposure_, originalCurves_, normalizedCurves_, beforeDirCurves_;
};
} // namespace spektrafilm
@@ -0,0 +1,242 @@
// Algorithm port of Spektrafilm 0.3.4 (3bb2c2d2801ff68b92019cf1dbcbb133d60832bc),
// utils/gamut_compression.py, and colour-science 0.4.7 CAM16 / CAM16-UCS.
// See the bundled Spektrafilm and colour-science license notices.
#include "spectral_gamut.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
namespace spektrafilm {
namespace {
using Matrix = std::array<Vec3, 3>;
constexpr double kPi = 3.141592653589793238462643383279502884;
constexpr int kLightnessCount = 64;
constexpr int kHueCount = 720;
constexpr int kBisections = 18;
// colour-science intentionally uses these published rounded ProPhoto
// matrices. Replacing XYZ-to-RGB with a new inverse changes the boundary.
constexpr Matrix kRgbToXyz{{{0.7977, 0.1352, 0.0313},
{0.2880, 0.7119, 0.0001},
{0.0, 0.0, 0.8249}}};
constexpr Matrix kXyzToRgb{{{1.3460, -0.2556, -0.0511},
{-0.5446, 1.5082, 0.0205},
{0.0, 0.0, 1.2123}}};
constexpr Matrix kCat16{{{0.401288, 0.650173, -0.051461},
{-0.250268, 1.204414, 0.045854},
{-0.002079, 0.048952, 0.953127}}};
constexpr Matrix kInverseCat16{{
{1.8620678550872327, -1.0112546305316843, 0.14918677544445175},
{0.3875265432361372, 0.6214474419314753, -0.00897398516761252},
{-0.01584149884933386, -0.03412293802851557, 1.0499644368778496}}};
Vec3 multiply(const Matrix& matrix, const Vec3& value) {
Vec3 out{};
for (int i = 0; i < 3; ++i) {
out[i] = matrix[i][0] * value[0] + matrix[i][1] * value[1] +
matrix[i][2] * value[2];
}
return out;
}
double signedPower(double value, double exponent) {
return std::copysign(std::pow(std::abs(value), exponent), value);
}
double safeDivide(double numerator, double denominator) {
// colour.algebra.sdiv's default "Ignore Zero Conversion" mode.
return denominator == 0.0 ? 0.0 : numerator / denominator;
}
double knee(double value, double threshold, double limit, double power) {
if (value <= threshold) return value;
const double scale = limit - threshold;
const double x = (value - threshold) / scale;
return threshold + scale * x / std::pow(1.0 + std::pow(x, power), 1.0 / power);
}
struct Cam16 {
double fl;
double nbb;
double z;
double aw;
double chromaFactor;
double flQuarter;
Vec3 adaptation;
Cam16() {
constexpr double adaptingLuminance = 64.0;
constexpr double backgroundRatio = 20.0 / 100.0;
const double k = 1.0 / (5.0 * adaptingLuminance + 1.0);
const double k4 = std::pow(k, 4.0);
fl = 0.2 * k4 * 5.0 * adaptingLuminance +
0.1 * std::pow(1.0 - k4, 2.0) * std::cbrt(5.0 * adaptingLuminance);
flQuarter = std::pow(fl, 0.25);
nbb = 0.725 * std::pow(1.0 / backgroundRatio, 0.2);
z = 1.48 + std::sqrt(backgroundRatio);
chromaFactor = std::pow(1.64 - std::pow(0.29, backgroundRatio), 0.73);
const double d = std::clamp(1.0 - std::exp((-adaptingLuminance - 42.0) / 92.0) / 3.6, 0.0, 1.0);
// CAM16-UCS wrappers multiply normalized XYZ and its white by 100;
// Y_b remains 20. Using a Y=1 white directly inside CAM16 is wrong.
const Vec3 white{100.0 * 0.3457 / 0.3585, 100.0,
100.0 * (1.0 - 0.3457 - 0.3585) / 0.3585};
const Vec3 rgbWhite = multiply(kCat16, white);
Vec3 response{};
for (int i = 0; i < 3; ++i) {
adaptation[i] = d * 100.0 / rgbWhite[i] + 1.0 - d;
response[i] = compressResponse(adaptation[i] * rgbWhite[i]);
}
aw = achromatic(response);
}
double compressResponse(double value) const {
const double f = std::pow(fl * std::abs(value) / 100.0, 0.42);
return 400.0 * std::copysign(f, value) / (27.13 + f) + 0.1;
}
double expandResponse(double value) const {
const double shifted = value - 0.1;
const double magnitude = std::abs(shifted);
return std::copysign(1.0, shifted) * 100.0 / fl *
signedPower(27.13 * magnitude / (400.0 - magnitude), 1.0 / 0.42);
}
double achromatic(const Vec3& response) const {
return (2.0 * response[0] + response[1] + response[2] / 20.0 - 0.305) * nbb;
}
Vec3 forward(const Vec3& xyz) const {
Vec3 response = multiply(kCat16, xyz);
for (int i = 0; i < 3; ++i) response[i] = compressResponse(response[i] * 100.0 * adaptation[i]);
const double a = response[0] - 12.0 * response[1] / 11.0 + response[2] / 11.0;
const double b = (response[0] + response[1] - 2.0 * response[2]) / 9.0;
const double h = std::atan2(b, a);
const double et = (std::cos(h + 2.0) + 3.8) / 4.0;
const double j = 100.0 * signedPower(achromatic(response) / aw, 0.69 * z);
const double t = (50000.0 / 13.0) * nbb * safeDivide(
et * std::sqrt(a * a + b * b), response[0] + response[1] + 21.0 * response[2] / 20.0);
const double c = signedPower(t, 0.9) * signedPower(j / 100.0, 0.5) * chromaFactor;
const double m = c * flQuarter;
const double mp = std::log1p(0.0228 * m) / 0.0228;
return {1.7 * j / (1.0 + 0.007 * j), mp * std::cos(h), mp * std::sin(h)};
}
Vec3 inverse(const Vec3& jab) const {
const double j = jab[0] / (1.7 - 0.007 * jab[0]);
const double mp = std::hypot(jab[1], jab[2]);
const double m = std::expm1(0.0228 * mp) / 0.0228;
const double c = m / flQuarter;
const double h = std::atan2(jab[2], jab[1]);
const double sh = std::sin(h);
const double ch = std::cos(h);
const double t = signedPower(c / (std::sqrt(std::max(j, std::numeric_limits<double>::epsilon()) / 100.0) * chromaFactor), 1.0 / 0.9);
const double et = (std::cos(h + 2.0) + 3.8) / 4.0;
const double ach = aw * signedPower(j / 100.0, 1.0 / (0.69 * z));
const double p1 = safeDivide((50000.0 / 13.0) * nbb * et, t);
const double p2 = ach / nbb + 0.305;
constexpr double p3 = 21.0 / 20.0;
const double n = p2 * (2.0 + p3) * (460.0 / 1403.0);
double a = 0.0;
double b = 0.0;
if (t != 0.0) {
if (std::abs(sh) >= std::abs(ch)) {
b = n / (p1 / sh + (2.0 + p3) * (220.0 / 1403.0) * ch / sh -
27.0 / 1403.0 + p3 * (6300.0 / 1403.0));
a = b * ch / sh;
} else if (std::abs(sh) < std::abs(ch)) {
a = n / (p1 / ch + (2.0 + p3) * (220.0 / 1403.0) -
(27.0 / 1403.0 - p3 * (6300.0 / 1403.0)) * sh / ch);
b = a * sh / ch;
}
}
Vec3 response{(460.0 * p2 + 451.0 * a + 288.0 * b) / 1403.0,
(460.0 * p2 - 891.0 * a - 261.0 * b) / 1403.0,
(460.0 * p2 - 220.0 * a - 6300.0 * b) / 1403.0};
for (int i = 0; i < 3; ++i) response[i] = expandResponse(response[i]) / adaptation[i];
Vec3 xyz = multiply(kInverseCat16, response);
for (double& component : xyz) component /= 100.0;
return xyz;
}
};
struct GamutBoundary {
Cam16 cam;
std::vector<double> cmax;
double whiteJp;
// Match numpy.linspace's step followed by h_grid[1]-h_grid[0].
double hueStep = (-kPi + 2.0 * kPi / kHueCount) - (-kPi);
GamutBoundary() : cmax(kLightnessCount * kHueCount) {
const Vec3 white{0.3457 / 0.3585, 1.0, (1.0 - 0.3457 - 0.3585) / 0.3585};
whiteJp = cam.forward(white)[0];
for (int l = 0; l < kLightnessCount; ++l) {
const double lightness = 1.0 + l * (109.0 / (kLightnessCount - 1));
for (int h = 0; h < kHueCount; ++h) {
const double hue = -kPi + h * (2.0 * kPi / kHueCount);
const double ch = std::cos(hue);
const double sh = std::sin(hue);
double lo = 0.0;
double hi = 150.0;
for (int iteration = 0; iteration < kBisections; ++iteration) {
const double mid = (lo + hi) * 0.5;
const Vec3 rgb = multiply(kXyzToRgb, cam.inverse({lightness, mid * ch, mid * sh}));
const bool inside = std::all_of(rgb.begin(), rgb.end(), [](double v) {
return v >= -1e-6 && v <= 1.0 + 1e-6;
});
if (inside) lo = mid; else hi = mid;
}
cmax[l * kHueCount + h] = lo;
}
}
}
double lookup(double lightness, double hue) const {
const double li = (std::clamp(lightness, 1.0, 110.0) - 1.0) / 109.0 * (kLightnessCount - 1);
const int l0 = std::clamp(static_cast<int>(std::floor(li)), 0, kLightnessCount - 2);
const double lf = li - l0;
const double hi = (hue + kPi) / hueStep;
const int floorHue = static_cast<int>(std::floor(hi));
const int h0 = (floorHue % kHueCount + kHueCount) % kHueCount;
const int h1 = (h0 + 1) % kHueCount;
const double hf = hi - std::floor(hi);
return cmax[l0 * kHueCount + h0] * (1.0 - lf) * (1.0 - hf) +
cmax[l0 * kHueCount + h1] * (1.0 - lf) * hf +
cmax[(l0 + 1) * kHueCount + h0] * lf * (1.0 - hf) +
cmax[(l0 + 1) * kHueCount + h1] * lf * hf;
}
};
const GamutBoundary& boundary() {
// C++11 initialization is thread-safe. All subsequent operations are read-only.
static const GamutBoundary instance;
return instance;
}
} // namespace
OutputGamut::OutputGamut() { (void) boundary(); }
Vec3 OutputGamut::compress(const Vec3& linearProPhoto) const {
const GamutBoundary& state = boundary();
Vec3 jab = state.cam.forward(multiply(kRgbToXyz, linearProPhoto));
jab[0] = knee(jab[0] / state.whiteJp, 0.7, 1.0, 2.2) * state.whiteJp;
const double chroma = std::hypot(jab[1], jab[2]);
const double hue = std::atan2(jab[2], jab[1]);
// Extreme ProPhoto primaries can have undefined CAM16 chroma. Upstream
// propagates it through Cmax and the knee; inverse CAM16's two masked
// hue branches then leave opponent a/b at zero. Preserve that result
// without NumPy's intermediate NaN-to-integer table-coordinate cast.
if (!std::isfinite(hue) || !std::isfinite(jab[0])) {
const double invalid = std::numeric_limits<double>::quiet_NaN();
return multiply(kXyzToRgb, state.cam.inverse({jab[0], invalid, invalid}));
}
const double maxChroma = std::fmax(state.lookup(jab[0], hue), 1e-9);
const double newChroma = knee(chroma / maxChroma, 0.0, 1.0, 6.0) * maxChroma;
jab[1] = newChroma * std::cos(hue);
jab[2] = newChroma * std::sin(hue);
return multiply(kXyzToRgb, state.cam.inverse(jab));
}
} // namespace spektrafilm
@@ -0,0 +1,16 @@
#pragma once
#include "spectral_data.h"
namespace spektrafilm {
// Spektrafilm 0.3.4's default output gamut compressor, fixed to linear
// ProPhoto RGB. The shared 64 x 720 chroma boundary is generated from the
// CAM16 inverse on first use; it is not a pre-baked colour transform.
class OutputGamut {
public:
OutputGamut();
Vec3 compress(const Vec3& linearProPhoto) const;
};
} // namespace spektrafilm
@@ -0,0 +1,78 @@
#include "spectral_generator.h"
#include <algorithm>
#include <cmath>
#include <exception>
#include <mutex>
#include <stdexcept>
namespace spektrafilm {
namespace {
Vec3 linearInput(int r, int g, int b, int size) {
// Match the upstream baker's explicit float32 input conversion.
return {static_cast<float>(2.88 * proPhotoDecode(double(r) / (size - 1))),
static_cast<float>(2.88 * proPhotoDecode(double(g) / (size - 1))),
static_cast<float>(2.88 * proPhotoDecode(double(b) / (size - 1)))};
}
template<typename F> std::vector<float> generate(int size, const F& evaluate) {
if (size != 65) throw std::invalid_argument("Unsupported spectral lattice size");
std::vector<float> result(size * size * size * 4);
std::exception_ptr failure;
std::mutex failureMutex;
// Bounded workers; never occupy every camera/preview thread to generate a table.
#pragma omp parallel for num_threads(2) schedule(static)
for (int b = 0; b < size; ++b) {
try {
for (int g = 0; g < size; ++g) for (int r = 0; r < size; ++r) {
const Vec3 value = evaluate(r, g, b);
const size_t offset = ((b * size + g) * size + r) * 4;
for (int c = 0; c < 3; ++c) {
if (!std::isfinite(value[c])) throw std::runtime_error("Non-finite spectral LUT output");
result[offset + c] = static_cast<float>(std::clamp(value[c], 0.0, 1.0));
}
result[offset + 3] = 1;
}
} catch (...) {
std::lock_guard<std::mutex> lock(failureMutex);
if (!failure) failure = std::current_exception();
}
}
if (failure) std::rethrow_exception(failure);
return result;
}
}
DensityWire measureDensityWire(const Filming& film) {
DensityWire wire{{-0.2, -0.2, -0.2}, {0, 0, 0}};
for (int b = 0; b < 9; ++b) for (int g = 0; g < 9; ++g) for (int r = 0; r < 9; ++r) {
const Vec3 density = film.develop(linearInput(r, g, b, 9));
for (int c = 0; c < 3; ++c) wire.maximum[c] = std::max(wire.maximum[c], density[c]);
}
for (double& v : wire.maximum) {
v = std::ceil(v * 1.05 * 1e4) / 1e4;
if (!std::isfinite(v) || !(v > 0)) throw std::runtime_error("Invalid spectral density domain");
}
return wire;
}
std::vector<float> generateFilmLut(const Filming& film, const DensityWire& wire,
const Scanner* positiveScanner, int size) {
return generate(size, [&](int r, int g, int b) {
Vec3 value = film.develop(linearInput(r, g, b, size));
if (positiveScanner) return positiveScanner->scan(value);
for (int c = 0; c < 3; ++c)
value[c] = (value[c] - wire.minimum[c]) / (wire.maximum[c] - wire.minimum[c]);
return value;
});
}
std::vector<float> generatePrintLut(const Printing& printing, const Scanner& scanner,
const DensityWire& wire, int size) {
return generate(size, [&](int r, int g, int b) {
const Vec3 code{1.5 * r / (size - 1), 1.5 * g / (size - 1), 1.5 * b / (size - 1)};
Vec3 density{};
for (int c = 0; c < 3; ++c)
density[c] = static_cast<float>(wire.minimum[c] + code[c] * (wire.maximum[c] - wire.minimum[c]));
return scanner.scan(printing.develop(printing.expose(density)));
});
}
}
@@ -0,0 +1,12 @@
#pragma once
#include "spectral_filming.h"
#include "spectral_printing.h"
namespace spektrafilm {
struct DensityWire { Vec3 minimum, maximum; };
DensityWire measureDensityWire(const Filming& film);
std::vector<float> generateFilmLut(const Filming& film, const DensityWire& wire,
const Scanner* positiveScanner, int size);
std::vector<float> generatePrintLut(const Printing& printing, const Scanner& scanner,
const DensityWire& wire, int size);
}
@@ -0,0 +1,130 @@
#include "spectral_generator.h"
#include <jni.h>
#include <android/log.h>
#include <chrono>
#include <memory>
#include <mutex>
#include <stdexcept>
namespace {
using namespace spektrafilm;
struct RuntimeModel {
std::string sharedKey, filmKey;
DataSet shared, filmData;
std::unique_ptr<Filming> film;
DensityWire wire{};
};
RuntimeModel model;
std::mutex modelMutex;
std::string string(JNIEnv* env, jstring value) {
if (!value) throw std::invalid_argument("Missing spectral model key");
const char* chars = env->GetStringUTFChars(value, nullptr);
if (!chars) throw std::runtime_error("Unable to read spectral model key");
std::string result(chars);
env->ReleaseStringUTFChars(value, chars);
return result;
}
DataSet data(JNIEnv* env, jbyteArray input) {
if (!input) throw std::invalid_argument("Missing spectral model data");
const jsize size = env->GetArrayLength(input);
if (size <= 0 || size > 64 * 1024 * 1024) throw std::invalid_argument("Invalid spectral model byte count");
jbyte* bytes = env->GetByteArrayElements(input, nullptr);
if (!bytes) throw std::runtime_error("Unable to access spectral model data");
try {
auto result = readDataSet(reinterpret_cast<uint8_t*>(bytes), size);
env->ReleaseByteArrayElements(input, bytes, JNI_ABORT);
return result;
} catch (...) {
env->ReleaseByteArrayElements(input, bytes, JNI_ABORT);
throw;
}
}
jfloatArray output(JNIEnv* env, const std::vector<float>& values) {
jfloatArray array = env->NewFloatArray(static_cast<jsize>(values.size()));
if (!array) throw std::runtime_error("Unable to allocate spectral lattice");
if (!values.empty()) env->SetFloatArrayRegion(array, 0, static_cast<jsize>(values.size()), values.data());
if (env->ExceptionCheck()) throw std::runtime_error("Unable to copy spectral lattice");
return array;
}
}
extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_hinnka_mycamera_raw_SpektrafilmNativeBridge_generate(
JNIEnv* env, jobject, jstring sharedKeyValue, jstring filmKeyValue,
jbyteArray sharedData, jbyteArray filmData, jstring paperNameValue,
jbyteArray paperData, jboolean positive, jboolean buildFilm, jboolean buildPrint) {
std::lock_guard<std::mutex> lock(modelMutex);
try {
const auto started = std::chrono::steady_clock::now();
const std::string sharedKey = string(env, sharedKeyValue);
const std::string filmKey = string(env, filmKeyValue);
const std::string paperName = string(env, paperNameValue);
if (model.sharedKey != sharedKey) {
model = RuntimeModel{};
model.shared = data(env, sharedData);
model.sharedKey = sharedKey;
}
if (model.filmKey != filmKey) {
model.film.reset();
model.filmData.clear();
model.filmKey.clear();
model.filmData = data(env, filmData);
model.film = std::make_unique<Filming>(model.shared, model.filmData);
model.wire = measureDensityWire(*model.film);
model.filmKey = filmKey;
}
if (!model.film || model.film->positive() != bool(positive) || (positive && buildPrint))
throw std::invalid_argument("Spectral model topology mismatch");
static const OutputGamut gamut;
std::vector<float> filmTable, printTable;
if (buildFilm) {
if (positive) {
const Scanner scanner(model.shared, model.filmData, gamut);
filmTable = generateFilmLut(*model.film, model.wire, &scanner, 65);
} else {
filmTable = generateFilmLut(*model.film, model.wire, nullptr, 65);
}
}
if (buildPrint) {
const DataSet paper = data(env, paperData);
const Printing printing(model.shared, model.filmData, paper, paperName, model.film->midgrayDensity());
const Scanner scanner(model.shared, paper, gamut);
printTable = generatePrintLut(printing, scanner, model.wire, 65);
}
jclass floatArrayClass = env->FindClass("[F");
if (!floatArrayClass) throw std::runtime_error("Missing float array class");
jobjectArray result = env->NewObjectArray(2, floatArrayClass, nullptr);
env->DeleteLocalRef(floatArrayClass);
if (!result) throw std::runtime_error("Unable to allocate spectral result");
jfloatArray filmOutput = output(env, filmTable);
env->SetObjectArrayElement(result, 0, filmOutput);
env->DeleteLocalRef(filmOutput);
// Release native arrays before constructing the next Java result.
std::vector<float>().swap(filmTable);
jfloatArray printOutput = output(env, printTable);
env->SetObjectArrayElement(result, 1, printOutput);
env->DeleteLocalRef(printOutput);
if (env->ExceptionCheck()) throw std::runtime_error("Unable to return spectral result");
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - started).count();
__android_log_print(ANDROID_LOG_DEBUG, "SpektrafilmNative", "Generated on demand: film=%d print=%d size=65 elapsed=%lldms model=%s",
int(buildFilm), int(buildPrint), static_cast<long long>(elapsed), filmKey.c_str());
return result;
} catch (const std::exception& e) {
// Kotlin invalidates its model-key handshake after any failed call.
model = RuntimeModel{};
if (!env->ExceptionCheck()) {
jclass exception = env->FindClass("java/lang/IllegalStateException");
if (exception) env->ThrowNew(exception, e.what());
}
return nullptr;
} catch (...) {
model = RuntimeModel{};
if (!env->ExceptionCheck()) {
jclass exception = env->FindClass("java/lang/IllegalStateException");
if (exception) env->ThrowNew(exception, "Native spectral generation failed");
}
return nullptr;
}
}
@@ -0,0 +1,158 @@
// Pointwise printing/scanning port of Spektrafilm 0.3.4 (3bb2c2d).
// See LICENSE.spektrafilm and docs/spektrafilm-luts.md for provenance.
#include "spectral_printing.h"
#include <algorithm>
#include <cmath>
#include <stdexcept>
namespace spektrafilm {
namespace {
const std::vector<double>& sized(const DataSet& d, const std::string& name, size_t count) {
const auto& v = d.at(name);
if (v.size() != count) throw std::invalid_argument("Invalid spectral tensor: " + name);
return v;
}
double spectralDensity(const std::vector<double>& dyes, const std::vector<double>& base,
size_t wavelength, const Vec3& cmy) {
double d = base[wavelength];
for (int c = 0; c < 3; ++c) d += cmy[c] * dyes[wavelength * 3 + c];
return d;
}
}
double proPhotoDecode(double v) {
return v < 0.03125 ? v / 16.0 : std::pow(v, 1.8);
}
double proPhotoEncode(double v) {
v = std::clamp(v, 0.0, 1.0);
return v < 0.001953125 ? v * 16.0 : std::pow(v, 1.0 / 1.8);
}
Scanner::Scanner(const DataSet& shared, const DataSet& medium, const OutputGamut& gamut)
: base_(medium.at("spectral.baseDensity")), gamut_(gamut) {
const size_t n = base_.size();
if (n == 0 || n > 1024) throw std::invalid_argument("Invalid scan wavelengths");
dyes_ = sized(medium, "spectral.channelDensity", n * 3);
valid_ = sized(medium, "spectral.valid", n);
illuminant_ = sized(medium, "scan.illuminant", n);
observer_ = sized(shared, "scan.observer", n * 3);
matrix_ = sized(medium, "scan.xyzToProPhoto", 9);
for (size_t w = 0; w < n; ++w) normalization_ += illuminant_[w] * observer_[w * 3 + 1];
if (!(normalization_ > 0)) throw std::invalid_argument("Invalid scanner illuminant");
}
Vec3 Scanner::scan(const Vec3& density) const {
Vec3 xyz{}, rgb{};
for (size_t w = 0; w < base_.size(); ++w) {
if (valid_[w] == 0) continue;
const double light = std::pow(10.0, -spectralDensity(dyes_, base_, w, density)) * illuminant_[w];
for (int c = 0; c < 3; ++c) xyz[c] += light * observer_[w * 3 + c];
}
for (double& v : xyz) {
// Match the upstream cmy_to_log_xyz -> pow(10, log_xyz) tap contract.
v = std::pow(10.0, std::log10(std::max(v / normalization_, 0.0) + 1e-10));
}
for (int r = 0; r < 3; ++r)
for (int c = 0; c < 3; ++c) rgb[r] += matrix_[r * 3 + c] * xyz[c];
rgb = gamut_.compress(rgb);
for (double& v : rgb) {
if (!std::isfinite(v)) throw std::runtime_error("Non-finite spectral scanner result");
v = proPhotoEncode(v);
}
return rgb;
}
Printing::Printing(const DataSet& shared, const DataSet& film, const DataSet& paper,
const std::string& paperName, const Vec3& midgrayDensity)
: filmBase_(film.at("spectral.baseDensity")), axis_(paper.at("print.logExposure")) {
const size_t n = filmBase_.size();
if (n == 0 || n > 1024 || axis_.size() < 2 || axis_.size() > 65536)
throw std::invalid_argument("Invalid print model dimensions");
filmDyes_ = sized(film, "spectral.channelDensity", n * 3);
valid_ = sized(film, "spectral.valid", n);
const auto& filters = sized(shared, "print.dichroicFilters", n * 3);
const auto& light = sized(shared, "print.lightSource", n);
const auto& sensitivity = sized(paper, "print.sensitivity", n * 3);
const auto& cc = sized(film, "print.neutral." + paperName, 3);
exposure_ = sized(paper, "print.exposure", 1)[0];
const bool normalize = sized(paper, "print.normalizeExposure", 1)[0] != 0;
if (!(exposure_ > 0)) throw std::invalid_argument("Invalid print exposure");
Vec3 transmittance{};
for (int c = 0; c < 3; ++c) transmittance[c] = std::pow(10.0, -cc[c] / 100.0);
weights_.resize(n * 3);
Vec3 rawMidgray{};
for (size_t w = 0; w < n; ++w) {
if (valid_[w] == 0) continue;
double source = light[w];
for (int c = 0; c < 3; ++c)
source *= 1.0 - (1.0 - filters[w * 3 + c]) * (1.0 - transmittance[c]);
const double transmission = std::pow(10.0, -spectralDensity(filmDyes_, filmBase_, w, midgrayDensity));
for (int c = 0; c < 3; ++c) {
weights_[w * 3 + c] = source * sensitivity[w * 3 + c];
rawMidgray[c] += transmission * weights_[w * 3 + c];
}
}
// Default camera EV=0: compensated and uncompensated reference exposures
// coincide, preserving all normalize/compensate branches of this preset.
if (normalize) {
double logMean = 0;
for (double v : rawMidgray) logMean += std::log(std::max(v, 1e-10)) / 3.0;
normalization_ = std::exp(-logMean);
}
const auto& centers = paper.at("print.centers");
if (centers.empty() || centers.size() % 3 != 0 || centers.size() > 96)
throw std::invalid_argument("Invalid print density layers");
const size_t layers = centers.size() / 3;
const auto& sigmas = sized(paper, "print.sigmas", centers.size());
const auto& amplitudes = sized(paper, "print.amplitudes", centers.size());
if (!std::is_sorted(axis_.begin(), axis_.end())) throw std::invalid_argument("Unsorted print curve");
curves_.resize(axis_.size() * 3);
// LUT mode disables creative s023 morphing: evaluate the fitted normal
// CDF layers on the stock exposure axis, then interpolate as upstream.
if (std::any_of(sigmas.begin(), sigmas.end(), [](double v) { return !(v > 0); }))
throw std::invalid_argument("Invalid print layer sigma");
for (size_t i = 0; i < axis_.size(); ++i) {
for (int c = 0; c < 3; ++c) {
double density = 0;
for (size_t layer = 0; layer < layers; ++layer) {
const size_t k = c * layers + layer;
const double sigma = sigmas[k];
const double z = (axis_[i] - centers[k]) / sigma;
density += amplitudes[k] * 0.5 * std::erfc(-z / std::sqrt(2.0));
}
curves_[i * 3 + c] = density;
}
}
}
Vec3 Printing::expose(const Vec3& filmDensity) const {
Vec3 raw{};
for (size_t w = 0; w < filmBase_.size(); ++w) {
if (valid_[w] == 0) continue;
const double transmission = std::pow(10.0, -spectralDensity(filmDyes_, filmBase_, w, filmDensity));
for (int c = 0; c < 3; ++c) raw[c] += transmission * weights_[w * 3 + c];
}
for (double& v : raw) {
const double logRaw = std::log10(std::max(v * normalization_, 0.0) + 1e-10);
v = std::log10(std::max(std::pow(10.0, logRaw) * exposure_, 0.0) + 1e-10);
}
return raw;
}
Vec3 Printing::develop(const Vec3& logExposure) const {
Vec3 result{};
for (int c = 0; c < 3; ++c) {
const double x = logExposure[c];
if (x <= axis_.front()) result[c] = curves_[c];
else if (x >= axis_.back()) result[c] = curves_[(axis_.size() - 1) * 3 + c];
else {
const size_t upper = std::upper_bound(axis_.begin(), axis_.end(), x) - axis_.begin();
const size_t lower = upper - 1;
const double width = axis_[upper] - axis_[lower];
const double t = width != 0 ? (x - axis_[lower]) / width : 0.0;
result[c] = curves_[lower * 3 + c] + t * (curves_[upper * 3 + c] - curves_[lower * 3 + c]);
}
}
return result;
}
}
@@ -0,0 +1,33 @@
#pragma once
#include "spectral_data.h"
#include "spectral_gamut.h"
namespace spektrafilm {
// Pointwise LUT-mode scanning. The medium can be a print or a positive film.
class Scanner {
public:
Scanner(const DataSet& shared, const DataSet& medium, const OutputGamut& gamut);
Vec3 scan(const Vec3& density) const;
private:
std::vector<double> dyes_, base_, valid_, illuminant_, observer_, matrix_;
double normalization_ = 0;
const OutputGamut& gamut_;
};
class Printing {
public:
Printing(const DataSet& shared, const DataSet& film, const DataSet& paper,
const std::string& paperName, const Vec3& midgrayDensity);
Vec3 expose(const Vec3& filmDensity) const;
Vec3 develop(const Vec3& logExposure) const;
private:
std::vector<double> filmDyes_, filmBase_, valid_, weights_, axis_, curves_;
double normalization_ = 1, exposure_ = 1;
};
double proPhotoDecode(double value);
double proPhotoEncode(double value);
}
@@ -1,16 +1,15 @@
package com.hinnka.mycamera.raw
import android.content.Context
import com.hinnka.mycamera.lut.LutConfig
import com.hinnka.mycamera.utils.BoundedTextLineReader
import com.hinnka.mycamera.utils.PLog
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.math.abs
import kotlin.math.ln
import kotlin.math.pow
/** RGBA lattice in blue, green, red order, with red varying fastest. */
data class SpectralLutTable(
val sourceKey: String,
val size: Int,
val values: FloatArray,
)
data class SpectralFilmLut(
val stock: String,
@@ -19,19 +18,20 @@ data class SpectralFilmLut(
val referenceIlluminant: String,
val viewingIlluminant: String,
val sourceKey: String,
val size: Int,
val values: FloatArray
)
val filmTable: SpectralLutTable,
val printTable: SpectralLutTable?,
val inputScale: Float,
val printInputScale: Float,
val negativeDensityGains: FloatArray,
) {
val size: Int get() = filmTable.size
val values: FloatArray get() = filmTable.values
}
data class FilmStockInfo(
val type: String,
val referenceIlluminant: String,
val viewingIlluminant: String
)
data class FilmDensityWire(
val dMin: FloatArray,
val dMax: FloatArray
val viewingIlluminant: String,
)
data class SpectralFilmTuning(
@@ -83,38 +83,6 @@ data class PrintPaperInfo(
val viewingIlluminant: String
)
data class SpectralFilmPrintModel(
val version: Int,
val observerCmfs: FloatArray,
val viewingIlluminants: Map<String, FloatArray>,
val xyzToProPhoto: Map<String, FloatArray>,
val films: Map<String, SpectralFilmModelData>,
val papers: Map<String, SpectralPaperModelData>,
val combinations: Map<String, Map<String, SpectralPrintCombinationData>>
)
data class SpectralFilmModelData(
val channelDensity: FloatArray,
val baseDensity: FloatArray,
val densityMin: FloatArray,
val densityMax: FloatArray
)
data class SpectralPaperModelData(
val viewingIlluminant: String,
val sensitivity: FloatArray,
val channelDensity: FloatArray,
val baseDensity: FloatArray,
val logExposure: FloatArray,
val densityCurves: FloatArray
)
data class SpectralPrintCombinationData(
val printIlluminant: FloatArray,
val exposureFactor: Float,
val neutralFilters: FloatArray
)
object FilmStockRegistry {
private val default = FilmStockInfo(
type = "negative",
@@ -148,38 +116,6 @@ object FilmStockRegistry {
fun get(stock: String): FilmStockInfo = stocks[stock] ?: default
}
object FilmDensityWireRegistry {
private val defaultDMin = floatArrayOf(-0.2f, -0.2f, -0.2f)
val wires = mapOf(
"fujifilm_c200" to wire(1.7393f, 1.9257f, 2.2892f),
"fujifilm_pro_400h" to wire(1.5215f, 1.6171f, 2.0555f),
"fujifilm_xtra_400" to wire(2.0234f, 2.1502f, 2.6683f),
"kodak_ektar_100" to wire(1.8008f, 1.7775f, 2.2188f),
"kodak_gold_200" to wire(1.6538f, 1.5270f, 1.6814f),
"kodak_portra_160" to wire(1.6281f, 1.6692f, 1.9841f),
"kodak_portra_400" to wire(1.8590f, 1.7816f, 2.0896f),
"kodak_portra_800" to wire(1.8386f, 1.7134f, 1.8858f),
"kodak_portra_800_push1" to wire(2.1669f, 1.9517f, 2.2205f),
"kodak_portra_800_push2" to wire(2.3529f, 2.0343f, 2.4457f),
"kodak_ultramax_400" to wire(1.7868f, 1.6910f, 1.9068f),
"kodak_verita_200d" to wire(1.6719f, 1.6319f, 1.8600f),
"kodak_vision3_200t" to wire(1.5222f, 1.5838f, 1.8118f),
"kodak_vision3_250d" to wire(1.5678f, 1.6333f, 1.8032f),
"kodak_vision3_500t" to wire(1.5709f, 1.5010f, 1.8260f),
"kodak_vision3_50d" to wire(1.5802f, 1.6924f, 1.9061f)
)
fun get(stock: String): FilmDensityWire? = wires[stock]
private fun wire(cMax: Float, mMax: Float, yMax: Float): FilmDensityWire {
return FilmDensityWire(
dMin = defaultDMin.copyOf(),
dMax = floatArrayOf(cMax, mMax, yMax)
)
}
}
object PrintPaperRegistry {
private val default = PrintPaperInfo(referenceIlluminant = "TH-KG3", viewingIlluminant = "D50")
@@ -197,447 +133,178 @@ object PrintPaperRegistry {
fun get(paper: String): PrintPaperInfo = papers[paper] ?: default
}
object SpectralPrintModelRegistry {
private const val TAG = "SpectralPrintModel"
private const val MODEL_ASSET = "spektrafilm/print_model.json"
private const val WAVELENGTH_COUNT = 81
private const val CHANNEL_COUNT = 3
@Volatile
private var cached: SpectralFilmPrintModel? = null
fun load(context: Context): SpectralFilmPrintModel? {
cached?.let { return it }
return synchronized(this) {
cached ?: loadInternal(context)?.also { cached = it }
}
}
private fun loadInternal(context: Context): SpectralFilmPrintModel? {
return try {
val jsonText = context.assets.open(MODEL_ASSET).bufferedReader().use { it.readText() }
val root = JSONObject(jsonText)
SpectralFilmPrintModel(
version = root.optInt("version", 1),
observerCmfs = root.getJSONArray("observerCmfs").toFloatArray2d(WAVELENGTH_COUNT, CHANNEL_COUNT),
viewingIlluminants = root.getJSONObject("viewingIlluminants").toFloatArrayMap1d(),
xyzToProPhoto = root.getJSONObject("xyzToProPhoto").toFloatArrayMap2d(CHANNEL_COUNT, CHANNEL_COUNT),
films = parseFilms(root.getJSONObject("films")),
papers = parsePapers(root.getJSONObject("papers")),
combinations = parseCombinations(root.getJSONObject("combinations"))
)
} catch (e: Exception) {
PLog.e(TAG, "Failed to load Spektrafilm print model", e)
null
}
}
private fun parseFilms(obj: JSONObject): Map<String, SpectralFilmModelData> {
val result = mutableMapOf<String, SpectralFilmModelData>()
obj.keys().forEach { key ->
val film = obj.getJSONObject(key)
result[key] = SpectralFilmModelData(
channelDensity = film.getJSONArray("channelDensity").toFloatArray2d(WAVELENGTH_COUNT, CHANNEL_COUNT),
baseDensity = film.getJSONArray("baseDensity").toFloatArray1d(),
densityMin = film.getJSONArray("densityMin").toFloatArray1d(),
densityMax = film.getJSONArray("densityMax").toFloatArray1d()
)
}
return result
}
private fun parsePapers(obj: JSONObject): Map<String, SpectralPaperModelData> {
val result = mutableMapOf<String, SpectralPaperModelData>()
obj.keys().forEach { key ->
val paper = obj.getJSONObject(key)
result[key] = SpectralPaperModelData(
viewingIlluminant = paper.getString("viewingIlluminant"),
sensitivity = paper.getJSONArray("sensitivity").toFloatArray2d(WAVELENGTH_COUNT, CHANNEL_COUNT),
channelDensity = paper.getJSONArray("channelDensity").toFloatArray2d(WAVELENGTH_COUNT, CHANNEL_COUNT),
baseDensity = paper.getJSONArray("baseDensity").toFloatArray1d(),
logExposure = paper.getJSONArray("logExposure").toFloatArray1d(),
densityCurves = paper.getJSONArray("densityCurves").toFloatArray2d(paper.getJSONArray("logExposure").length(), CHANNEL_COUNT)
)
}
return result
}
private fun parseCombinations(obj: JSONObject): Map<String, Map<String, SpectralPrintCombinationData>> {
val result = mutableMapOf<String, Map<String, SpectralPrintCombinationData>>()
obj.keys().forEach { filmKey ->
val paperMap = mutableMapOf<String, SpectralPrintCombinationData>()
val papers = obj.getJSONObject(filmKey)
papers.keys().forEach { paperKey ->
val combo = papers.getJSONObject(paperKey)
paperMap[paperKey] = SpectralPrintCombinationData(
printIlluminant = combo.getJSONArray("printIlluminant").toFloatArray1d(),
exposureFactor = combo.getJSONArray("exposureFactor").firstNumber().toFloat(),
neutralFilters = combo.getJSONArray("neutralFilters").toFloatArray1d()
)
}
result[filmKey] = paperMap
}
return result
}
private fun JSONObject.toFloatArrayMap1d(): Map<String, FloatArray> {
val result = mutableMapOf<String, FloatArray>()
keys().forEach { key -> result[key] = getJSONArray(key).toFloatArray1d() }
return result
}
private fun JSONObject.toFloatArrayMap2d(rows: Int, cols: Int): Map<String, FloatArray> {
val result = mutableMapOf<String, FloatArray>()
keys().forEach { key -> result[key] = getJSONArray(key).toFloatArray2d(rows, cols) }
return result
}
private fun JSONArray.toFloatArray1d(): FloatArray {
val result = FloatArray(length())
for (i in 0 until length()) {
result[i] = optDouble(i, 0.0).toFloat()
}
return result
}
private fun JSONArray.toFloatArray2d(rows: Int, cols: Int): FloatArray {
val result = FloatArray(rows * cols)
for (row in 0 until rows) {
val rowArray = getJSONArray(row)
for (col in 0 until cols) {
result[row * cols + col] = rowArray.optDouble(col, 0.0).toFloat()
}
}
return result
}
private fun JSONArray.firstNumber(): Double {
var current: Any = this
while (current is JSONArray) {
current = current.get(0)
}
return (current as Number).toDouble()
}
}
/** Resolves source models and generates only the selected film/print stages. */
object SpectralFilmProfile {
private const val TAG = "SpectralFilmProfile"
private const val LUT_SIZE = 17
private const val RAW_SPECTRAL_FILM_INPUT_SCALE = 2.88f
private const val PREVIEW_EXPOSURE_ANCHOR_SRGB = 0.5f
private const val MAX_MANIFEST_BYTES = 1024 * 1024
private val sha256Pattern = Regex("[0-9a-f]{64}")
private val commitPattern = Regex("[0-9a-f]{40}")
private const val DEFAULT_FILM_ASSET = "spektrafilm/profiles/kodak_portra_400_film.cube"
private data class FilmAsset(
val type: String,
val referenceIlluminant: String,
val viewingIlluminant: String,
val model: SpectralModelAsset,
)
private data class PrintAsset(val model: SpectralModelAsset, val viewingIlluminant: String)
private data class Manifest(
val upstreamCommit: String,
val algorithm: String,
val size: Int,
val inputScale: Float,
val printInputScale: Float,
val shared: SpectralModelAsset,
val films: Map<String, FilmAsset>,
val prints: Map<String, PrintAsset>,
)
@Volatile
private var cachedDefault: SpectralFilmLut? = null
// All access is serialized, including native model lifetime and disk eviction.
// Tuning changes reuse these exact arrays and only update shader uniforms.
private var cachedManifest: Manifest? = null
private var cachedFilm: SpectralLutTable? = null
private var cachedPrint: SpectralLutTable? = null
private var cachedSelection: SpectralFilmLut? = null
@Volatile
private var cachedCombined: SpectralFilmLut? = null
private var cachedCombinedFilmKey: String? = null
private var cachedCombinedPrintKey: String? = null
private var cachedCombinedTuningKey: String? = null
@Volatile
private var cachedPreviewConfig: LutConfig? = null
private var cachedPreviewFilmKey: String? = null
private var cachedPreviewPrintKey: String? = null
private var cachedPreviewTuningKey: String? = null
fun loadDefaultLut(context: Context): SpectralFilmLut? {
cachedDefault?.let { return it }
return synchronized(this) {
cachedDefault ?: loadCombinedLutInternal(
context,
"kodak_portra_400",
"kodak_portra_endura",
DEFAULT_FILM_ASSET
)?.also { cachedDefault = it }
}
}
fun loadDefaultLut(context: Context): SpectralFilmLut? = loadCombinedLut(
context, "kodak_portra_400", "kodak_portra_endura",
)
@Synchronized
fun loadCombinedLut(
context: Context,
filmStock: String,
printPaper: String,
tuning: SpectralFilmTuning = SpectralFilmTuning.DEFAULT
): SpectralFilmLut? {
val tuningKey = tuning.cacheKey()
if (cachedCombinedFilmKey == filmStock && cachedCombinedPrintKey == printPaper && cachedCombinedTuningKey == tuningKey) {
cachedCombined?.let { return it }
}
return synchronized(this) {
if (cachedCombinedFilmKey == filmStock && cachedCombinedPrintKey == printPaper && cachedCombinedTuningKey == tuningKey) {
cachedCombined?.let { return it }
}
val filmAsset = "spektrafilm/profiles/${filmStock}_film.cube"
val lut = loadCombinedLutInternal(context, filmStock, printPaper, filmAsset, tuning.normalized())
if (lut != null) {
cachedCombined = lut
cachedCombinedFilmKey = filmStock
cachedCombinedPrintKey = printPaper
cachedCombinedTuningKey = tuningKey
}
lut
}
}
private fun loadCombinedLutInternal(
context: Context,
filmStock: String,
printPaper: String,
filmAssetPath: String,
tuning: SpectralFilmTuning = SpectralFilmTuning.DEFAULT
): SpectralFilmLut? {
val startTime = System.currentTimeMillis()
val filmInfo = FilmStockRegistry.get(filmStock)
val printInfo = PrintPaperRegistry.get(printPaper)
if (filmInfo.type == "positive") {
val positiveData = loadRawCube(context, filmAssetPath) ?: return null
val positiveValues = packRgbLut(positiveData)
val elapsed = System.currentTimeMillis() - startTime
PLog.d(
TAG,
"Loaded positive film 1-LUT ($filmStock) from film asset without print paper ($printPaper ignored) in ${elapsed}ms"
)
return SpectralFilmLut(
tuning: SpectralFilmTuning = SpectralFilmTuning.DEFAULT,
): SpectralFilmLut? = try {
val manifest = cachedManifest ?: loadManifest(context).also { cachedManifest = it }
val film = requireNotNull(manifest.films[filmStock]) { "Unknown Spektrafilm stock: $filmStock" }
val print = if (film.type == "negative") {
requireNotNull(manifest.prints[printPaper]) { "Unknown Spektrafilm print: $printPaper" }
} else null
val normalized = tuning.normalized()
val gains = if (print != null) floatArrayOf(
normalized.negativeFilmDensityGainC(),
normalized.negativeFilmDensityGainM(),
normalized.negativeFilmDensityGainY(),
) else floatArrayOf(1f, 1f, 1f)
require(gains.all { it.isFinite() && it in 0.5f..1.5f }) { "Invalid Spektrafilm density gains" }
val request = SpectralRuntimeRequest(
algorithm = manifest.algorithm,
upstreamCommit = manifest.upstreamCommit,
size = manifest.size,
inputScale = manifest.inputScale,
printInputScale = manifest.printInputScale,
shared = manifest.shared,
film = film.model,
paperName = if (print != null) printPaper else "",
paper = print?.model,
positive = print == null,
)
val selectionKey = "${request.filmKey}:${request.printKey}:${gains.joinToString()}"
cachedSelection?.takeIf { it.sourceKey == selectionKey } ?: run {
// Release the old selection before loading another pair; otherwise its
// references would keep obsolete LUT arrays alive during generation.
cachedSelection = null
if (cachedFilm?.sourceKey != request.filmKey) cachedFilm = null
if (cachedPrint?.sourceKey != request.printKey) cachedPrint = null
val stages = SpektrafilmRuntime.load(context, request, cachedFilm, cachedPrint)
cachedFilm = stages.first
cachedPrint = stages.second
SpectralFilmLut(
stock = filmStock,
name = filmStock,
type = filmInfo.type,
referenceIlluminant = filmInfo.referenceIlluminant,
viewingIlluminant = filmInfo.viewingIlluminant,
sourceKey = "$filmStock:${filmInfo.type}:${filmInfo.referenceIlluminant}:${filmInfo.viewingIlluminant}",
size = LUT_SIZE,
values = positiveValues
)
}
val filmData = loadRawCube(context, filmAssetPath) ?: return null
val printModel = SpectralPrintModelRegistry.load(context) ?: return null
val densityWire = FilmDensityWireRegistry.get(filmStock)
val combinedValues = combineWithDynamicPrint(filmStock, printPaper, filmData, printModel, densityWire, tuning)
?: return null
val elapsed = System.currentTimeMillis() - startTime
PLog.d(
TAG,
"Dynamically combined film ($filmStock/${filmInfo.referenceIlluminant}) and " +
"print ($printPaper/${printInfo.referenceIlluminant}) using Spektrafilm print model " +
"with ${if (densityWire != null) "cmy_film wire" else "film density range fallback"} in ${elapsed}ms"
)
return SpectralFilmLut(
stock = filmStock,
name = "$filmStock + $printPaper",
type = filmInfo.type,
referenceIlluminant = filmInfo.referenceIlluminant,
viewingIlluminant = printInfo.viewingIlluminant,
sourceKey = "$filmStock:$printPaper:${filmInfo.type}:${filmInfo.referenceIlluminant}:${printInfo.referenceIlluminant}:${printInfo.viewingIlluminant}:wire=${densityWire?.dMax?.joinToString() ?: "fallback"}:tuning=${tuning.cacheKey()}",
size = LUT_SIZE,
values = combinedValues
)
}
private fun loadRawCube(context: Context, assetPath: String): FloatArray? {
return try {
val totalSize = LUT_SIZE * LUT_SIZE * LUT_SIZE * 3
val values = FloatArray(totalSize)
var dst = 0
context.assets.open(assetPath).use { inputStream ->
BufferedReader(InputStreamReader(inputStream)).use { reader ->
BoundedTextLineReader.forEachLine(reader) { line ->
val trimmed = line.trim()
if (trimmed.isEmpty() || trimmed.startsWith("#") ||
trimmed.startsWith("TITLE") || trimmed.startsWith("LUT_3D_SIZE") ||
trimmed.startsWith("DOMAIN_MIN") || trimmed.startsWith("DOMAIN_MAX")
) {
return@forEachLine
}
val parts = trimmed.split("\\s+".toRegex())
if (parts.size >= 3 && dst < totalSize) {
values[dst++] = parts[0].toFloat()
values[dst++] = parts[1].toFloat()
values[dst++] = parts[2].toFloat()
}
}
}
name = if (print != null) "$filmStock + $printPaper" else filmStock,
type = film.type,
referenceIlluminant = film.referenceIlluminant,
viewingIlluminant = print?.viewingIlluminant ?: film.viewingIlluminant,
sourceKey = selectionKey,
filmTable = stages.first,
printTable = stages.second,
inputScale = manifest.inputScale,
printInputScale = manifest.printInputScale,
negativeDensityGains = gains,
).also {
cachedSelection = it
PLog.d(TAG, "Selected Spektrafilm ${it.name}, pipeline=native-spectral-two-stage, " +
"filmSize=${it.size}, printSize=${it.printTable?.size ?: 0}, " +
"densityGains=${gains.joinToString()}, upstream=${manifest.upstreamCommit}")
}
if (dst == totalSize) {
values
} else {
PLog.e(TAG, "Cube file $assetPath has incorrect size: $dst elements, expected $totalSize")
null
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to prepare Spektrafilm stages for $filmStock + $printPaper", e)
null
} catch (e: LinkageError) {
PLog.e(TAG, "Spektrafilm native runtime is unavailable", e)
null
}
private fun loadManifest(context: Context): Manifest {
val bytes = context.assets.open("spektrafilm/manifest.json").use { input ->
val buffer = ByteArray(MAX_MANIFEST_BYTES + 1)
var count = 0
while (count < buffer.size) {
val read = input.read(buffer, count, buffer.size - count)
if (read < 0) break
count += read
}
} catch (e: Exception) {
PLog.e(TAG, "Failed to load raw cube from $assetPath", e)
null
require(count <= MAX_MANIFEST_BYTES) { "Spektrafilm manifest exceeds size limit" }
buffer.copyOf(count)
}
val root = JSONObject(bytes.toString(Charsets.UTF_8))
require(root.getDouble("schemaVersion") == 4.0) { "Unsupported Spektrafilm model schema" }
require(root.getString("encoding") == "gzip-named-packed-le" &&
root.getString("runtimeAlgorithm") == "spectral-v1" && root.getBoolean("lutMode")) {
"Unsupported Spektrafilm model/runtime contract"
}
require(root.getString("inputColorSpace") == "ProPhoto RGB" &&
root.getString("outputColorSpace") == "ProPhoto RGB") { "Invalid Spektrafilm color contract" }
val size = root.getInt("lutSize")
require(size == 65 && root.getDouble("lutSize") == 65.0) { "Invalid Spektrafilm runtime lattice size" }
val inputScale = root.getDouble("inputScale").toFloat()
val printInputScale = root.getDouble("printInputScale").toFloat()
require(inputScale == 2.88f && printInputScale == 1.5f) { "Invalid Spektrafilm input domains" }
val commit = root.getString("upstreamCommit")
require(commitPattern.matches(commit)) { "Invalid Spektrafilm upstream commit" }
val filmObjects = root.getJSONObject("films")
require(filmObjects.keys().asSequence().toSet() == FilmStockRegistry.stocks.keys) {
"Spektrafilm model stock coverage differs from the UI registry"
}
val films = FilmStockRegistry.stocks.mapValues { (stock, expected) ->
val obj = filmObjects.getJSONObject(stock)
val type = obj.getString("type")
val reference = obj.getString("referenceIlluminant")
val viewing = obj.getString("viewingIlluminant")
require(type == expected.type && reference == expected.referenceIlluminant &&
viewing == expected.viewingIlluminant) { "Invalid Spektrafilm film metadata: $stock" }
FilmAsset(type, reference, viewing, parseModelAsset(obj.getJSONObject("model")))
}
val printObjects = root.getJSONObject("prints")
require(printObjects.keys().asSequence().toSet() == PrintPaperRegistry.papers.keys) {
"Spektrafilm model print coverage differs from the UI registry"
}
val prints = PrintPaperRegistry.papers.mapValues { (paper, expected) ->
val obj = printObjects.getJSONObject(paper)
val viewing = obj.getString("viewingIlluminant")
require(viewing == expected.viewingIlluminant) { "Invalid print illuminant: $paper" }
PrintAsset(parseModelAsset(obj.getJSONObject("model")), viewing)
}
return Manifest(commit, root.getString("runtimeAlgorithm"), size, inputScale,
printInputScale, parseModelAsset(root.getJSONObject("shared")), films, prints)
}
private fun packRgbLut(rgbData: FloatArray): FloatArray {
val totalSize = LUT_SIZE * LUT_SIZE * LUT_SIZE * 4
val result = FloatArray(totalSize)
for (i in 0 until (LUT_SIZE * LUT_SIZE * LUT_SIZE)) {
val dstOffset = i * 4
result[dstOffset] = rgbData[i * 3]
result[dstOffset + 1] = rgbData[i * 3 + 1]
result[dstOffset + 2] = rgbData[i * 3 + 2]
result[dstOffset + 3] = 1f
private fun parseModelAsset(obj: JSONObject): SpectralModelAsset {
val path = obj.getString("path")
require(path.startsWith("model/") && path.endsWith(".spkm") &&
path.split('/').all { it.isNotEmpty() && it != "." && it != ".." && '\\' !in it }) {
"Invalid Spektrafilm model path: $path"
}
return result
val sha256 = obj.getString("sha256")
require(sha256Pattern.matches(sha256)) { "Invalid Spektrafilm model digest: $path" }
fun length(field: String): Int {
val size = obj.getLong(field)
require(size in 1..SpektrafilmRuntime.MAX_MODEL_BYTES.toLong() &&
obj.getDouble(field) == size.toDouble()) { "Invalid Spektrafilm model $field: $path" }
return size.toInt()
}
return SpectralModelAsset(path, sha256, length("bytes"), length("uncompressedBytes"))
}
private fun combineWithDynamicPrint(
filmStock: String,
printPaper: String,
filmData: FloatArray,
model: SpectralFilmPrintModel,
densityWire: FilmDensityWire?,
tuning: SpectralFilmTuning
): FloatArray? {
val filmModel = model.films[filmStock]
val paperModel = model.papers[printPaper]
val combo = model.combinations[filmStock]?.get(printPaper)
if (filmModel == null || paperModel == null || combo == null) {
PLog.e(TAG, "Missing Spektrafilm print model data for $filmStock + $printPaper")
return null
}
val viewingIlluminant = model.viewingIlluminants[paperModel.viewingIlluminant]
val xyzToProPhoto = model.xyzToProPhoto[paperModel.viewingIlluminant]
if (viewingIlluminant == null || xyzToProPhoto == null) {
PLog.e(TAG, "Missing viewing illuminant ${paperModel.viewingIlluminant} for $printPaper")
return null
}
val totalSize = LUT_SIZE * LUT_SIZE * LUT_SIZE * 4
val combined = FloatArray(totalSize)
val wavelengths = viewingIlluminant.size
val paperSensitivity = FloatArray(wavelengths * 3)
for (i in paperSensitivity.indices) {
paperSensitivity[i] = paperModel.sensitivity[i]
}
val scanNormalization = computeScanNormalization(viewingIlluminant, model.observerCmfs, wavelengths)
val dMinFilm = densityWire?.dMin ?: filmModel.densityMin
val dMaxFilm = densityWire?.dMax ?: filmModel.densityMax
if (densityWire == null) {
PLog.w(TAG, "Missing cmy_film density wire for $filmStock; falling back to film profile density range")
}
val dRange0 = dMaxFilm[0] - dMinFilm[0]
val dRange1 = dMaxFilm[1] - dMinFilm[1]
val dRange2 = dMaxFilm[2] - dMinFilm[2]
val cNegativeFilmGain = tuning.negativeFilmDensityGainC()
val mNegativeFilmGain = tuning.negativeFilmDensityGainM()
val yNegativeFilmGain = tuning.negativeFilmDensityGainY()
val filmSpectralDensity = FloatArray(wavelengths)
val printDensity = FloatArray(3)
val paperSpectralDensity = FloatArray(wavelengths)
for (i in 0 until (LUT_SIZE * LUT_SIZE * LUT_SIZE)) {
val cDensity = dMinFilm[0] + filmData[i * 3] * dRange0 * cNegativeFilmGain
val mDensity = dMinFilm[1] + filmData[i * 3 + 1] * dRange1 * mNegativeFilmGain
val yDensity = dMinFilm[2] + filmData[i * 3 + 2] * dRange2 * yNegativeFilmGain
for (w in 0 until wavelengths) {
val base = w * 3
filmSpectralDensity[w] = filmModel.baseDensity[w] +
cDensity * filmModel.channelDensity[base] +
mDensity * filmModel.channelDensity[base + 1] +
yDensity * filmModel.channelDensity[base + 2]
}
for (ch in 0..2) {
var raw = 0f
for (w in 0 until wavelengths) {
raw += pow10(-filmSpectralDensity[w]) *
combo.printIlluminant[w] *
paperSensitivity[w * 3 + ch]
}
val logRaw = log10((raw * combo.exposureFactor).coerceAtLeast(1e-10f))
printDensity[ch] = interpolateDensity(logRaw, paperModel.logExposure, paperModel.densityCurves, ch)
}
for (w in 0 until wavelengths) {
val base = w * 3
paperSpectralDensity[w] = paperModel.baseDensity[w] +
printDensity[0] * paperModel.channelDensity[base] +
printDensity[1] * paperModel.channelDensity[base + 1] +
printDensity[2] * paperModel.channelDensity[base + 2]
}
var x = 0f
var y = 0f
var z = 0f
for (w in 0 until wavelengths) {
val light = pow10(-paperSpectralDensity[w]) * viewingIlluminant[w]
val cmfBase = w * 3
x += light * model.observerCmfs[cmfBase]
y += light * model.observerCmfs[cmfBase + 1]
z += light * model.observerCmfs[cmfBase + 2]
}
x /= scanNormalization
y /= scanNormalization
z /= scanNormalization
val rLinear = xyzToProPhoto[0] * x + xyzToProPhoto[1] * y + xyzToProPhoto[2] * z
val gLinear = xyzToProPhoto[3] * x + xyzToProPhoto[4] * y + xyzToProPhoto[5] * z
val bLinear = xyzToProPhoto[6] * x + xyzToProPhoto[7] * y + xyzToProPhoto[8] * z
val dstOffset = i * 4
combined[dstOffset] = encodeProPhoto(rLinear)
combined[dstOffset + 1] = encodeProPhoto(gLinear)
combined[dstOffset + 2] = encodeProPhoto(bLinear)
combined[dstOffset + 3] = 1f
}
return combined
}
private fun computeScanNormalization(
illuminant: FloatArray,
observerCmfs: FloatArray,
wavelengths: Int
): Float {
var normalization = 0f
for (w in 0 until wavelengths) {
normalization += illuminant[w] * observerCmfs[w * 3 + 1]
}
return normalization.coerceAtLeast(1e-10f)
}
private fun interpolateDensity(
logRaw: Float,
logExposure: FloatArray,
densityCurves: FloatArray,
channel: Int
): Float {
if (logRaw <= logExposure.first()) return densityCurves[channel]
val lastIndex = logExposure.lastIndex
if (logRaw >= logExposure[lastIndex]) return densityCurves[lastIndex * 3 + channel]
var high = 1
while (high < logExposure.size && logRaw > logExposure[high]) {
high++
}
val low = high - 1
val t = ((logRaw - logExposure[low]) / (logExposure[high] - logExposure[low])).coerceIn(0f, 1f)
val y0 = densityCurves[low * 3 + channel]
val y1 = densityCurves[high * 3 + channel]
return y0 * (1f - t) + y1 * t
}
private fun pow10(value: Float): Float = 10.0.pow(value.toDouble()).toFloat()
private fun log10(value: Float): Float = (ln(value.toDouble()) / LN_10).toFloat()
private fun encodeProPhoto(value: Float): Float {
val clamped = value.coerceAtLeast(0f)
val encoded = if (clamped < 0.001953125f) {
clamped * 16f
} else {
clamped.toDouble().pow(1.0 / 1.8).toFloat()
}
return encoded.coerceIn(0f, 1f)
}
private const val LN_10 = 2.302585092994046
}
@@ -0,0 +1,281 @@
package com.hinnka.mycamera.raw
import android.content.Context
import android.os.SystemClock
import com.hinnka.mycamera.utils.PLog
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.FilterInputStream
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.security.DigestInputStream
import java.security.MessageDigest
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
internal data class SpectralModelAsset(
val path: String,
val sha256: String,
val compressedBytes: Int,
val uncompressedBytes: Int,
)
internal data class SpectralRuntimeRequest(
val algorithm: String,
val upstreamCommit: String,
val size: Int,
val inputScale: Float,
val printInputScale: Float,
val shared: SpectralModelAsset,
val film: SpectralModelAsset,
val paperName: String,
val paper: SpectralModelAsset?,
val positive: Boolean,
) {
private val context = "schema4:$algorithm:$upstreamCommit:ProPhoto RGB:$size:$inputScale:$printInputScale"
val sharedKey = digest("$context:shared:${shared.sha256}")
val modelFilmKey = digest("$sharedKey:film:${film.sha256}:positive=$positive")
val filmKey = digest("$modelFilmKey:film-stage")
val printKey: String? = paper?.let { digest("$modelFilmKey:print-stage:$paperName:${it.sha256}") }
}
private fun digest(value: String): String = hex(MessageDigest.getInstance("SHA-256").digest(value.toByteArray(Charsets.UTF_8)))
private fun hex(value: ByteArray): String = value.joinToString("") { "%02x".format(it.toInt() and 0xff) }
/** The only JNI entry point. Calls are serialized by SpektrafilmRuntime. */
internal object SpektrafilmNativeBridge {
init { System.loadLibrary("my-native-lib") }
external fun generate(
sharedKey: String,
filmKey: String,
sharedData: ByteArray?,
filmData: ByteArray?,
paperName: String,
paperData: ByteArray?,
positive: Boolean,
buildFilm: Boolean,
buildPrint: Boolean,
): Array<FloatArray>
}
/** Native source models are retained outside Java heap; only the active pair of LUTs is retained by the caller. */
internal object SpektrafilmRuntime {
const val MAX_MODEL_BYTES = 64 * 1024 * 1024
private const val TAG = "SpektrafilmRuntime"
private const val CACHE_DIRECTORY = "spektrafilm-spectral-v1"
private const val CACHE_MAGIC = 0x53504b33
private const val CACHE_FORMAT = 1
private const val CACHE_ENTRIES = 8
private const val BUFFER_SIZE = 64 * 1024
private const val FLOATS_PER_BLOCK = BUFFER_SIZE / 4
private const val MAX_CACHE_FILE_BYTES = 65L * 65 * 65 * 4 * 4 + 64 * 1024
private var loadedSharedKey: String? = null
private var loadedFilmKey: String? = null
@Synchronized
fun load(
context: Context,
request: SpectralRuntimeRequest,
currentFilm: SpectralLutTable?,
currentPrint: SpectralLutTable?,
): Pair<SpectralLutTable, SpectralLutTable?> {
val started = SystemClock.elapsedRealtime()
val directory = File(context.cacheDir, CACHE_DIRECTORY)
val film = currentFilm?.takeIf { it.sourceKey == request.filmKey }
?: readCache(directory, request.filmKey, request.size)
val print = request.printKey?.let { key ->
currentPrint?.takeIf { it.sourceKey == key } ?: readCache(directory, key, request.size)
}
// In-memory reuse is still an LRU access. In particular, switching
// papers repeatedly must not evict the continuously used film stage.
val accessedAt = System.currentTimeMillis()
film?.let { cacheFile(directory, it.sourceKey).setLastModified(accessedAt) }
print?.let { cacheFile(directory, it.sourceKey).setLastModified(accessedAt) }
val buildFilm = film == null
val buildPrint = request.paper != null && print == null
if (!buildFilm && !buildPrint) {
PLog.d(TAG, "Spektrafilm cacheHit, filmKey=${request.filmKey}, printKey=${request.printKey}, " +
"elapsed=${SystemClock.elapsedRealtime() - started}ms, upstream=${request.upstreamCommit}")
return requireNotNull(film) to print
}
// These temporary arrays live only through generate(). In particular the
// shared spectral basis is never stored in a Java-side model cache.
val generated = try {
val sharedChanged = loadedSharedKey != request.sharedKey
val sharedBytes = if (sharedChanged) loadModel(context, request.shared) else null
val filmBytes = if (sharedChanged || loadedFilmKey != request.modelFilmKey) {
loadModel(context, request.film)
} else null
val paperBytes = if (buildPrint) loadModel(context, requireNotNull(request.paper)) else null
val result = SpektrafilmNativeBridge.generate(
request.sharedKey, request.modelFilmKey, sharedBytes, filmBytes,
request.paperName, paperBytes, request.positive, buildFilm, buildPrint,
)
require(result.size == 2) { "Invalid native Spektrafilm stage count" }
validateGenerated(result[0], request.size, buildFilm)
validateGenerated(result[1], request.size, buildPrint)
loadedSharedKey = request.sharedKey
loadedFilmKey = request.modelFilmKey
result
} catch (failure: Throwable) {
// Native also invalidates models on failure. Never subsequently pass
// null payloads based on a partially completed model installation.
loadedSharedKey = null
loadedFilmKey = null
throw failure
}
val filmResult = film ?: SpectralLutTable(request.filmKey, request.size, generated[0]).also {
writeCache(directory, it)
}
val printResult = print ?: request.printKey?.let { key ->
SpectralLutTable(key, request.size, generated[1]).also { writeCache(directory, it) }
}
PLog.d(TAG, "Spektrafilm generated, film=$buildFilm, print=$buildPrint, " +
"filmKey=${request.filmKey}, printKey=${request.printKey}, " +
"elapsed=${SystemClock.elapsedRealtime() - started}ms, upstream=${request.upstreamCommit}")
return filmResult to printResult
}
private fun validateGenerated(values: FloatArray, size: Int, built: Boolean) {
require(values.size == if (built) size * size * size * 4 else 0) { "Invalid native Spektrafilm stage length" }
require(values.all { it.isFinite() }) { "Non-finite native Spektrafilm stage value" }
for (index in 3 until values.size step 4) {
require(values[index] == 1f) { "Invalid native Spektrafilm stage alpha" }
require(values[index - 3] in 0f..1f && values[index - 2] in 0f..1f && values[index - 1] in 0f..1f) {
"Out-of-domain Spektrafilm stage RGB value"
}
}
}
private class CountedInput(input: InputStream, private val limit: Int) : FilterInputStream(input) {
var count = 0
private set
override fun read(): Int = super.read().also { if (it != -1) add(1) }
override fun read(bytes: ByteArray, offset: Int, length: Int): Int =
`in`.read(bytes, offset, length).also { if (it > 0) add(it) }
private fun add(amount: Int) {
require(amount <= limit - count) { "Spektrafilm compressed model exceeds declared length" }
count += amount
}
}
private fun loadModel(context: Context, asset: SpectralModelAsset): ByteArray {
require(asset.uncompressedBytes in 1..MAX_MODEL_BYTES && asset.compressedBytes in 1..MAX_MODEL_BYTES)
val bytes = ByteArray(asset.uncompressedBytes)
val hash = MessageDigest.getInstance("SHA-256")
CountedInput(context.assets.open("spektrafilm/${asset.path}"), asset.compressedBytes).use { counted ->
DigestInputStream(counted, hash).use { compressed ->
GZIPInputStream(compressed, BUFFER_SIZE).use { input ->
var offset = 0
while (offset < bytes.size) {
val read = input.read(bytes, offset, bytes.size - offset)
require(read > 0) { "Truncated Spektrafilm source model: ${asset.path}" }
offset += read
}
require(input.read() == -1) { "Excess Spektrafilm source model payload: ${asset.path}" }
// Gzip validates CRC on EOF. Hash the complete compressed
// asset as well, including any bytes after its last member.
val tail = ByteArray(BUFFER_SIZE)
while (compressed.read(tail) != -1) { /* update digest and bounded byte count */ }
require(counted.count == asset.compressedBytes) { "Truncated compressed model: ${asset.path}" }
}
}
}
require(hex(hash.digest()) == asset.sha256) { "Spektrafilm source checksum mismatch: ${asset.path}" }
return bytes
}
private fun cacheFile(directory: File, key: String) = File(directory, "$key.lut.gz")
private fun readCache(directory: File, key: String, size: Int): SpectralLutTable? {
val file = cacheFile(directory, key)
if (!file.isFile) return null
return try {
require(file.length() in 1..MAX_CACHE_FILE_BYTES) { "Invalid LUT cache file size" }
val values = FloatArray(size * size * size * 4)
DataInputStream(GZIPInputStream(file.inputStream(), BUFFER_SIZE).buffered(BUFFER_SIZE)).use { input ->
require(input.readInt() == CACHE_MAGIC && input.readInt() == CACHE_FORMAT) { "Unsupported LUT cache header" }
require(input.readUTF() == key && input.readInt() == size && input.readInt() == values.size) {
"LUT cache identity or size mismatch"
}
val block = ByteArray(BUFFER_SIZE)
val floats = ByteBuffer.wrap(block).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer()
var offset = 0
while (offset < values.size) {
val count = minOf(FLOATS_PER_BLOCK, values.size - offset)
input.readFully(block, 0, count * 4)
floats.position(0)
floats.get(values, offset, count)
offset += count
}
require(input.read() == -1) { "Excess LUT cache payload" }
}
validateGenerated(values, size, true)
file.setLastModified(System.currentTimeMillis())
SpectralLutTable(key, size, values)
} catch (failure: Exception) {
file.delete()
PLog.w(TAG, "Discarded invalid Spektrafilm cache key=$key: ${failure.message}")
null
}
}
private fun writeCache(directory: File, table: SpectralLutTable) {
var temporary: File? = null
try {
check(directory.isDirectory || directory.mkdirs()) { "Cannot create LUT cache directory" }
temporary = File.createTempFile("stage-", ".tmp", directory)
FileOutputStream(temporary).use { raw ->
GZIPOutputStream(raw, BUFFER_SIZE).use { gzip ->
val output = DataOutputStream(gzip.buffered(BUFFER_SIZE))
output.writeInt(CACHE_MAGIC)
output.writeInt(CACHE_FORMAT)
output.writeUTF(table.sourceKey)
output.writeInt(table.size)
output.writeInt(table.values.size)
val block = ByteArray(BUFFER_SIZE)
val floats = ByteBuffer.wrap(block).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer()
var offset = 0
while (offset < table.values.size) {
val count = minOf(FLOATS_PER_BLOCK, table.values.size - offset)
floats.position(0)
floats.put(table.values, offset, count)
output.write(block, 0, count * 4)
offset += count
}
output.flush()
gzip.finish()
gzip.flush()
raw.fd.sync()
}
}
check(temporary.renameTo(cacheFile(directory, table.sourceKey))) { "Cannot atomically install LUT cache" }
pruneCache(directory)
} catch (failure: Exception) {
// Cache availability is optional: a verified generated stage remains
// usable when Android has evicted cache storage or disk space is low.
PLog.w(TAG, "Cannot persist Spektrafilm LUT key=${table.sourceKey}: ${failure.message}")
} finally {
temporary?.delete()
}
}
private fun pruneCache(directory: File) {
val files = directory.listFiles().orEmpty()
files.filter { it.name.endsWith(".tmp") }.forEach { it.delete() }
val tables = files.filter { it.name.endsWith(".lut.gz") }.sortedByDescending { it.lastModified() }
var retainedBytes = 0L
tables.forEachIndexed { index, file ->
if (index >= CACHE_ENTRIES || retainedBytes + file.length() > CACHE_ENTRIES * MAX_CACHE_FILE_BYTES) {
file.delete()
} else {
retainedBytes += file.length()
}
}
}
}
@@ -7,9 +7,14 @@ import java.nio.ByteOrder
internal object SpektrafilmToneShader {
val SPECTRAL_FILM_COMBINED_UNIFORMS = """
uniform sampler3D uSpectralFilmTexture;
uniform highp sampler3D uSpectralFilmTexture;
uniform highp sampler3D uSpectralPrintTexture;
uniform mat3 uOutputTransform;
uniform int uSpectralFilmSize;
uniform int uSpectralPrintSize;
uniform float uSpectralInputScale;
uniform float uSpectralPrintInputScale;
uniform vec3 uSpectralNegativeDensityGains;
""".trimIndent()
val SPECTRAL_FILM_COMBINED_FUNCTIONS = """
vec3 linearToProPhoto(vec3 color) {
@@ -28,19 +33,34 @@ internal object SpektrafilmToneShader {
return mix(lowPart, highPart, isHigh);
}
vec3 spectralLutCoordinate(vec3 value, int size) {
// Model samples span lattice indices 0..N-1; GL samples texel centers.
float lutSize = float(size);
return (clamp(value, 0.0, 1.0) * (lutSize - 1.0) + 0.5) / lutSize;
}
vec3 applySpectralFilm(vec3 color) {
if (uSpectralFilmSize <= 1) {
return color;
}
vec3 normalizedColor = color / 2.88;
vec3 encodedColor = linearToProPhoto(normalizedColor);
// .cube samples span lattice indices 0..N-1; GL samples texel centers.
// Direct normalized coordinates clamp the first/last half texel,
// flattening shadows independently in each color channel.
float lutSize = float(uSpectralFilmSize);
vec3 lutCoord = (clamp(encodedColor, 0.0, 1.0) * (lutSize - 1.0) + 0.5) / lutSize;
vec3 lutResult = texture(uSpectralFilmTexture, lutCoord).rgb;
return proPhotoToLinear(lutResult);
vec3 encodedColor = linearToProPhoto(color / uSpectralInputScale);
vec3 filmResult = texture(
uSpectralFilmTexture,
spectralLutCoordinate(encodedColor, uSpectralFilmSize)
).rgb;
if (uSpectralPrintSize > 1) {
// The film LUT contains normalized CMY densities. Apply the user's
// negative-density gain before the independent print/scanner LUT.
// Its lattice spans 0..1.5 to cover every supported density gain.
vec3 printInput = filmResult * uSpectralNegativeDensityGains / uSpectralPrintInputScale;
filmResult = texture(
uSpectralPrintTexture,
spectralLutCoordinate(printInput, uSpectralPrintSize)
).rgb;
}
// Positive film LUTs already include scanning; both paths end in
// encoded ProPhoto RGB and share the same linear output contract.
return proPhotoToLinear(filmResult);
}
vec3 applyEngineTone(vec3 color) {
@@ -57,107 +77,98 @@ internal object SpektrafilmToneShader {
internal class SpektrafilmToneAlgorithm(quad: RawFullscreenQuad) :
RawRenderingEngineToneAlgorithm(quad, SpektrafilmToneShader.DEFINITION) {
private var textureId = 0
private var textureKey: String? = null
// Shared tone resources occupy 0 (input), 7 (gain table), 2 (HDR coordinate),
// and 4 (HDR base curve). Keep both 3D samplers explicit on every draw.
private val filmTexture = LutTexture(6, "film")
private val printTexture = LutTexture(5, "print")
override fun bindEngineResources(program: Int, input: RawEngineTonePass.Input) {
super.bindEngineResources(program, input)
val lut = input.spectralFilmLut
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uSpectralFilmTexture"), 6)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(program, "uSpectralFilmSize"),
lut?.size ?: 1,
)
GLES30.glActiveTexture(GLES30.GL_TEXTURE6)
GLES30.glBindTexture(
GLES30.GL_TEXTURE_3D,
lut?.let(::ensureTexture) ?: ensureFallbackTexture(),
filmTexture.bind(program, "uSpectralFilmTexture", lut?.filmTable)
printTexture.bind(program, "uSpectralPrintTexture", lut?.printTable)
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uSpectralFilmSize"), lut?.size ?: 1)
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, "uSpectralPrintSize"), lut?.printTable?.size ?: 1)
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uSpectralInputScale"), lut?.inputScale ?: 1f)
GLES30.glUniform1f(GLES30.glGetUniformLocation(program, "uSpectralPrintInputScale"), lut?.printInputScale ?: 1f)
val gains = lut?.negativeDensityGains
GLES30.glUniform3f(
GLES30.glGetUniformLocation(program, "uSpectralNegativeDensityGains"),
gains?.get(0) ?: 1f, gains?.get(1) ?: 1f, gains?.get(2) ?: 1f,
)
RawGlesProgram.logErrors("SpektrafilmToneAlgorithm.bindEngineResources")
}
override fun releaseEngineResources() {
if (textureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(textureId), 0)
textureId = 0
}
textureKey = null
filmTexture.release()
printTexture.release()
}
private fun ensureTexture(lut: SpectralFilmLut): Int {
val key = "${lut.sourceKey}:${lut.size}:${lut.values.size}"
if (textureId != 0 && textureKey == key) return textureId
if (textureId == 0) {
textureId = IntArray(1).also { GLES30.glGenTextures(1, it, 0) }[0]
private class LutTexture(private val unit: Int, private val stage: String) {
private var textureId = 0
private var textureKey: String? = null
fun bind(program: Int, uniform: String, table: SpectralLutTable?) {
GLES30.glUniform1i(GLES30.glGetUniformLocation(program, uniform), unit)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit)
val key = table?.sourceKey ?: FALLBACK_KEY
if (textureId == 0 || textureKey != key) upload(table, key)
GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, textureId)
}
val buffer = ByteBuffer.allocateDirect(lut.values.size * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.apply {
put(lut.values)
position(0)
fun release() {
if (textureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(textureId), 0)
textureId = 0
}
GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, textureId)
configureTexture(GLES30.GL_LINEAR)
GLES30.glTexImage3D(
GLES30.GL_TEXTURE_3D,
0,
GLES30.GL_RGBA16F,
lut.size,
lut.size,
lut.size,
0,
GLES30.GL_RGBA,
GLES30.GL_FLOAT,
buffer,
)
textureKey = key
PLog.d(
TAG,
"Uploaded spectral film LUT: ${lut.name}, type=${lut.type}, " +
"refLight=${lut.referenceIlluminant}, viewLight=${lut.viewingIlluminant}, " +
"size=${lut.size}, format=RGBA16F, sampling=texel-center/highp, " +
"linearPipeline=highp-sampler2D, source=${lut.sourceKey}",
)
return textureId
}
private fun ensureFallbackTexture(): Int {
if (textureId != 0 && textureKey == FALLBACK_KEY) return textureId
if (textureId == 0) {
textureId = IntArray(1).also { GLES30.glGenTextures(1, it, 0) }[0]
textureKey = null
}
val buffer = ByteBuffer.allocateDirect(4 * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.apply {
put(floatArrayOf(0f, 1f, 1f, 1f))
position(0)
}
GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, textureId)
configureTexture(GLES30.GL_NEAREST)
GLES30.glTexImage3D(
GLES30.GL_TEXTURE_3D,
0,
GLES30.GL_RGBA16F,
1,
1,
1,
0,
GLES30.GL_RGBA,
GLES30.GL_FLOAT,
buffer,
)
textureKey = FALLBACK_KEY
return textureId
}
private fun configureTexture(filter: Int) {
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_MIN_FILTER, filter)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_MAG_FILTER, filter)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_R, GLES30.GL_CLAMP_TO_EDGE)
private fun upload(table: SpectralLutTable?, key: String) {
val size = table?.size ?: 1
val limit = IntArray(1)
GLES30.glGetIntegerv(GLES30.GL_MAX_3D_TEXTURE_SIZE, limit, 0)
require(size <= limit[0]) { "Spektrafilm $stage LUT size $size exceeds GL_MAX_3D_TEXTURE_SIZE=${limit[0]}" }
val values = table?.values ?: floatArrayOf(0f, 0f, 0f, 1f)
require(values.size == size * size * size * 4) { "Invalid Spektrafilm $stage lattice size" }
if (textureId == 0) {
textureId = IntArray(1).also { GLES30.glGenTextures(1, it, 0) }[0]
check(textureId != 0) { "Unable to allocate Spektrafilm $stage texture" }
}
textureKey = null
// Only allocate/upload when the source asset changes, never for density
// adjustments or subsequent frames. Null stages bind a valid 1³ texture.
val buffer = ByteBuffer.allocateDirect(values.size * Float.SIZE_BYTES)
.order(ByteOrder.nativeOrder()).asFloatBuffer().apply {
put(values)
position(0)
}
GLES30.glBindTexture(GLES30.GL_TEXTURE_3D, textureId)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_3D, GLES30.GL_TEXTURE_WRAP_R, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glBindBuffer(GLES30.GL_PIXEL_UNPACK_BUFFER, 0)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ALIGNMENT, 4)
GLES30.glPixelStorei(GLES30.GL_UNPACK_ROW_LENGTH, 0)
GLES30.glPixelStorei(GLES30.GL_UNPACK_IMAGE_HEIGHT, 0)
GLES30.glPixelStorei(GLES30.GL_UNPACK_SKIP_PIXELS, 0)
GLES30.glPixelStorei(GLES30.GL_UNPACK_SKIP_ROWS, 0)
GLES30.glPixelStorei(GLES30.GL_UNPACK_SKIP_IMAGES, 0)
GLES30.glTexImage3D(
GLES30.GL_TEXTURE_3D, 0, GLES30.GL_RGBA16F, size, size, size, 0,
GLES30.GL_RGBA, GLES30.GL_FLOAT, buffer,
)
val error = GLES30.glGetError()
check(error == GLES30.GL_NO_ERROR) {
"Spektrafilm $stage LUT upload failed: GL error=0x${error.toString(16)}, size=$size, format=RGBA16F, unit=$unit"
}
textureKey = key
PLog.d(TAG, "Uploaded Spektrafilm $stage LUT: size=$size, format=RGBA16F, " +
"sampling=texel-center/highp, pipeline=film-density-print, " +
"linearPipeline=highp-sampler2D, unit=$unit, source=$key")
}
}
private companion object {