Initial commit: ArgyllCMS v3.5.0 and multichannel profiling research

This commit is contained in:
2026-10-31 14:27:14 +03:30
commit 66f664fc82
1828 changed files with 1123613 additions and 0 deletions

91
Argyll_V3.5.0/imdi/Jamfile Executable file
View File

@@ -0,0 +1,91 @@
# JAM style makefile for integer interpolation code, cctiff etc.
#PREF_CCFLAGS += $(CCOPTFLAG) ; # Turn optimisation on
PREF_CCFLAGS += $(CCDEBUGFLAG) ; # Debugging flags
#PREF_CCFLAGS += $(CCPROFFLAG) ; # Profile flags
PREF_LINKFLAGS += $(LINKDEBUGFLAG) ; # Link debugging flags
#PREF_LINKFLAGS += $(LINKPROFFLAG) ; # Profile flags
#PREF_CCFLAGS += $(CCHEAPDEBUG) ; # Heap Debugging flags
#Products
Libraries = libimdi ;
Executables = cctiff greytiff ;
Headers = imdi.h ;
#Install
InstallBin $(DESTDIR)$(PREFIX)/bin : $(Executables) ;
#InstallFile $(DESTDIR)$(PREFIX)/h : $(Headers) ;
#InstallLib $(DESTDIR)$(PREFIX)/lib : $(Libraries) ;
HDRS = ../h ;
# Hack! Make cross compile of MingW64 on 32 bit host work.
# (This doesn't work - 32 bit libraries are not provided :-()
#if $(NT) && $(MINGW64) {
# ObjectCcFlags ctest imdi_make imdi_gen cgen : -m32 ;
# MainLinkFlags ctest imdi_make : -m32 -L $(MINGW64_LIB32) ;
#}
if $(NT) && $(MINGW64) {
IMDI_MAKE_OPT = -f ; # Force 64 bits
}
# imdi low level cgen test code
Main ctest : ctest.c cgen.c ;
# make imdi code program
Main imdi_make : imdi_make.c imdi_gen.c cgen.c ;
HDRS = ../h ../numlib ;
LINKLIBS = ../numlib/libnum ;
# GenFile source.c : program args ; make custom file
# Generate all the kernel files
GenFileND imdi_k.h : imdi_make $(IMDI_MAKE_OPT) -d [ NormPaths $(DOT) ] ;
# imdi library
Library libimdi : imdi.c imdi_tab.c ;
HDRS += ../icc ../rspl ../gamut ../cgats ../spectro ;
LINKLIBS = $(LINKLIBS) libimdi ../icc/libicc ../numlib/libnum ;
# imdi test code
Main itest : itest.c refi.c : : : ../rspl : : ../rspl/librspl ../plot/libplot
../plot/libvrml ../numlib/libui ;
# TIFF file color correction utlity
Main cctiff : cctiff.c : : : ../xicc $(TIFFINC) $(JPEGINC) : : ../xicc/libxicc ../rspl/librspl ../cgats/libcgats ../plot/libplot ../plot/libvrml ../numlib/libui $(TIFFLIB) $(JPEGLIB) ;
# Old TIFF file color correction utlity
#Main cctiffo : cctiffo.c : : : $(TIFFINC) : : $(TIFFLIB) ;
# TIFF file monochrome conversion utlity
#Main greytiff : greytiff.c ;
Main greytiff : greytiff.c : : : ../spectro ../xicc ../gamut ../rspl ../cgats $(TIFFINC)
: : ../xicc/libxicc ../gamut/libgamut ../rspl/librspl ../cgats/libcgats
../plot/libplot ../plot/libvrml ../numlib/libui $(TIFFLIB) $(JPEGLIB) ;
# ssort generation code
#Main ssort : ssort.c ;
#Main shsort : shsort.c ;
# code generated by shsort
#Main ttt : ttt.c ;
if $(BUILD_JUNK) {
Main f2test : f2test.c : : : ../spectro ../xicc ../gamut ../rspl ../cgats $(TIFFINC)
: : ../xicc/libxicc ../gamut/libgamut ../rspl/librspl ../cgats/libcgats
../plot/libplot ../plot/libvrml $(TIFFLIB) $(JPEGLIB) ;
CCFLAGS += -msse3 ;
Main tvec : tvec.c ;
Main tvec2 : tvec2.c ;
# test code
Main tsort : tsort.c ;
}

662
Argyll_V3.5.0/imdi/License.txt Executable file
View File

@@ -0,0 +1,662 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<http://www.gnu.org/licenses/>.

View File

@@ -0,0 +1,66 @@
# Boilerplate Makefile for compiling imdi
# Copyright 2000 - 2007 Graeme W. Gill
# This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
# see the License.txt file for licencing details.
# "include" the right environment for your system,
# by uncommenting the appropriate line:
# Microsoft VC++, WinNT setup
include Makefile.WNT
# Generic UNIX setup
#include Makefile.UNIX
# Apple OS X
#include Makefile.OSX
###############################
#Set optimisation on
CCFLAGS = $(CCFLAGSDEF) $(CCOPTFLAG) $(CCDEFINES) $(BCONFIG)
#Set debugging on
#CCFLAGS = $(CCFLAGSDEF) $(CCDEBUGFLAG) $(CCDEFINES) $(BCONFIG)
# debugging #define
#CCFLAGS = $(CCFLAGSDEF) $(CCDEBUGFLAG) $(CCDEFINES) $(DEFFLAG)DEBUG
LINKFLAGS = $(LINKFLAGSDEF) $(LINKDEBUGFLAG)
STDHDRS = $(INCFLAG)$(STDHDRSDEF)
all:: libimdi$(SUFLIB)
# Used by both code generator and runtime
imdi_make$(SUFEXE): imdi_make$(SUFOBJ) imdi_gen$(SUFOBJ) cgen$(SUFOBJ)
$(LINK) $(LINKOF)imdi_make$(SUFEXE) imdi_make$(SUFOBJ) imdi_gen$(SUFOBJ) cgen$(SUFOBJ)
# The code generator program
cgen$(SUFOBJ): cgen.c imdi_utl.h imdi_arch.h imdi_gen.h imdi_tab.h
$(CC) cgen.c
imdi_gen$(SUFOBJ): imdi_gen.c imdi_utl.h imdi_arch.h imdi_gen.h
$(CC) imdi_gen.c
# Generate the kernel files
imdi_k.h imdi_k.c : imdi_make$(SUFEXE)
.$(SLASH)imdi_make$(SUFEXE)
# imdi runtime library
imdi$(SUFOBJ): imdi.c imdi.h imdi_tab.h imdi_k.h imdi_k.c
$(CC) imdi.c
libimdi$(SUFLIB): imdi$(SUFOBJ) imdi_tab$(SUFOBJ)
$(LIBU) $(LIBOF)$@ imdi$(SUFOBJ) imdi_tab$(SUFOBJ)
$(RANLIB) libimdi$(SUFLIB)

View File

@@ -0,0 +1,42 @@
# MAC OSX, derived from UNIX setup
# Copyright 2000 - 2007 Graeme W. Gill
# This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
# see the License.txt file for licencing details.
SLASH = /
SUFLIB = .a
SUFOBJ = .o
SUFEXE =
CMDSEP = ;
INCFLAG = -I
DEFFLAG = -D
UNDEFFLAG = -U
CCOPTFLAG = -O
CCDEBUGFLAG = -g
CCPROFFLAG =
LINKDEBUGFLAG =
LINKPROFFLAG =
STDHDRSDEF = /usr/include
MAKEU = make
LIBU = ar -r
LIBOF =
RANLIB = ranlib
AS = as
CCFLAGSDEF = -DUNIX -c
CC = cc $(CCFLAGS) $(STDHDRS)
CCOF = -o
LINKFLAGSDEF = -lm
LINKLIBS =
LINK = cc $(LINKFLAGS) $(LINKLIBS)
LINKOF = -o
.SUFFIXES:
.SUFFIXES: .c $(SUFLIB) $(SUFOBJ) $(SUFEXE)
.c$(SUFOBJ):
$(CC) $(CCOF)$*$(SUFOBJ) $<

View File

@@ -0,0 +1,42 @@
# Generic UNIX setup
# Copyright 2000 - 2007 Graeme W. Gill
# This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
# see the License.txt file for licencing details.
SLASH = /
SUFLIB = .a
SUFOBJ = .o
SUFEXE =
CMDSEP = ;
INCFLAG = -I
DEFFLAG = -D
UNDEFFLAG = -U
CCOPTFLAG = -O
CCDEBUGFLAG = -g
CCPROFFLAG =
LINKDEBUGFLAG =
LINKPROFFLAG =
STDHDRSDEF = /usr/include
MAKEU = make
LIBU = ar -r
LIBOF =
RANLIB = echo
AS = as
CCFLAGSDEF = -DUNIX -c
CC = cc $(CCFLAGS) $(STDHDRS)
CCOF = -o
LINKFLAGSDEF = -lm
LINKLIBS =
LINK = cc $(LINKFLAGS) $(LINKLIBS)
LINKOF = -o
.SUFFIXES:
.SUFFIXES: .c $(SUFLIB) $(SUFOBJ) $(SUFEXE)
.c$(SUFOBJ):
$(CC) $(CCOF)$*$(SUFOBJ) $<

View File

@@ -0,0 +1,42 @@
# Microsoft VC++, WinNT setup
# Copyright 2000 - 2007 Graeme W. Gill
# This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
# see the License.txt file for licencing details.
SLASH = \
SUFLIB = .lib
SUFOBJ = .obj
SUFEXE = .exe
CMDSEP = &
INCFLAG = /I
DEFFLAG = /D
UNDEFFLAG = /U
CCOPTFLAG = /Ox /GB
CCDEBUGFLAG = /Z7 /Od
CCPROFFLAG = /Z7
LINKDEBUGFLAG = /DEBUG
LINKPROFFLAG = /PROFILE
STDHDRSDEF = $(MSVCNT)\include
MAKEU = nmake
LIBU = lib
LIBOF = /OUT:
RANLIB = rem
AS = masm386
CCFLAGSDEF = /DNT /c
CC = cl /nologo $(CCFLAGS) $(STDHDRS)
CCOF = /Fo
LINKLIBS = $(MSVCNT)/lib/user32.lib $(MSVCNT)/lib/gdi32.lib
LINKFLAGSDEF = /link /INCREMENTAL:NO
LINK = link $(LINKFLAGS)
LINKOF = /OUT:
.SUFFIXES:
.SUFFIXES: .c $(SUFLIB) $(SUFOBJ) $(SUFEXE)
.c$(SUFOBJ):
$(CC) $(CCOF)$*$(SUFOBJ) $<

114
Argyll_V3.5.0/imdi/Readme.txt Executable file
View File

@@ -0,0 +1,114 @@
This is the development area for IMDI, the
Integer Multi-Dimensional Interpolation routines.
They provide a flexible and high performance
system for applying color transforms to typical
raster pixel data. Because they provide a means of
applying arbitrary combination dependent mappings
of multi-channel pixel data, there are many other
possible uses for these sorts of routines as well,
including high quality matting/compositing. For instance,
one could create a smooth, proportional "chroma key"
type of matt for matting one RGB image onto another
by creating a 6 channel to 3 dimensional transform,
that its applied to each pair of pixels from the
source images and produces one combined output pixel.
Additional input or output alpha channels are easy
to add by simply adding more input and/or output
dimensions. The matting calculatons can be almost
arbitrarily complex, and the imdi will apply them
to the pixel data at very high speed.
The system has two parts, one that generates taylored,
optimised source code for the transformation kernels,
and the run time code that matches a transform request
to a compiled kernel, and initialises the appropriate
run time lookup tables.
The kernel source generator is intended to accomodate
various optimisations, such as assembly code, vector
instruction set (ie. MMX, AltiVec etc.) versions, but
at present only generates the more portable 'C' code
kernels.
Both 8 bit per component and 16 bit per component
pixel data is handled, up to 8 input and output
dimensions (but this limit could be trivially raised).
imdi_make.exe is the module that triggers the generation of
optimised source code as configured for the color spaces
and pixel formats selected. By default creates
a single imdi_k.c and imdi_k.h file, but if
given the -i flag, creates a separate file
for each kernel variant.
cgen.c C code generator module.
itest.c regresion test routine.
Normally runs speed and accuracy tests for
all configured kernel variants.
The -q flag makes it run quicker,
but makes the benchmarking inacurate,
the -s flag will cause it to stop
if any routine has unexpectedly low
accuracy.
cctiff.c is the utility that takes an ICC device
profile link, and converts a TIFF file
from the input colorspace to the output
space. Both 8 bit and 16 bit TIFF files
are handled, as well as colorspaces up to
8 channels in and out.
This accepts either a device link ICC profile,
or links an input and output devce ICC profile
to define the color transform.
greytiff.c is a utility similar to cctiff, that
is an example of how to colorimetrically
convert an RGB file into a monochrome RGB file.
Misc. Notes
-----------
ITU-T Rec. T.42 specifies the ITULAB encoding in terms of a range
and offset for each component, which are related to the minimum and
maximum values as follows:
minimum = - (range x offset) / 2^n - 1
maximum = minimum + range
The Decode field default values depend on the color space. For the
ITULAB color space encoding, the default values correspond to the
base range and offset, as specified in ITU-T Rec. T.42 [T.42]. The
following table gives the base range and offset values for
BitsPerSample=8 and 12, and the corresponding default minimum and
maximum default values for the Decode field, calculated using the
equations above when PhotometricInterpetation=10.
+-----------------------------------------------+
| ITU-T Rec. T.42 | Decode |
+---------+-----------| base values | default values |
| BitsPer + Component +------------------+----------------------------+
| -Sample | | Range | Offset | Min | Max |
+---------+-----------+--------+---------+--------------+-------------+
| 8 | L* | 100 | 0 | 0 | 100 |
| +-----------+--------+---------+--------------+-------------+
| | a* | 170 | 128 | -21760/255 | 21590/255 |
| +-----------+--------+---------+--------------+-------------+
| | b* | 200 | 96 | -19200/255 | 31800/255 |
+---------+-----------+--------+---------+--------------+-------------+
| 12 | L* | 100 | 0 | 0 | 100 |
| +-----------+--------+---------+--------------+-------------+
| | a* | 170 | 2048 | -348160/4095 | 347990/4095 |
| +-----------+--------+---------+--------------+-------------+
| | b* | 200 | 1536 | -307200/4095 | 511800/4095 |
+---------+-----------+--------+---------+--------------+-------------+
For example, when PhotometricInterpretation=10 and BitsPerSample=8,
the default value for Decode is (0, 100, -21760/255, 21590/255,
-19200/255, 31800/255).

26
Argyll_V3.5.0/imdi/afiles Executable file
View File

@@ -0,0 +1,26 @@
Readme.txt
License.txt
afiles
Jamfile
Makefile
Makefile.OSX
Makefile.UNIX
Makefile.WNT
cctiff.c
cctiffo.c
greytiff.c
cgen.c
ctest.c
imdi.c
imdi.h
imdi_make.c
imdi_arch.h
imdi_gen.h
imdi_gen.c
imdi_utl.h
imdi_tab.c
imdi_tab.h
itest.c
refi.c
refi.h
ssort.c

2393
Argyll_V3.5.0/imdi/cctiff.c Normal file

File diff suppressed because it is too large Load Diff

1097
Argyll_V3.5.0/imdi/cctiffo.c Normal file

File diff suppressed because it is too large Load Diff

2150
Argyll_V3.5.0/imdi/cgen.c Normal file

File diff suppressed because it is too large Load Diff

156
Argyll_V3.5.0/imdi/ctest.c Normal file
View File

@@ -0,0 +1,156 @@
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
/* Test frame for cgen.c IMDI generation code */
/*
* Copyright 2000 - 2006 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
#include "imdi.h"
#include "imdi_tab.h"
int
main(void) {
int rv;
genspec gs, ogs;
tabspec ts, ots;
mach_arch ar;
FILE *kcode;
/* Zero out the gen and tabspecs, to give diff a place to start */
memset((void *)&ogs, 0, sizeof(genspec));
memset((void *)&gs, 0, sizeof(genspec));
memset((void *)&ots, 0, sizeof(tabspec));
memset((void *)&ts, 0, sizeof(tabspec));
printf("Testing gen_c_kernel\n");
if ((kcode = fopen("imdi_k99.c","w")) == NULL) {
printf("Couldn't open 'imdi_k99.c'\n");
return -1;
}
/* Setup an interpolation kernel specification */
gs.id = 4; /* Number of input dimensions */
gs.in.pint = 1; /* Flag - nonz if pixel interleaved */
gs.in.packed = 0; /* Flag - nonz if channels packed into one read */
gs.in.bpch[0] = 8; /* Bits per channel */
gs.in.chi[0] = 4; /* Channel increment */
gs.in.bov[0] = 0; /* Bit offset to value within channel */
gs.in.bpv[0] = 8; /* Bits per value within channel */
gs.in.bpch[1] = 8; /* Bits per channel */
gs.in.chi[1] = 4; /* Channel increment */
gs.in.bov[1] = 0; /* Bit offset to value within channel */
gs.in.bpv[1] = 8; /* Bits per value within channel */
gs.in.bpch[2] = 8; /* Bits per channel */
gs.in.chi[2] = 4; /* Channel increment */
gs.in.bov[2] = 0; /* Bit offset to value within channel */
gs.in.bpv[2] = 8; /* Bits per value within channel */
gs.in.bpch[3] = 8; /* Bits per channel */
gs.in.chi[3] = 4; /* Channel increment */
gs.in.bov[3] = 0; /* Bit offset to value within channel */
gs.in.bpv[3] = 8; /* Bits per value within channel */
gs.od = 1; /* Number of output dimensions */
gs.out.pint = 1; /* Flag - nonz if pixel interleaved */
gs.out.packed = 0; /* Flag - nonz if channels packed into one write */
gs.out.bpch[0] = 8; /* Bits per channel */
gs.out.chi[0] = 1; /* Channel increment */
gs.out.bov[0] = 0; /* Bit offset to value within channel */
gs.out.bpv[0] = 8; /* Bits per value within channel */
gs.out.bpch[1] = 8; /* Bits per channel */
gs.out.chi[1] = 4; /* Channel increment */
gs.out.bov[1] = 0; /* Bit offset to value within channel */
gs.out.bpv[1] = 8; /* Bits per value within channel */
gs.out.bpch[2] = 8; /* Bits per channel */
gs.out.chi[2] = 4; /* Channel increment */
gs.out.bov[2] = 0; /* Bit offset to value within channel */
gs.out.bpv[2] = 8; /* Bits per value within channel */
gs.out.bpch[3] = 8; /* Bits per channel */
gs.out.chi[3] = 4; /* Channel increment */
gs.out.bov[3] = 0; /* Bit offset to value within channel */
gs.out.bpv[3] = 8; /* Bits per value within channel */
gs.out.bpch[4] = 8; /* Bits per channel */
gs.out.chi[4] = 4; /* Channel increment */
gs.out.bov[4] = 0; /* Bit offset to value within channel */
gs.out.bpv[4] = 8; /* Bits per value within channel */
gs.out.bpch[5] = 8; /* Bits per channel */
gs.out.chi[5] = 4; /* Channel increment */
gs.out.bov[5] = 0; /* Bit offset to value within channel */
gs.out.bpv[5] = 8; /* Bits per value within channel */
gs.opt = opts_none; /* Direction and stride options */
gs.prec = 8; /* Precsision needed */
gs.itres = 16; /* Interpolation table resolution */
gs.stres = 17; /* Simplex table resolution */
/* Setup a machine architecture */
ar.bigend = 0; /* Non-zero if this is a bigendian architecture */
ar.uwa = 0; /* Use wide memory access */
ar.shfm = 0; /* Use shifts to mask values */
ar.oscale = 8; /* Has scaled indexing up to * 8 */
ar.smmul = 0; /* Doesn't have fast small multiply for index scaling */
ar.pbits = 32; /* Number of bits in a pointer */
ar.nords = 3; /* Number of ord types */
ar.ords[0].bits = 8;
ar.ords[0].name = "unsigned char";
ar.ords[0].align = 1;
ar.ords[1].bits = 16;
ar.ords[1].name = "unsigned short";
ar.ords[1].align = 1;
ar.ords[2].bits = 32;
ar.ords[2].name = "unsigned int";
ar.ords[2].align = 1;
#ifdef ALLOW64
ar.ords[3].bits = 64;
ar.ords[3].name = "unsigned longlong";
ar.ords[3].align = 0;
#endif /* ALLOW64 */
ar.natord = 2; /* Most natural type */
ar.nints = 3; /* Number of int types */
ar.ints[0].bits = 8;
ar.ints[0].name = "signed char";
ar.ints[0].align = 1;
ar.ints[1].bits = 16;
ar.ints[1].name = "short";
ar.ints[1].align = 1;
ar.ints[2].bits = 32;
ar.ints[2].name = "int";
ar.ints[2].align = 1;
#ifdef ALLOW64
ar.ints[3].bits = 64;
ar.ints[3].name = "longlong";
ar.ints[3].align = 0;
#endif /* ALLOW64 */
ar.natint = 2; /* Most natural type */
rv = gen_c_kernel(&gs, &ts, &ar, kcode, 99, &ogs, &ots);
fclose(kcode);
return 0;
}

View File

@@ -0,0 +1,582 @@
/*
* Convert a TIFF to monochrome in a colorimetrically correct way.
*
* Author: Graeme W. Gill
* Date: 01/8/29
* Version: 1.00
*
* Copyright 2000, Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
/*
* Thanks to Neil Okamoto for the 16 bit TIFF mods.
*/
/* TTBD:
*
*/
/*
This program is a framework that exercises the
IMDI code. It can also do the conversion using the
floating point code in ICCLIB as a reference.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <fcntl.h>
#include <string.h>
#include <math.h>
#include "copyright.h"
#include "aconfig.h"
#include "tiffio.h"
#include "icc.h"
#include "numlib.h"
#include "conv.h"
#include "xicc.h"
#include "imdi.h"
#undef DO_CHECK /* Do floating point check */
void usage(void) {
fprintf(stderr,"Convert a TIFF file to monochrome using an ICC device profile, V%s\n",ARGYLL_VERSION_STR);
fprintf(stderr,"Author: Graeme W. Gill, licensed under the AGPL Version 3\n");
fprintf(stderr,"usage: greytiff [-v level] profile.icm infile.tif outfile.tif\n");
fprintf(stderr," -v Verbose\n");
fprintf(stderr," -p Use slow precise correction\n");
fprintf(stderr," -j Use CIECAM02\n");
exit(1);
}
/* Convert an ICC colorspace to the corresponding TIFF Photometric tag */
/* return 0xffff if not possible. */
int
ColorSpaceSignature2TiffPhotometric(
icColorSpaceSignature cspace
) {
switch(cspace) {
case icSigGrayData:
return PHOTOMETRIC_MINISBLACK;
case icSigRgbData:
return PHOTOMETRIC_RGB;
case icSigCmykData:
return PHOTOMETRIC_SEPARATED;
case icSigYCbCrData:
return PHOTOMETRIC_YCBCR;
case icSigLabData:
return PHOTOMETRIC_CIELAB;
case icSigXYZData:
case icSigLuvData:
case icSigYxyData:
case icSigHsvData:
case icSigHlsData:
case icSigCmyData:
case icSig2colorData:
case icSig3colorData:
case icSig4colorData:
case icSig5colorData:
case icSigMch5Data:
case icSig6colorData:
case icSigMch6Data:
case icSig7colorData:
case icSigMch7Data:
case icSig8colorData:
case icSigMch8Data:
case icSig9colorData:
case icSig10colorData:
case icSig11colorData:
case icSig12colorData:
case icSig13colorData:
case icSig14colorData:
case icSig15colorData:
default:
return 0xffff;
}
return 0xffff;
}
char *
Photometric2str(
int pmtc
) {
static char buf[80];
switch (pmtc) {
case PHOTOMETRIC_MINISWHITE:
return "Subtractive Gray";
case PHOTOMETRIC_MINISBLACK:
return "Additive Gray";
case PHOTOMETRIC_RGB:
return "RGB";
case PHOTOMETRIC_PALETTE:
return "Indexed";
case PHOTOMETRIC_MASK:
return "Transparency Mask";
case PHOTOMETRIC_SEPARATED:
return "CMYK";
case PHOTOMETRIC_YCBCR:
return "YCbCr";
case PHOTOMETRIC_CIELAB:
return "CIELab";
case PHOTOMETRIC_LOGL:
return "CIELog2L";
case PHOTOMETRIC_LOGLUV:
return "CIELog2Luv";
}
sprintf(buf,"Unknown Tag %d",pmtc);
return buf;
}
/* Callbacks used to initialise imdi */
/* Context for imdi setup callbacks */
typedef struct {
int id, od;
icxLuBase *flu; /* Device -> Jab/Lab */
icxLuBase *blu; /* Jab/Lab -> Device */
} sucntx;
/* Input curve function */
void input_curve(
void *cntx,
double *out_vals,
double *in_vals
) {
sucntx *rx = (sucntx *)cntx;
int e;
for (e = 0; e < rx->id; e++)
out_vals[e] = in_vals[e];
}
/* Multi-dim table function */
void md_table(
void *cntx,
double *out_vals,
double *in_vals
) {
sucntx *rx = (sucntx *)cntx;
double Lab[3];
rx->flu->lookup(rx->flu, Lab, in_vals);
Lab[1] = Lab[2] = 0.0;
rx->blu->lookup(rx->blu, out_vals, Lab);
}
/* Output curve function */
void output_curve(
void *cntx,
double *out_vals,
double *in_vals
) {
sucntx *rx = (sucntx *)cntx;
int e;
for (e = 0; e < rx->od; e++)
out_vals[e] = in_vals[e];
}
int
main(int argc, char *argv[]) {
int fa,nfa; /* argument we're looking at */
static char prof_name[MAXNAMEL+1];
static char in_name[MAXNAMEL+1];
static char out_name[MAXNAMEL+1];
icmFile *p_fp;
icmErr err = { 0, { '\000'} };
icc *icco;
xicc *xicco;
int verb = 0;
int slow = 0;
int rv = 0;
icColorSpaceSignature pcsor = icSigLabData;
TIFF *rh = NULL, *wh = NULL;
int x, y, width, height; /* Size of image */
uint16 samplesperpixel, bitspersample;
uint16 pconfig, photometric, pmtc;
uint16 resunits;
float resx, resy;
tdata_t *inbuf, *outbuf, *checkbuf;
icColorSpaceSignature ins; /* Type of input spaces */
int inn; /* Number of device components */
/* IMDI */
imdi *s = NULL;
sucntx su; /* Setup context */
unsigned char *inp[MAX_CHAN];
unsigned char *outp[MAX_CHAN];
#ifdef DO_CHECK
/* Error check */
int mxerr = 0;
double avgerr = 0.0;
double avgcount = 0.0;
#endif /* DO_CHECK */
if (argc < 2)
usage();
/* Process the arguments */
for (fa = 1;fa < argc;fa++) {
nfa = fa; /* skip to nfa if next argument is used */
if (argv[fa][0] == '-') { /* Look for any flags */
char *na = NULL; /* next argument after flag, null if none */
if (argv[fa][2] != '\000')
na = &argv[fa][2]; /* next is directly after flag */
else {
if ((fa+1) < argc) {
if (argv[fa+1][0] != '-') {
nfa = fa + 1;
na = argv[nfa]; /* next is seperate non-flag argument */
}
}
}
if (argv[fa][1] == '?')
usage();
/* Slow, Precise */
else if (argv[fa][1] == 'p' || argv[fa][1] == 'P') {
slow = 1;
}
/* Use CIECAM02 */
else if (argv[fa][1] == 'j' || argv[fa][1] == 'J') {
pcsor = icxSigJabData;
}
/* Verbosity */
else if (argv[fa][1] == 'v' || argv[fa][1] == 'V') {
verb = 1;
}
else
usage();
} else
break;
}
if (fa >= argc || argv[fa][0] == '-') usage();
strncpy(prof_name,argv[fa++],MAXNAMEL); prof_name[MAXNAMEL] = '\000';
if (fa >= argc || argv[fa][0] == '-') usage();
strncpy(in_name,argv[fa++],MAXNAMEL); in_name[MAXNAMEL] = '\000';
if (fa >= argc || argv[fa][0] == '-') usage();
strncpy(out_name,argv[fa++],MAXNAMEL); out_name[MAXNAMEL] = '\000';
/* - - - - - - - - - - - - - - - - */
/* Open up the profile for reading */
if ((p_fp = new_icmFileStd_name(&err,prof_name,"r")) == NULL)
error ("Can't open file '%s' (0x%x, '%s')",prof_name,err.c,err.m);
if ((icco = new_icc(&err)) == NULL)
error ("Creation of ICC object failed (0x%x, '%s')",err.c,err.m);
/* Wrap with an expanded icc */
if ((xicco = new_xicc(icco)) == NULL)
error ("Creation of xicc failed");
if ((rv = icco->read(icco,p_fp,0)) != 0)
error ("%d, %s",rv,icco->e.m);
if (verb) {
icmFile *op;
if ((op = new_icmFileStd_fp(&err,stdout)) == NULL)
error ("Can't open stdout (0x%x, '%s')",err.c,err.m);
icco->header->dump(icco->header, op, 1);
op->del(op);
}
/* Check that the profile is appropriate */
if (icco->header->deviceClass != icSigInputClass
&& icco->header->deviceClass != icSigDisplayClass
&& icco->header->deviceClass != icSigOutputClass
&& icco->header->deviceClass != icSigColorSpaceClass) /* For sRGB etc. */
error("Profile isn't a device profile");
/* Get a expanded color conversion object */
if ((su.flu = xicco->get_luobj(xicco, ICX_CLIP_NEAREST, icmFwd, icRelativeColorimetric, pcsor, icmLuOrdNorm, NULL, NULL)) == NULL)
error ("%d, %s",xicco->e.c, xicco->e.m);
/* Get details of conversion (Arguments may be NULL if info not needed) */
su.flu->spaces(su.flu, &ins, &inn, NULL, NULL, NULL, NULL, NULL, NULL);
su.id = inn;
su.od = inn;
/* Get a bwd conversion object */
if ((su.blu = xicco->get_luobj(xicco, ICX_CLIP_NEAREST, icmBwd, icRelativeColorimetric, pcsor, icmLuOrdNorm, NULL, NULL)) == NULL)
error ("%d, %s",xicco->e.c, xicco->e.m);
/* - - - - - - - - - - - - - - - */
/* Open up input tiff file ready for reading */
/* Got arguments, so setup to process the file */
if ((rh = TIFFOpen(in_name, "r")) == NULL)
error("error opening read file '%s'",in_name);
TIFFGetField(rh, TIFFTAG_IMAGEWIDTH, &width);
TIFFGetField(rh, TIFFTAG_IMAGELENGTH, &height);
TIFFGetField(rh, TIFFTAG_BITSPERSAMPLE, &bitspersample);
if (bitspersample != 8 && bitspersample != 16) {
error("TIFF Input file must be 8 or 16 bit/channel");
}
TIFFGetField(rh, TIFFTAG_PHOTOMETRIC, &photometric);
if ((pmtc = ColorSpaceSignature2TiffPhotometric(ins)) == 0xffff)
error("ICC input colorspace '%s' can't be handled by a TIFF file!",
icm2str(icmColorSpaceSig, ins));
if (pmtc != photometric)
error("ICC input colorspace '%s' doesn't match TIFF photometric '%s'!",
icm2str(icmColorSpaceSig, ins), Photometric2str(photometric));
TIFFGetField(rh, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
if (inn != samplesperpixel)
error ("TIFF Input file has %d input channels mismatched to colorspace '%s'",
samplesperpixel, icm2str(icmColorSpaceSig, ins));
TIFFGetField(rh, TIFFTAG_PLANARCONFIG, &pconfig);
if (pconfig != PLANARCONFIG_CONTIG)
error ("TIFF Input file must be planar");
TIFFGetField(rh, TIFFTAG_RESOLUTIONUNIT, &resunits);
TIFFGetField(rh, TIFFTAG_XRESOLUTION, &resx);
TIFFGetField(rh, TIFFTAG_YRESOLUTION, &resy);
/* - - - - - - - - - - - - - - - */
if ((wh = TIFFOpen(out_name, "w")) == NULL)
error("Can\'t create TIFF file '%s'!",out_name);
TIFFSetField(wh, TIFFTAG_IMAGEWIDTH, width);
TIFFSetField(wh, TIFFTAG_IMAGELENGTH, height);
TIFFSetField(wh, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
TIFFSetField(wh, TIFFTAG_SAMPLESPERPIXEL, inn);
TIFFSetField(wh, TIFFTAG_BITSPERSAMPLE, bitspersample);
TIFFSetField(wh, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
if ((pmtc = ColorSpaceSignature2TiffPhotometric(ins)) == 0xffff)
error("TIFF file can't handle output colorspace '%s'!",
icm2str(icmColorSpaceSig, ins));
TIFFSetField(wh, TIFFTAG_PHOTOMETRIC, pmtc);
TIFFSetField(wh, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
if (resunits) {
TIFFSetField(wh, TIFFTAG_RESOLUTIONUNIT, resunits);
TIFFSetField(wh, TIFFTAG_XRESOLUTION, resx);
TIFFSetField(wh, TIFFTAG_YRESOLUTION, resy);
}
TIFFSetField(wh, TIFFTAG_IMAGEDESCRIPTION, "Color corrected by Argyll");
/* - - - - - - - - - - - - - - - */
/* Setup the imdi */
if (!slow) {
s = new_imdi(
inn, /* Number of input dimensions */
inn, /* Number of output dimensions */
bitspersample == 8 ? pixint8 : pixint16,
/* Output pixel representation */
0x0, /* Treat every channel as unsigned */
NULL, /* No raster to callback channel mapping */
prec_min, /* Minimum of input and output precision */
bitspersample == 8 ? pixint8 : pixint16,
0x0, /* Treat every channel as unsigned */
NULL, /* No raster to callback channel mapping */
17, /* Desired table resolution. 33 is also a good number */
oopts_none, /* Desired per channel output options */
NULL, /* Output channel check values */
opts_none, /* Desired processing direction and stride support */
input_curve, /* Callback functions */
md_table,
output_curve,
(void *)&su /* Context to callbacks */
);
if (s == NULL)
error("new_imdi failed");
}
/* - - - - - - - - - - - - - - - */
/* Process colors to translate */
/* (Should fix this to process a group of lines at a time ?) */
inbuf = _TIFFmalloc(TIFFScanlineSize(rh));
outbuf = _TIFFmalloc(TIFFScanlineSize(wh));
checkbuf = _TIFFmalloc(TIFFScanlineSize(wh));
inp[0] = (unsigned char *)inbuf;
outp[0] = (unsigned char *)outbuf;
if (!slow) { /* Fast */
for (y = 0; y < height; y++) {
/* Read in the next line */
if (TIFFReadScanline(rh, inbuf, y, 0) < 0)
error ("Failed to read TIFF line %d",y);
/* Do fast conversion */
s->interp(s, (void **)outp, 0, (void **)inp, 0, width);
#ifdef DO_CHECK
/* Do floating point conversion */
for (x = 0; x < width; x++) {
int i;
double in[MAX_CHAN], out[MAX_CHAN];
double Lab[3];
if (bitspersample == 8)
for (i = 0; i < inn; i++)
in[i] = ((unsigned char *)inbuf)[x * inn + i]/255.0;
else
for (i = 0; i < inn; i++)
in[i] = ((unsigned short *)inbuf)[x * inn + i]/65535.0;
if ((rv = su.flu->lookup(su.flu, Lab, in)) > 1)
error ("%d, %s",icco->e.c,icco->e.m);
Lab[1] = Lab[2] = 0.0;
if ((rv = su.blu->lookup(su.blu, out, Lab)) > 1)
error ("%d, %s",icco->e.c,icco->e.m);
if (bitspersample == 8)
for (i = 0; i < inn; i++)
((unsigned char *)checkbuf)[x * inn + i] = (int)(out[i] * 255.0 + 0.5);
else
for (i = 0; i < inn; i++)
((unsigned short *)checkbuf)[x * inn + i] = (int)(out[i] * 65535.0 + 0.5);
}
/* Compute the errors */
for (x = 0; x < (width * inn); x++) {
int err;
if (bitspersample == 8)
err = ((unsigned char *)outbuf)[x] - ((unsigned char *)checkbuf)[x];
else
err = ((unsigned short *)outbuf)[x] - ((unsigned short *)checkbuf)[x];
if (err < 0)
err = -err;
if (err > mxerr)
mxerr = err;
avgerr += (double)err;
avgcount++;
}
#endif /* DO_CHECK */
if (TIFFWriteScanline(wh, outbuf, y, 0) < 0)
error ("Failed to write TIFF line %d",y);
}
} else { /* Slow but precise */
if (bitspersample == 8) {
for (y = 0; y < height; y++) {
/* Read in the next line */
if (TIFFReadScanline(rh, inbuf, y, 0) < 0)
error ("Failed to read TIFF line %d",y);
/* Do floating point conversion */
for (x = 0; x < width; x++) {
int i;
double in[MAX_CHAN], out[MAX_CHAN];
double Lab[3];
for (i = 0; i < inn; i++) {
in[i] = ((unsigned char *)inbuf)[x * inn + i]/255.0;
}
if ((rv = su.flu->lookup(su.flu, Lab, in)) > 1)
error ("%d, %s",icco->e.c,icco->e.m);
Lab[1] = Lab[2] = 0.0;
if ((rv = su.blu->lookup(su.blu, out, Lab)) > 1)
error ("%d, %s",icco->e.c,icco->e.m);
for (i = 0; i < inn; i++) {
((unsigned char *)outbuf)[x * inn + i] = (int)(out[i] * 255.0 + 0.5);
}
}
if (TIFFWriteScanline(wh, outbuf, y, 0) < 0)
error ("Failed to write TIFF line %d",y);
}
} else if (bitspersample == 16) {
for (y = 0; y < height; y++) {
/* Read in the next line */
if (TIFFReadScanline(rh, inbuf, y, 0) < 0)
error ("Failed to read TIFF line %d",y);
/* Do floating point conversion */
for (x = 0; x < width; x++) {
int i;
double in[MAX_CHAN], out[MAX_CHAN];
double Lab[3];
for (i = 0; i < inn; i++) {
in[i] = ((unsigned short *)inbuf)[x * inn + i]/65535.0;
}
if ((rv = su.flu->lookup(su.flu, Lab, in)) > 1)
error ("%d, %s",icco->e.c,icco->e.m);
Lab[1] = Lab[2] = 0.0;
if ((rv = su.blu->lookup(su.blu, out, Lab)) > 1)
error ("%d, %s",icco->e.c,icco->e.m);
for (i = 0; i < inn; i++) {
((unsigned short *)outbuf)[x * inn + i] = (int)(out[i] * 65535.0 + 0.5);
}
}
if (TIFFWriteScanline(wh, outbuf, y, 0) < 0)
error ("Failed to write TIFF line %d",y);
}
}
}
#ifdef DO_CHECK
printf("Worst error = %d bits, average error = %f bits\n", mxerr, avgerr/avgcount);
if (bitspersample == 8)
printf("Worst error = %f%%, average error = %f%%\n",
mxerr/2.55, avgerr/(2.55 * avgcount));
else
printf("Worst error = %f%%, average error = %f%%\n",
mxerr/655.35, avgerr/(655.35 * avgcount));
#endif /* DO_CHECK */
/* Done with lookup object */
if (s != NULL)
s->del(s);
su.flu->del(su.flu);
su.blu->del(su.blu);
xicco->del(xicco);
icco->del(icco);
p_fp->del(p_fp);
TIFFClose(rh); /* Close Input file */
TIFFClose(wh); /* Close Output file */
return 0;
}

605
Argyll_V3.5.0/imdi/imdi.c Normal file
View File

@@ -0,0 +1,605 @@
/* Integer Multi-Dimensional Interpolation */
/*
* Copyright 2000 - 2007 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
/*
* This is the implementation of the run time code.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#include <string.h>
#include "imdi.h"
#include "imdi_tab.h"
#include "imdi_k.h" /* Declaration of all the kernel functions */
#undef VERBOSE
#undef VVERBOSE
static unsigned int imdi_get_check(imdi *im);
static void imdi_reset_check(imdi *im);
static void imdi_info(imdi *s, unsigned long *size, int *gres, int *sres);
static void imdi_del(imdi *im);
static void interp_match(imdi *s, void **outp, int outst, void **inp, int inst,
unsigned int npixels);
/* Create a new imdi */
/* Return NULL if request is not supported */
/* Note that we use the high level pixel layout description to locate */
/* a suitable run-time. */
imdi *new_imdi(
int id, /* Number of input dimensions */
int od, /* Number of output lookup dimensions */
/* Number of output channels written = od - no. of oopt skip flags */
imdi_pixrep in, /* Input pixel representation */
int in_signed, /* Bit flag per channel, NZ if treat as signed */
int *inm, /* Input raster channel to callback channel mapping, NULL for none. */
imdi_iprec iprec, /* Internal processing precision */
imdi_pixrep out, /* Output pixel representation */
int out_signed, /* Bit flag per channel, NZ if treat as signed */
int *outm, /* Output raster channel to callback channel mapping, NULL for none. */
/* Mapping must include skipped channels. */
int res, /* Desired table resolution */
imdi_ooptions oopt, /* Output per channel options (by callback channel) */
unsigned int *checkv, /* Output channel check values (by callback channel, NULL == 0) */
imdi_options opt, /* Direction and stride options */
/* Callbacks to lookup the imdi table values. */
/* (Skip output channels are looked up) */
void (*input_curves) (void *cntx, double *out_vals, double *in_vals),
void (*md_table) (void *cntx, double *out_vals, double *in_vals),
void (*output_curves)(void *cntx, double *out_vals, double *in_vals),
void *cntx /* Context to callbacks */
) {
int i;
int prec; /* Target internal precision */
int bk = -1; /* Best table */
int bfig = 0x7fffffff; /* Best tables figure of merit */
int bstres = 0; /* Best tables target stres */
genspec gs; /* Generation specification */
tabspec ts; /* Table specifications */
genspec bgs; /* Best gen spec */
tabspec bts; /* Best tab spec */
imdi_conv bcnv = conv_none; /* Best tables conversion flags */
imdi_ooptions Ooopt; /* oopt re-aranged to correspond to output channel index */
imdi *im;
/* Compute the Output channel index oopt mask */
if (outm == NULL)
Ooopt = oopt;
else {
int ff;
Ooopt = 0;
for (i = 0; i < od; i++) {
ff = OOPTX(oopt,outm[i]);
Ooopt |= OOPT(ff,i);
}
}
#ifdef VERBOSE
printf("new_imdi called with id %d, od %d, res %d Ooopt 0x%x, opt 0x%x\n", id, od, res, Ooopt, opt);
printf("about to checking %d kernels\n", no_kfuncs);
#endif
/* Figure out the internal precision requested */
COMPUTE_IPREC(prec, in, iprec, out)
/* Zero out the gen and tabspecs, to give diff a place to start */
memset((void *)&gs, 0, sizeof(genspec));
memset((void *)&ts, 0, sizeof(tabspec));
/* The first thing to do is see if there is an available kernel function */
for (i = 0; i < no_kfuncs; i++) {
int stres; /* Computed stres needed */
imdi_conv cnv = conv_none; /* Conversions needed for this choice */
int fig; /* Figure of merit - smaller is better */
ktable[i].gentab(&gs, &ts); /* Udate the kernel functions genspec and tabspec */
#ifdef VERBOSE
printf("\n");
printf("kernel %d has id %d, od %d, irep %d orep %d oopt 0x%x, opt 0x%x\n",
i, gs.id, gs.od, gs.irep, gs.orep, gs.oopt, gs.opt);
printf("Input req is id %d, od %d, irep %d orep %d, oopt 0x%x, opt 0x%x\n",
id, od, in, out, Ooopt, opt);
#endif
/* First check mandatory things */
if (!(
id == gs.id /* Input dimension */
&& od == gs.od /* Output dimension */
)) {
#ifdef VVERBOSE
printf(" Input or Output dimension mismatch\n");
#endif
continue;
}
/* Check if we have an exact or conversion match for input stride */
if (!(
(opt & opts_istride) == (gs.opt & opts_istride)
|| (!(opt & opts_istride) && (gs.opt & opts_istride))
)) {
#ifdef VVERBOSE
printf(" Input stride mismatch\n");
#endif
continue;
}
/* Check if we have an exact or conversion match for output stride */
if (!(
(opt & opts_ostride) == (gs.opt & opts_ostride)
|| (!(opt & opts_ostride) && (gs.opt & opts_ostride))
)) {
#ifdef VVERBOSE
printf(" Output stride mismatch\n");
#endif
continue;
}
/* Check if we have an exact or conversion match for input representation */
if (!(
in == gs.irep
|| (in == pixint8 && gs.irep == planeint8 && (gs.opt & opts_istride))
|| (in == pixint16 && gs.irep == planeint16 && (gs.opt & opts_istride))
)) {
#ifdef VVERBOSE
printf(" Input representation mismatch\n");
#endif
continue;
}
/* Check if we have an exact or conversion match for output representation */
if (!(
out == gs.orep
|| (out == pixint8 && gs.orep == planeint8 && (gs.opt & opts_ostride))
|| (out == pixint16 && gs.orep == planeint16 && (gs.opt & opts_ostride))
)) {
#ifdef VVERBOSE
printf(" Output representation mismatch\n");
#endif
continue;
}
/* See if we have the output per channel options needed */
if (!((Ooopt & gs.oopt) == Ooopt)) {
#ifdef VVERBOSE
printf(" Output per channel options mismatch\n");
#endif
continue;
}
/* See if we have an exact or conversion match for reverse direction */
if (!(
((!(opt & opts_bwd) && !(opt & opts_fwd))) /* Don't care */
|| (((opt & opts_bwd) && (gs.opt & opts_bwd))) /* Match */
|| (((opt & opts_fwd) && (gs.opt & opts_fwd))) /* Match */
|| ((gs.opt & opts_istride) && (gs.opt & opts_ostride)) /* Can convert */
)) {
#ifdef VVERBOSE
printf(" Direction mismatch\n");
#endif
continue;
}
#ifdef VERBOSE
printf(" found match\n");
#endif
fig = 0;
/* Apply penalty if we will have to do a conversion match */
if ((opt & opts_istride) != (gs.opt & opts_istride)) {
cnv |= conv_istr;
fig += 1000;
#ifdef VERBOSE
printf(" needs input stride conversion though\n");
#endif
}
if ((opt & opts_ostride) != (gs.opt & opts_ostride)) {
cnv |= conv_ostr;
fig += 1000;
#ifdef VERBOSE
printf(" needs output stride conversion though\n");
#endif
}
if (in != gs.irep) {
cnv |= conv_irep;
fig += 5000;
#ifdef VERBOSE
printf(" needs input representation conversion though\n");
#endif
}
if (out != gs.orep) {
cnv |= conv_orep;
fig += 5000;
#ifdef VERBOSE
printf(" needs output representation conversion though\n");
#endif
}
/* If we don't need output checking or skipping, but we've got it */
if ((~Ooopt & gs.oopt) != 0) {
unsigned int tmp = (~Ooopt & gs.oopt);
/* Count number of bits set that we don't need */
/* (From HACKMEM 169) */
tmp = tmp - ((tmp >> 1) & 033333333333) - ((tmp >> 2) & 011111111111);
tmp = ((tmp + (tmp >> 3)) & 030707070707) % 63;
fig += tmp;
#ifdef VERBOSE
printf(" has output options we don't need though\n");
#endif
}
/* If we've got output skipping, we need to skip pointers in interp. */
if ((Ooopt & OOPTS_SKIP) != 0) {
cnv |= conv_skip;
}
if (((opt & opts_fwd) && (gs.opt & opts_bwd))
|| ((opt & opts_bwd) && (gs.opt & opts_fwd))) {
cnv |= conv_rev;
fig += 1000;
#ifdef VERBOSE
printf(" needs direction conversion though\n");
#endif
}
if (prec != gs.prec) { /* Internal precision mismatch */
fig += 100000; /* Will have a major effect, so discourage using it */
#ifdef VERBOSE
printf(" internal precision doesn't match though (want %d, got %d)\n",prec,gs.prec);
#endif
}
/* If we've got a choice of algorithm possible */
if (gs.opt & (opts_splx_sort | opts_sort_splx)) {
/* If we've got a preference of algorithm, */
if ((opt & (opts_splx_sort | opts_sort_splx))) {
/* and there is a mismatch */
if (((opt & opts_splx_sort) && ts.sort != 0)
|| ((opt & opts_sort_splx) && ts.sort == 0)) {
fig += 10000; /* Will have a great effect, so discourage using it */
#ifdef VERBOSE
printf(" sort/simplex algorithm mismatch\n");
#endif
}
} else { /* There is no preference chosen at run time, */
/* and there is a mismatch to the compile time preference */
if (((gs.opt & opts_splx_sort) && ts.sort != 0)
|| ((gs.opt & opts_sort_splx) && ts.sort == 0)) {
fig += 10000; /* Will have a great effect, so discourage using it */
#ifdef VERBOSE
printf(" sort/simplex algorithm mismatch\n");
#endif
}
}
}
if (ts.sort) {
stres = 0;
#ifdef VERBOSE
printf("gres = %d, gs.gres = %d\n",res,gs.itres);
#endif
/* We want one that is equals or exceeds the desired */
/* resolution, but doesn't exceed it too much, or the code */
/* will be inefficient. */
/* If there are no routines that can meet the desired precision, */
/* then it is ok to use the one closest to the desired precision. */
if (gs.itres >= res) {
fig += 10 * (gs.itres - res);
} else {
fig += 10000 + 10 * (res - gs.itres);
}
} else {
/* compute the needed stres (Assuming not sort) */
stres = ((1 << gs.prec)-1 + res-2)/(res-1);
#ifdef VERBOSE
printf("gres = %d, sres = %d, gs.gres = %d, gs.sres = %d\n",res,stres,gs.itres,gs.stres);
#endif
/* We want one that is equals or exceeds the desired */
/* resolution, but doesn't exceed it too much, or the code */
/* will be inefficient. */
/* If there are no routines that can meet the desired precision, */
/* then it is ok to use the one closest to the desired precision. */
if (gs.itres >= res && gs.stres >= stres) {
fig += 10 * (gs.itres - res) + (gs.stres - stres);
} {
if (gs.itres < res) {
fig += 10000 + 10 * (res - gs.itres);
}
if (gs.stres < stres) {
fig += 1000 + 10 * (stres - gs.stres);
}
}
}
#ifdef VERBOSE
printf(" figure of merit %d\n",fig);
#endif
/* Is this the best one so far ? */
if (fig < bfig) {
bfig = fig;
bk = i;
bstres = stres;
bgs = gs; /* Structure copy */
bts = ts; /* Structure copy */
bcnv = cnv;
#ifdef VERBOSE
printf(" best so far\n");
#endif
}
}
if (bk < 0) {
#ifdef VERBOSE
printf("new_imdi failed - dimensionality or representations couldn't be matched\n");
#endif
return NULL; /* Nothing matches */
}
if ((im = (imdi *)calloc(1, sizeof(imdi))) == NULL) {
#ifdef VERBOSE
printf("new_imdi malloc imdi failed\n");
#endif
/* Should we return an error somehow ? */
return NULL;
}
/* We've decided kernel function bk is going to be the best, */
/* so now setup the appropriate tables to use with it. */
if (bgs.itres > res)
bgs.itres = res; /* Tell table create what the res is */
if (bgs.stres > bstres)
bgs.stres = bstres;
/* Tel table setup how to treat integer input in per channel lookups */
bgs.in_signed = in_signed;
bgs.out_signed = out_signed;
#ifdef VERBOSE
if (!bts.sort) {
if ((bgs.stres * (bgs.itres-1)) < ((1 << bgs.prec)-1)) {
printf("Warning: table chosen doesn't reach desired precision!\n");
printf("Wanted %d, got %d\n", ((1 << bgs.prec)-1), (bgs.stres * (bgs.itres-1)));
}
}
#endif
/* Allocate and initialise the appropriate tables */
im->impl = (void *)imdi_tab(&bgs, &bts, bcnv, in, out, ktable[bk].interp,
inm, outm, oopt, checkv, input_curves, md_table,
output_curves, cntx);
if (im->impl == NULL) {
#ifdef VERBOSE
printf("imdi_tab failed\n");
#endif
imdi_del(im);
return NULL;
}
#ifdef VERBOSE
if (bcnv != conv_none)
printf("imdi_tab: using a runtime match, cnv flags 0x%x\n",bcnv);
#endif
if (bcnv == conv_none) /* No runtime match conversion needed */
im->interp = ktable[bk].interp;
else
im->interp = interp_match;
im->get_check = imdi_get_check;
im->reset_check = imdi_reset_check;
im->info = imdi_info;
im->del = imdi_del;
#ifdef VERBOSE
printf("new_imdi returning 0x%x\n", im);
#endif
return im;
}
/* Runtime matching adapter */
/* We can emulate many combinations of interpolation function */
/* by converting to a routine that supports stride, or one that */
/* supports plane interleaved and stride. */
/* This also lets us emulate functions that can convert between */
/* pixel and plane interleaved at the same time as doing the */
/* color interpolation. Warp is in components (NOT bytes) */
/* We cope with skipping writes to output channels by */
/* only implementing that support in plane interleaved, */
/* and depending on that being used for pixel interleaved. */
static void interp_match(
imdi *s,
void **outp, int outst, /* Output pointers and stride */
void **inp, int inst, /* Input pointers and stride */
unsigned int npixels /* Number of pixels */
) {
int j, i;
void *minp[IXDI];
void *moutp[IXDI];
imdi_imp *impl = (imdi_imp *)s->impl;
imdi_conv cnv = impl->cnv;
/* Need to supply default stride. */
/* This is simply the input dimension for pixel interleaved, */
/* and 1 for plane interleaved. */
if (cnv & conv_istr) {
if (impl->cirep == pixint8 || impl->cirep == pixint16)
inst = impl->id;
else
inst = 1;
}
if (cnv & conv_ostr) {
if (impl->corep == pixint8 || impl->corep == pixint16)
outst = impl->wod;
else
outst = 1;
}
/* Convert from pixel to plane by setting the plane pointers */
/* to each pixel component, and using the pixel interleaved stride */
if (cnv & conv_irep) {
if (impl->cirep == pixint8) { /* Convert from pix8 to plane8 */
for (j = 0; j < impl->id; j++)
minp[j] = (void *)((char *)inp[0] + j);
} else if (impl->cirep == pixint16) { /* Convert from pix16 to plane16 */
for (j = 0; j < impl->id; j++)
minp[j] = (void *)((char *)inp[0] + 2 * j);
}
} else { /* Copy pointers, because we call with them. */
if (impl->cirep == pixint8 || impl->cirep == pixint16) {
minp[0] = inp[0];
} else {
for (j = 0; j < impl->id; j++)
minp[j] = inp[j];
}
}
if (cnv & conv_orep) {
if (impl->corep == pixint8) { /* Convert from pix8 to plane8 */
for (j = i = 0; j < impl->od; j++) {
if ((impl->skipf & (1 << j)) == 0) /* If not skipped */
moutp[j] = (void *)((char *)outp[0] + i++);
else
moutp[j] = NULL;
}
} else if (impl->corep == pixint16) { /* Convert from pix16 to plane16 */
for (j = i = 0; j < impl->od; j++)
if ((impl->skipf & (1 << j)) == 0) /* If not skipped */
moutp[j] = (void *)((char *)outp[0] + 2 * i++);
else
moutp[j] = NULL;
}
} else { /* Copy pointers, because we call with them. */
if (impl->corep == pixint8 || impl->corep == pixint16) {
moutp[0] = outp[0];
} else { /* Plane interleaved */
for (j = i = 0; j < impl->od; j++) {
if ((impl->skipf & (1 << j)) == 0) /* If not skipped */
moutp[j] = outp[i++];
else
moutp[j] = NULL;
}
}
}
/* Convert fwd function to a backwards one, or visa-versa. */
/* Move the pointers to the last pixel, and reverse the stride */
if (cnv & conv_rev) {
if (impl->firep == pixint8) {
minp[0] = (void *)((char *)minp[0] + inst * (npixels - 1));
} else if (impl->firep == pixint16) {
minp[0] = (void *)((char *)minp[0] + inst * 2 * (npixels - 1));
} else if (impl->firep == planeint8) {
for (j = 0; j < impl->id; j++)
minp[j] = (void *)((char *)minp[j] + inst * (npixels - 1));
} else if (impl->firep == planeint16) {
for (j = 0; j < impl->id; j++)
minp[j] = (void *)((char *)minp[j] + inst * 2 * (npixels - 1));
}
inst = -inst;
if (impl->forep == pixint8) {
moutp[0] = (void *)((char *)moutp[0] + outst * (npixels - 1));
} else if (impl->forep == pixint16) {
moutp[0] = (void *)((char *)moutp[0] + outst * 2 * (npixels - 1));
} else if (impl->forep == planeint8) {
for (j = 0; j < impl->od; j++)
moutp[j] = (void *)((char *)moutp[j] + outst * (npixels - 1));
} else if (impl->forep == planeint16) {
for (j = 0; j < impl->od; j++)
moutp[j] = (void *)((char *)moutp[j] + outst * 2 * (npixels - 1));
}
outst = -outst;
}
/* Call the conversion routine we have */
impl->interp(s, moutp, outst, minp, inst, npixels);
}
/* Get the per output channel check flags - bit corresponds to output interpolation channel */
static unsigned int imdi_get_check(imdi *im) {
imdi_imp *impl = (imdi_imp *)im->impl;
unsigned int rv;
int i;
/* Convert from output channel index to callback index */
for (rv = 0, i = 0; i < impl->od; i++) {
unsigned int b;
b = 1 & (impl->checkf >> i); /* Output index flag */
rv |= (b << impl->im_map[i]); /* to callback index */
}
return rv;
}
/* Reset the output check flags (not reset by interp) */
static void imdi_reset_check(imdi *im) {
imdi_imp *impl = (imdi_imp *)im->impl;
impl->checkf = 0;
}
/* Return some information about the imdi */
static void imdi_info(imdi *im, unsigned long *psize, int *pgres, int *psres) {
imdi_imp *impl = (imdi_imp *)im->impl;
unsigned long size;
size = sizeof(imdi);
if (impl != NULL) {
size += impl->size;
if (psize != NULL)
*psize = size;
if (pgres != NULL)
*pgres = impl->gres;
if (psres != NULL)
*psres = impl->sres;
}
}
/* Delete the object */
static void imdi_del(imdi *im) {
/* Free all the allocated tables */
if (im->impl != NULL)
imdi_tab_free((imdi_imp *)im->impl);
/* Free this structure */
free(im);
}

93
Argyll_V3.5.0/imdi/imdi.h Normal file
View File

@@ -0,0 +1,93 @@
#ifndef IMDI_H
#define IMDI_H
/* Integer Multi-Dimensional Interpolation */
/*
* Copyright 2000 - 2007 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
/*
* This file provides the common definitions for IMDI, and
* in particular, the runtime conversion object.
* Actual runtime details are kept opaque.
*/
#include "imdi_utl.h"
#include "imdi_arch.h"
#include "imdi_gen.h"
/* IMDI Object */
struct _imdi {
void *impl; /* Opaque pointer to implementation information (type imdi_imp *) */
/* Do the interpolation. */
/* Each pointer corresponds to the colors plane for plane interleaved. */
/* pointer[0] is used for pixel interleave. */
/* Stride is only obeyed if the appropriate option flag was set */
/* in new_imdi, and is in pixel components, and effectively defaults */
/* to 1 for plane interleaved, and id and od (adjusted for skip) for pixel interleave, */
/* so stride is in color components (NOT bytes) */
/* Output pointers and data must only reference non-skipped output channels. */
/* Note that once an imdi is created, multiple can call interp() without */
/* interfering with each other, allowing parallel execution. */
void (*interp)(struct _imdi *s, void **outp, int outst, /* Output pointers and stride */
void **inp, int inst, /* Input pointers and stride */
unsigned int npixels); /* Number of pixels */
/* Return some information about the imdi */
void (*info)(struct _imdi *s, unsigned long *size, int *gres, int *sres);
/* Get the per output channel check flags (bit is indexed by callback channel) */
/* Flag gets set if output != checkv */
unsigned int (*get_check)(struct _imdi *s);
/* Reset the output check flags (flag is not reset by interp) */
void (*reset_check)(struct _imdi *s);
/* Delete this object */
void (*del)(struct _imdi *s);
}; typedef struct _imdi imdi;
/* Create a new imdi. */
/* Return NULL if request is not supported */
imdi *new_imdi(
int id, /* Number of input dimensions */
int od, /* Number of output lookup dimensions */
/* Number of output channels written = od - no. of oopt skip flags */
imdi_pixrep in, /* Input pixel representation */
int in_signed, /* Bit flag per channel, NZ if treat as signed */
int *inm, /* Input raster channel to callback channel mapping, NULL for none. */
imdi_iprec iprec, /* Internal processing precision */
imdi_pixrep out, /* Output pixel representation */
int out_signed, /* Bit flag per channel, NZ if treat as signed */
int *outm, /* Output raster channel to callback channel mapping, NULL for none. */
/* Mapping must include skipped channels. */
int res, /* Desired table resolution */
imdi_ooptions oopt, /* Output per channel options (by callback channel) */
unsigned int *checkv, /* Output channel check values (by callback channel, NULL == 0) */
imdi_options opt, /* Direction and stride options */
/* Callbacks to lookup the imdi table values. */
/* (Skip output channels are looked up) */
void (*input_curves) (void *cntx, double *out_vals, double *in_vals),
void (*md_table) (void *cntx, double *out_vals, double *in_vals),
void (*output_curves)(void *cntx, double *out_vals, double *in_vals),
void *cntx /* Context to callbacks */
);
#endif /* IMDI_H */

View File

@@ -0,0 +1,71 @@
#ifndef IMDI_ARCH_H
#define IMDI_ARCH_H
/* Integer Multi-Dimensional Interpolation */
/*
* Copyright 2000 - 2007 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
/*
* Contained here is any architecture/platform specific facilities,
* used by the runtime code, and used by the code generation code
* in generating the runtime code (used in the generation code itself
* only in discovering the architecture automatically),
* and the architecture table that describes the architecture to the
* code generation.
*
* The mach_arch structure is not used by the runtime, since it is implicit
* that the runtime is setup for the described architecture.
*
*/
#ifdef ALLOW64
#define STR_DEF(def) #def
/* Detect machine/compiler specifics here */
#if defined(NT)
#define longlong __int64
#else /* !NT, assume standard */
#define longlong long long
#endif /* !NT */
#define str_longlong STR_DEF(longlong)
#endif /* ALLOW64 */
/* Machine/Language architectural specifications */
typedef struct {
int bits; /* Bits in this data type */
char *name; /* Name used to specify this type */
int align; /* Non-zero if this type should be accessed aligned */
} dtypes;
#define MXDTYPES 6
typedef struct {
int bigend; /* Non-zero if this is a bigendian architecture */
int uwa; /* Use wide memory access */
int pbits; /* Number of bits in a pointer */
int nords; /* Number of ord types */
dtypes ords[MXDTYPES]; /* Ordinal types, in size order */
int natord; /* Index of natural machine ordinal */
int nints; /* Number of int types */
dtypes ints[MXDTYPES]; /* Integer types, in size order */
int natint; /* Index of natural machine integer */
/* Optimisation settings */
int shfm; /* Non-zero to use shifts for masking */
int oscale; /* Maximum power of 2 scaled indexing mode, 0 for none. */
int smmul; /* Has fast small multiply for index scaling */
} mach_arch;
#endif /* IMDI_ARCH_H */

View File

@@ -0,0 +1,319 @@
/* Integer Multi-Dimensional Interpolation */
/*
* Copyright 2000 - 2007 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
/*
* Code generation support that translates between the higher level
* gendesc, and the low level genspec.
*/
#undef VERBOSE
/*
Ideal grid resolutions for 8/16 bit precision calculations:
There are a limited number of grid resolution and grid cells
sub resolution values that work perfectly, and allow every possible
input value to map to a precise interpolation value. For any
system that deals with Lab data, it is also better if there is
a grid point near a,b == 0, meaning that an odd grid size is
preferable for 3 dimensional Lab input conversions. Reasonable memory
usage is usually somewhere between 100K and 1M entries for
the grid table, limiting the maximum grid resolution.
The following lists the some of the possible grid and sub grid
resolutions in order of best to worst. (Fewer jumps is better).
Grid Sub8 Round8 Sub16 Round16 Jumps
4 85 85 21845 21845 0
6 51 51 13107 13107 0
16 17 17 4369 4369 0
18 15 15 3855 3855 0
52 5 5 1285 1285 0
86 3 3 771 771 0
256 1 1 257 257 0
258 255 255 0
772 85 85 0
1286 51 51 0
3856 17 17 0
4370 15 15 0
13108 5 5 0
21846 3 3 0
65536 1 1 0
3 127.5 128 1
5 63.75 64 1
9 31.875 32 1
17 15.937 16 1
33 7.968 8 1
65 3.984 4 1
128 2.007 2 1
129 1.992 2 1
255 1.003 1 1
12 23.188 23 2
24 11.086 11 2
254 1.007 1 2
7 42.5 43 3
8 36.428 36 3
10 28.333 28 3
13 21.25 21 3
15 18.214 18 3
19 14.166 14 3
22 12.142 12 3
29 9.107 9 3
37 7.083 7 3
43 6.071 6 3
44 5.930 6 3
64 4.047 4 3
85 3.035 3 3
87 2.965 3 3
127 2.023 2 3
130 1.976 2 3
253 1.011 1 3
[8 bit: sub = 255/(grid-1), jumps = abs((grid-1)*round(sub)-255)]
[16 bit: sub = 65535/(grid-1), jumps = abs((grid-1)*round(sub)-65535)]
The above takes into consideration the mapping of the sub-cell or
simplex table resolution, but doesn't take into account the quantizing
of the sub-cell weighting values into the range 0..256 or 0..65536.
This will be best when round(sub) divides evenly into 256 or 65536,
so grid resolutions of 3, 5, 9, 17, 33, 65, 128, 129, 255 may be the
best choice for sort algorithm grid resolutions.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "copyright.h"
#include "aconfig.h"
#include "imdi_utl.h"
#include "imdi_arch.h"
#include "imdi_gen.h"
static void translate_pixrep(pixlayout *pl, char **desc, int *prec, imdi_pixrep rep, int dim, mach_arch *a);
/* Translate between a gendesc and genspec */
int /* Return number of combinations possible */
set_genspec(
genspec *gs, /* Return specification */
gendesc *gd, /* Input description */
int comb, /* Combination index */
mach_arch *a /* Machine architecture */
) {
int nc = 1; /* Number of combinations */
int nidc, id; /* Number of input dimension combinations, current index */
int nodc, od; /* Number of output dimension combinations, current index */
int nirc, ir; /* Number of input, prec. & out representations combinations, cnt index */
int pc, or; /* Precision combination index, Output combination index */
int ndc, opt; /* Number of direction stride ombinations, current index */
int tt;
/* Figure out how many combinations there are */
for (nidc = 0; gd->idcombs[nidc] != 0; nidc++) /* Input dimension */
;
nc *= nidc;
for (nodc = 0; gd->odcombs[nodc] != 0; nodc++) /* Output dimension */
;
nc *= nodc;
for (nirc = 0; gd->incombs[nirc] != 0; nirc++) /* Input/Precision/Output representation */
;
nc *= nirc;
for (tt = 0; gd->iprecs[tt] != 0; tt++) /* Internal precision representation */
;
if (nirc != tt) {
fprintf(stderr,"imdi_gen: Must be equal numberof input and precision representations\n");
exit(-1);
}
for (tt = 0; gd->outcombs[tt] != 0; tt++) /* Output representation */
;
if (nirc != tt) {
fprintf(stderr,"imdi_gen: Must be equal numberof input and output representations\n");
exit(-1);
}
for (ndc = 0; gd->optcombs[ndc] != opts_end; ndc++) /* Direction and stride options */
;
nc *= ndc;
if (nc <= 0) {
fprintf(stderr,"imdi_gen: no valid combinations specified for kernel generation\n");
exit(-1);
}
if (comb < nc) { /* If we are within a legal combination */
int iprec, oprec;
char *idesc, *odesc; /* Representation descriptions */
char *ddesc; /* Direction description */
id = comb % nidc;
comb /= nidc;
od = comb % nodc;
comb /= nodc;
ir = comb % nirc;
comb /= nirc;
pc = ir; /* In and precision combs track together */
or = ir; /* In and out combs track together */
opt = comb % ndc;
comb /= ndc;
#ifdef VERBOSE
printf("Combination id = %d, od = %d, ir = %d, pc = %d, or = %d, opt = %d\n",
id,od,ir,pc,or,opt);
#endif /* VERBOSE */
gs->id = gd->idcombs[id]; /* Input dimensions */
gs->itres = gd->itres[id]; /* Interpolation table resolution */
gs->stres = gd->stres[id]; /* Simplex table resolution */
gs->od = gd->odcombs[od]; /* Output dimensions */
gs->oopt = gd->ooptcombs[od]; /* Output per channel options */
if (gs->id > IXDI) {
fprintf(stderr,"imdi_gen: Input dimension %d exceeds limit %d\n",gs->id,IXDI);
exit(-1);
}
if (gs->od > IXDO) {
fprintf(stderr,"imdi_gen: Output dimension %d exceeds limit %d\n",gs->od,IXDO);
exit(-1);
}
/* Input representation */
gs->irep = gd->incombs[ir]; /* Keep a copy of this */
translate_pixrep(&gs->in, &idesc, &iprec, gd->incombs[ir], gs->id, a);
gs->in_signed = 0x0; /* Not used during generation, used at runtime setup */
/* Output representation */
gs->orep = gd->outcombs[or]; /* Keep a copy of this */
translate_pixrep(&gs->out, &odesc, &oprec, gd->outcombs[or], gs->od, a);
gs->out_signed = 0x0; /* Not used during generation, used at runtime setup */
COMPUTE_IPREC(gs->prec, gs->irep, gd->iprecs[pc], gs->orep)
gs->opt = gd->optcombs[opt]; /* Direction and stride options */
if (((gs->opt & opts_splx_sort) && (gs->opt & opts_sort_splx))
|| ((gs->opt & opts_splx_sort) && (gs->opt & opts_splx))
|| ((gs->opt & opts_sort_splx) && (gs->opt & opts_splx))) {
fprintf(stderr,"imdi_gen: Conflict in simplex/sort preferences\n");
exit(-1);
}
ddesc = gs->opt & opts_bwd ? "b" : "f"; /* Direction description */
#ifdef VERBOSE
printf("translates to prec = %d, id = %d, od = %d, itres %d, stdres %d\n",
gs->prec,gs->id,gs->od,gs->itres,gs->stres);
#endif /* VERBOSE */
/* Create a concise description string */
sprintf(gs->kdesc,"%d_%d_%s_%s_%s", gs->id, gs->od, idesc, odesc, ddesc);
}
return nc;
}
/* Convert the high level pixrep into the lower level pixel layout */
static void
translate_pixrep(
pixlayout *pl, /* pixlayout to initialise */
char **desc, /* Return description identifier (may be NULL) */
int *prec, /* Return basic precision specifier (may be NULL) */
imdi_pixrep rep, /* Representation to be translated */
int dim, /* Number of dimensions (values/pixel) */
mach_arch *a /* Machine architecture */
) {
switch (rep) {
case pixint8: { /* 8 Bits per value, pixel interleaved, no padding */
int i;
/* Could optimise this to packed for dim == 4 ~~~~ */
pl->pint = 1; /* pixel interleaved */
pl->packed = 0; /* Not packed */
for (i = 0; i < dim; i++) {
pl->bpch[i] = 8; /* Bits per channel */
pl->chi[i] = dim; /* Channel increment */
pl->bov[i] = 0; /* Bit offset to value within channel */
pl->bpv[i] = 8; /* Bits per value within channel */
}
if (prec != NULL)
*prec = 8; /* Basic 8 bit precision */
if (desc != NULL)
*desc = "i8"; /* Interleaved 8 bit */
} break;
case planeint8: { /* 8 bits per value, plane interleaved */
int i;
pl->pint = 0; /* Not pixel interleaved */
pl->packed = 0; /* Not packed */
for (i = 0; i < dim; i++) {
pl->bpch[i] = 8; /* Bits per channel */
pl->chi[i] = 1; /* Channel increment */
pl->bov[i] = 0; /* Bit offset to value within channel */
pl->bpv[i] = 8; /* Bits per value within channel */
}
if (prec != NULL)
*prec = 8; /* Basic 8 bit precision */
if (desc != NULL)
*desc = "p8"; /* Planar 8 bit */
} break;
case pixint16: { /* 16 Bits per value, pixel interleaved, no padding */
int i;
/* Could optimise this to packed for dim == 4 ~~~~ */
pl->pint = 1; /* pixel interleaved */
pl->packed = 0; /* Not packed */
for (i = 0; i < dim; i++) {
pl->bpch[i] = 16; /* Bits per channel */
pl->chi[i] = dim; /* Channel increment */
pl->bov[i] = 0; /* Bit offset to value within channel */
pl->bpv[i] = 16; /* Bits per value within channel */
}
if (prec != NULL)
*prec = 16; /* Basic 8 bit precision */
if (desc != NULL)
*desc = "i16"; /* Interleaved 16 bit */
} break;
case planeint16: { /* 16 bits per value, plane interleaved */
int i;
pl->pint = 0; /* Not pixel interleaved */
pl->packed = 0; /* Not packed */
for (i = 0; i < dim; i++) {
pl->bpch[i] = 16; /* Bits per channel */
pl->chi[i] = 1; /* Channel increment */
pl->bov[i] = 0; /* Bit offset to value within channel */
pl->bpv[i] = 16; /* Bits per value within channel */
}
if (prec != NULL)
*prec = 16; /* Basic 8 bit precision */
if (desc != NULL)
*desc = "p16"; /* Planar 8 bit */
} break;
default: {
fprintf(stderr,"Warning: Unknown pixel representation %d\n",rep);
} break;
}
}

View File

@@ -0,0 +1,271 @@
#ifndef IMDI_GEN_H
#define IMDI_GEN_H
/* Integer Multi-Dimensional Interpolation */
/*
* Copyright 2000 - 2007 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
/*
* Pixel code generation definitions.
*
* This defines a particular combination of pixel layout,
* number of channels, and other runtime requestable features.
* This is used by the code generation to setup anticipated
* support for these requests, used by the runtime to request
* the features, and by the runtime to identify the correct
* generated module to use.
*
*/
/* -------------------------------------------------- */
/* High level kernel generation description */
/* This is a high level macro desciption of the pixel layout. */
/* It can be expanded by adding a new enumeration, and then */
/* implementing the code in imdi_gen to translate the enumeration */
/* into the exact pixlayout structure details. */
typedef enum {
invalid_rep = 0x00,
pixint8 = 0x01, /* 8 Bits per value, pixel interleaved, no padding */
planeint8 = 0x02, /* 8 bits per value, plane interleaved */
pixint16 = 0x03, /* 16 Bits per value, pixel interleaved, no padding */
planeint16 = 0x04 /* 16 bits per value, plane interleaved */
} imdi_pixrep;
/* The internal processing precision */
typedef enum {
prec_min = 0, /* Minimum of input and output precision */
prec_max = 1, /* Maximum of input and output precision */
prec_in = 2, /* Same as input */
prec_out = 3, /* Same as output */
prec_p8 = 4, /* 8 Bits precision */
prec_p16 = 5 /* 16 Bits precision */
} imdi_iprec;
/* Output per channel processing options. For the compiled */
/* kernels, this is indexed by physical output channel, */
/* (not to be confused with the runtime oopt which is indexed */
/* by callback channel). */
/* - shift left by channel no * 2 to access option. */
/* Note that oopts_skip valid only for plane interleaved, */
/* and doesn't change the number output channels looked up, */
/* it changes the number of output channels written, hence */
/* must be matched by the arguments to interp() (number of */
/* output pointers, stride etc.) */
typedef enum {
oopts_none = 0x0, /* No extra options */
oopts_check = 0x1, /* Test channel value against trigger */
oopts_skip = 0x2, /* Don't write channel value */
oopts_chskp = 0x3 /* oopts_check + oopts_skip */
} imdi_ooptions;
/* Macro to create an instance of imdi_ooptions for a particular channel */
#define OOPT(flag,chan) ((flag) << (chan * 2))
/* Macro to extract the flags particular channel */
#define OOPTX(val,chan) (0x3 & ((val) >> (chan * 2)))
/* Value of no oopt flags set */
#define OOPTS_NONE 0x00000000
/* Mask to detect any oopts_check flags that are set */
#define OOPTS_CHECK 0x55555555
/* Mask to ignore any oopts_check flags that are set */
#define OOPTS_NOT_CHECK 0xAAAAAAAA
/* Mask to detect any oopts_skip flags that are set */
#define OOPTS_SKIP 0xAAAAAAAA
/* Mask to ignore any oopts_skip flags that are set */
#define OOPTS_NOT_SKIP 0x55555555
/* Processing options */
/* Note that there will be a choice between simplex lookup or sort algoritm for */
/* only a subset of kernels (8 bits processing precision, <= 4 input channels) */
typedef enum {
opts_none = 0x00, /* Forward direction, no stride */
opts_fwd = 0x01, /* Forwards direction (default is gen fwd/run don't care) */
opts_bwd = 0x02, /* Backwards direction (default is gen fwd/run don't care) */
opts_istride = 0x04, /* Stride on input */
opts_ostride = 0x08, /* Stride on output */
opts_splx_sort = 0x10, /* Prefer simplex over sort algorithm (generate both) */
opts_sort_splx = 0x20, /* Force sort algorithm, rather than simplex table (generate both) */
opts_splx = 0x40, /* Generate simplex only (when possible), default is sort only. */
opts_end = 0x80 /* End marker */
} imdi_options;
/* This sructure allows a series of related kernels to be generated */
#define MX_GDCS 20
/* * means multiplies combination */
/* + means lockstep with previous line */
typedef struct {
int idcombs[MX_GDCS]; /* * Input dimension combinations (0 at end) */
int itres[MX_GDCS]; /* + Interpolation table resolutions for */
int stres[MX_GDCS]; /* + Simplex table resolutions */
int odcombs[MX_GDCS]; /* * Output dimensions combinations (0 at end) */
imdi_ooptions ooptcombs[MX_GDCS]; /* + output per channel options */
imdi_pixrep incombs[MX_GDCS]; /* * Input pixel representation */
imdi_iprec iprecs[MX_GDCS]; /* + Internal precision */
imdi_pixrep outcombs[MX_GDCS]; /* + Output pixel representation */
imdi_options optcombs[MX_GDCS]; /* * Direction and stride options */
} gendesc;
/* -------------------------------------------------- */
/* Detailed level of generation specification */
/* Pixel layout: */
/* Each channel value is assumed to be read with a */
/* native machine single read of size bpch, */
/* and bov and bpv being bit indexes into that value. */
/* */
/* If pint == 0, then each read will be of size bpch[], and will */
/* have its own pointer, will be incremented by chi[]. */
/* If pint != 0, then the reads will be size bpch[0], from successive */
/* locations, chi[] apart. */
/* */
/* If packed == 0, then separate reads are needed for each input */
/* channel. */
/* If packed != 0, then the channel values will be extracted */
/* from a single read of size bpch[0] */
/* */
/* Note that at all times the bit offset and size values */
/* will be obeyed for each input value. */
/* NOTE :- if you change this, you need to change the code in cgen.c */
/* labeled !genspec and tabspec delta code! */
typedef struct {
int bpch[IXDIDO]; /* Bits per channel read (must be divisible by 8) */
int chi[IXDIDO]; /* channel increment in multiples of bpch[] (0 == dimensionality) */
int bov[IXDIDO]; /* Bit offset to value within channel */
int bpv[IXDIDO]; /* Bits per value within channel */
int pint; /* Flag - nonz if pixel interleaved (ie. reads from successice locations) */
int packed; /* Flag - nonz if all channels are packed into a single read */
} pixlayout;
/* Structure that specifies the configuration of a generated interpolation kernel. */
/* NOTE :- if you change this, you need to change the code in cgen.c */
/* labeled !genspec and tabspec delta code! */
typedef struct {
/* Input to code generator */
int prec; /* Internal precision:- either 8 or 16 bits */
int id; /* Number of input dimensions used for interpolation */
int od; /* Number of output dimensions created by interpolation */
imdi_pixrep irep; /* High level input pixel representation */
imdi_pixrep orep; /* High level output pixel representation */
int in_signed; /* Bit flag per channel, NZ if treat as signed (runtime setup) */
int out_signed; /* Bit flag per channel, NZ if treat as signed (runtime setup) */
pixlayout in; /* Input pixel layout */
pixlayout out; /* Output pixel layout */
imdi_ooptions oopt; /* output per channel options */
imdi_options opt; /* Direction and stride options */
int itres; /* Interpolation table resolution */
int stres; /* Simplex table resolution */
/* Returned value */
char kkeys[100]; /* Kernel keys */
char kdesc[100]; /* At genspec time */
char kname[100]; /* At generation time */
} genspec;
/* - - - - - - - - - - - - - - - - - - - - - - - */
/* Translate between high level and low level generation specification */
int set_genspec(genspec *gs, gendesc *gd, int comb, mach_arch *a);
/* - - - - - - - - - - - - - - - - - - - - - - - */
/* Convert the input and output pixel representation and the internal */
/* precision choice into a precision in bits */
/* (Used at code gen and code execution, hence defined as a macro) */
#define COMPUTE_IPREC(PRECOUT, INREP, IPREC, OUTREP) \
{ \
int _iprec, _oprec; \
\
switch (INREP) { \
default: \
case pixint8: \
case planeint8: \
_iprec = 8; \
break; \
case pixint16: \
case planeint16: \
_iprec = 16; \
break; \
} \
switch (OUTREP) { \
default: \
case pixint8: \
case planeint8: \
_oprec = 8; \
break; \
case pixint16: \
case planeint16: \
_oprec = 16; \
break; \
} \
switch (IPREC) { \
default: \
case prec_min: \
PRECOUT = _iprec < _oprec ? _iprec : _oprec; \
break; \
case prec_max: \
PRECOUT = _iprec > _oprec ? _iprec : _oprec; \
break; \
case prec_in: \
PRECOUT = _iprec; \
break; \
case prec_out: \
PRECOUT = _oprec; \
break; \
case prec_p8: \
PRECOUT = 8; \
break; \
case prec_p16: \
PRECOUT = 16; \
break; \
} \
} \
/* - - - - - - - - - - - - - - - - - - - - - - - */
struct _tabspec;
/* Supported code generators: */
/* The 'C' code generator */
/* Generate a source file to implement the specified */
/* interpolation kernel. Fill in return values and return 0 if OK. */
/* Return 1 if this kernel should be skipped (ie. force sort and sort not forced) */
/* and some other anon-zero on error. */
int gen_c_kernel(genspec *g, struct _tabspec *t, mach_arch *a,
FILE *fp, int index, genspec *og, struct _tabspec *ot);
/* asm, MMX, etc. generators declarations go here ! */
#endif /* IMDI_GEN_H */

View File

@@ -0,0 +1,514 @@
/* Integer Multi-Dimensional Interpolation */
/*
* Copyright 2000 - 2007 Graeme W. Gill
* All rights reserved.
*
* This material is licensed under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
/*
* Top level kernel code generator
*
* This module is invoked from the make system,
* and generates all the versions and configurations of
* the IMDI kernel code. It includes all the generated
* files in imdi_k.h, which also contains a table
* so that the run time code knows what kernels
* are available.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdarg.h>
#include <string.h>
#include "copyright.h"
#include "aconfig.h"
#include "imdi.h"
#include "imdi_tab.h"
#ifndef MAXNAMEL
# define MAXNAMEL 512 /* Maximum command line filename lengths */
#endif
#undef VERBOSE
#undef TEST1 /* Generate one test case */
/*
Ideal grid resolutions for 8 bit precision calculations.
See imdi_gen.c for a more detailed list.
Grid Jumps
4 0
6 0
16 0
18 0
52 0
86 0
256 0
3 1
5 1
9 1
17 1
33 1
65 1
128 1
129 1
255 1
*/
/* The following structure initialisations define what kernel routines should be built */
static
gendesc descs[] = {
#ifdef TEST1
{
{ 3, 0 }, /* * Input dimension combinations */
{ 33, 0 }, /* + Interpolation table resolutions */
{ 8, 0 }, /* + Min Simplex table resolutions */
{ 4, 0 }, /* * Output dimension combinations */
{OOPT(oopts_check,3), oopts_none}, /* + Output channel options */
{pixint8, 0 }, /* * Input pixel representation */
{prec_p16, 0}, /* + Internal precision */
{pixint8, 0}, /* + Output pixel representation */
{opts_sort_splx, opts_end} /* * Direction & stride combinations */
// {opts_splx_sort, opts_end} /* * Direction & stride combinations */
}
#else /* !TEST1 */
/* A reasonably full set of combinations */
/* * means multiplies combination */
/* + means lockstep with previous line */
{
{ 1, 3, 4, 5, 6, 7, 8, 9, 10, 0 }, /* * Input dimension combinations */
{ 256, 33, 18, 16, 12, 8, 7, 6, 5, 0 }, /* + Min Interpolation table resolutions */
{ 1, 8, 17, 1, 1, 1, 1, 1, 1, 0 }, /* + Min Simplex table resolutions */
{ 1, 3, 4, 5, 6, 7, 8, 9, 10, 0 }, /* * Output dimension combinations */
{oopts_none, oopts_none, oopts_none, oopts_none, oopts_none, oopts_none,
oopts_none, oopts_none, oopts_none, oopts_none, oopts_none, oopts_none},
/* + Output channel options */
{pixint8, pixint16, pixint8, pixint16, pixint16, 0 }, /* * Input pixel representation */
{prec_p8, prec_p8, prec_p8, prec_p16, prec_p16, 0 }, /* + Internal precision */
{pixint8, pixint8, pixint16, pixint16, pixint16, 0 }, /* + Output pixel representation */
{
opts_splx_sort, /* (both, but default to simple alg, no stride) */
opts_istride | opts_ostride, /* + (Sort only with stride) */
opts_end } /* * Direction & stride combinations */
}
#endif /* !TEST1 */
};
void set_architecture(mach_arch *ar, int use64);
struct _knamestr {
char name[MAXNAMEL+1];
char desc[MAXNAMEL+1];
struct _knamestr *next;
}; typedef struct _knamestr knamestr;
knamestr *
new_knamestr(char *name, char *desc) {
knamestr *kn;
if ((kn = (knamestr *)malloc(sizeof(knamestr))) == NULL) {
fprintf(stderr,"new_knamestr malloc failed\n");
exit(-1);
}
strcpy(kn->name, name);
strcpy(kn->desc, desc);
kn->next = NULL;
return kn;
}
void usage(void) {
fprintf(stderr,"Make imdi kernel code Version %s\n",ARGYLL_VERSION_STR);
fprintf(stderr,"usage: imdi_make [-i]\n");
fprintf(stderr," -d dir Directory to create them in (default .)\n");
fprintf(stderr," -i Individial Files\n");
fprintf(stderr," -f Force 64 bit\n");
exit(1);
}
int
main(int argc, char *argv[]) {
int fa,nfa; /* argument we're looking at */
int indiv = 0; /* Individual files */
int rv;
int dn, tnd;
genspec gs, ogs;
tabspec ts, ots;
mach_arch ar;
int ix = 1; /* kernel index */
knamestr *list = NULL, *lp = NULL;
#if defined(ALLOW64) && defined(USE64)
int use64 = 1;
#else
int use64 = 0;
#endif
static char dirname[MAXNAMEL+1+1] = ""; /* Output directory name */
static char temp[MAXNAMEL+100+1]; /* Buffer to compose filenames in */
FILE *kcode = NULL; /* Kernel routine code file */
FILE *kheader; /* Kernel routine header file */
/* Zero out the gen and tabspecs, to give diff a place to start */
memset((void *)&ogs, 0, sizeof(genspec));
memset((void *)&gs, 0, sizeof(genspec));
memset((void *)&ots, 0, sizeof(tabspec));
memset((void *)&ts, 0, sizeof(tabspec));
/* Process the arguments */
for(fa = 1;fa < argc;fa++) {
nfa = fa; /* skip to nfa if next argument is used */
if (argv[fa][0] == '-') { /* Look for any flags */
char *na = NULL; /* next argument after flag, null if none */
if (argv[fa][2] != '\000')
na = &argv[fa][2]; /* next is directly after flag */
else {
if ((fa+1) < argc) {
if (argv[fa+1][0] != '-') {
nfa = fa + 1;
na = argv[nfa]; /* next is seperate non-flag argument */
}
}
}
if (argv[fa][1] == '?') {
usage();
}
/* Destination directory */
else if (argv[fa][1] == 'd' || argv[fa][1] == 'D') {
int len;
fa = nfa;
if (na == NULL) usage();
strncpy(dirname,na,MAXNAMEL); dirname[MAXNAMEL] = '\000';
len = strlen(dirname);
if (len > 0) {
if (dirname[len-1] != '/' && dirname[len-1] != '\\')
strcat(dirname, "/");
}
}
/* Individual files */
else if (argv[fa][1] == 'i' || argv[fa][1] == 'I') {
indiv = 1;
}
/* Force 64 bit */
else if (argv[fa][1] == 'f' || argv[fa][1] == 'F') {
#ifdef ALLOW64
use64 = 1;
#else
fprintf(stderr,"ALLOW64 bits is undefined\n");
usage();
#endif
}
else {
usage();
}
} else
break;
}
set_architecture(&ar, use64);
/* Open the file for kernel routine declaration header */
sprintf(temp, "%simdi_k.h",dirname);
if ((kheader = fopen(temp, "w")) == NULL) {
fprintf(stderr,"imdi_make: unable to open file '%s'\n",temp);
exit(-1);
}
if (!indiv) {
sprintf(temp, "%simdi_k.c",dirname);
if ((kcode = fopen(temp, "w")) == NULL) {
fprintf(stderr,"imdi_make: unable to open file '%s'\n",temp);
exit(-1);
}
}
tnd = sizeof(descs)/sizeof(gendesc); /* Total number of descriptions */
#ifdef VERBOSE
printf("Number of descriptions = %d\n",tnd);
#endif /* VERBOSE */
fprintf(kheader,"/* Integer Multi-Dimensional Interpolation */\n");
fprintf(kheader,"/* Declarations for all the generated kernel functions */\n");
fprintf(kheader,"/* This file is generated by imdi_make */\n\n");
fprintf(kheader,"/* Copyright 2000 - 2007 Graeme W. Gill */\n");
fprintf(kheader,"/* All rights reserved. */\n");
fprintf(kheader,"/* This material is licensed under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :- */\n");
fprintf(kheader,"/* see the License.txt file for licensing details.*/\n");
fprintf(kheader,"\n");
/* For all the descriptions */
for (dn = 0; dn < tnd; dn++) {
int cb, ncb;
/* Do all combinations for that description */
for (cb = 0, ncb = 1; cb < ncb; cb++) {
int nalg, alg;
char ofname[100] = "indiv"; // ~~~999 this isn't right...
/* Compute generate spec. and number of combinations */
ncb = set_genspec(&gs, &descs[dn], cb, &ar);
if (indiv) {
sprintf(temp, "%s%s.c",dirname,ofname);
if ((kcode = fopen(temp, "w")) == NULL) {
fprintf(stderr,"imdi_make: unable to open file '%s'\n",temp);
exit(-1);
}
}
nalg = 2; /* By default generate just sort algorithm */
alg = 1;
if ((gs.opt & opts_splx_sort)
|| (gs.opt & opts_sort_splx)) {
alg = 0; /* Generate both simplex and sort algorithms */
}
if (gs.opt & opts_splx) {
nalg = 1; /* Generate just simplex algorithm */
alg = 0;
}
for (; alg < nalg; alg++) {
if (alg == 0)
gs.opt |= opts_splx;
else
gs.opt &= ~opts_splx;
/* Generate it */
rv = gen_c_kernel(&gs, &ts, &ar, kcode, ix, &ogs, &ots);
if (rv != 0 && rv != 1) {
fprintf(stderr,"imdi_make: gen_c_kernel returned a err %d\n",rv);
exit(-1);
}
/* Add the name to the list */
if (list == NULL)
lp = list = new_knamestr(gs.kname, gs.kdesc);
else {
lp->next = new_knamestr(gs.kname, gs.kdesc);
lp = lp->next;
}
if (indiv) {
if (fclose(kcode) != 0) {
fprintf(stderr,"imdi_make: unable to close file '%s'\n",ofname);
exit(-1);
}
}
ogs = gs; /* Structure copy */
ots = ts;
ix++;
if (rv == 0)
break; /* there was only sort available */
}
}
}
/* Include the kernel functions in the header file */
if (indiv) {
for(lp = list; lp != NULL; lp = lp->next) {
fprintf(kheader,"#include \"%s_%s.c\"\n",lp->name,lp->desc);
}
} else {
fprintf(kheader,"#include \"imdi_k.c\" /* All the kernel code */\n");
}
fprintf(kheader,"\n");
/* Output function table */
fprintf(kheader,
"struct {\n"
" void (*interp)(imdi *s, void **outp, int ostride, void **inp, int istride, unsigned int npix);\n"
" void (*gentab)(genspec *g, tabspec *t);\n"
"} ktable[%d] = {\n",ix-1);
for(lp = list; lp != NULL; lp = lp->next) {
fprintf(kheader,"\t{ %s, %s_gentab }%s\n", lp->name, lp->name,
lp->next != NULL ? "," : "");
}
fprintf(kheader,"};\n");
fprintf(kheader,"\n");
fprintf(kheader,"int no_kfuncs = %d;\n",ix-1);
fprintf(kheader,"\n");
if (!indiv) {
if (fclose(kcode) != 0) {
fprintf(stderr,"imdi_make: unable to close file 'imdi_k.c'\n");
exit(-1);
}
}
if (fclose(kheader) != 0) {
fprintf(stderr,"imdi_make: unable to close file 'imdi_k.h'\n");
exit(-1);
}
/* Free the kname list */
for(lp = list; lp != NULL;) {
char *p = (char *)lp;
lp = lp->next;
free(p);
}
return 0;
}
/* - - - - - - - - - - - - - - - - - - - - - - - */
/* Initialse the architecture structure properly. */
/* We're doing this purely at run time, on the assumption */
/* that the target machine is the one we're running on. */
/* We would have to do this differently in a cross development */
/* environment. */
void
set_architecture(
mach_arch *ar,
int use64
) {
unsigned long etest = 0xff;
char *machtype; /* Environment value */
if (*((unsigned char *)&etest) == 0xff) {
ar->bigend = 0; /* Little endian */
} else {
ar->bigend = 1; /* Big endian endian */
}
machtype = getenv("MACHTYPE");
/* Unfortunetaly many environments don't export MACHTYPE :-( */
/* so we implement a fall back */
if (machtype == NULL) {
#ifdef __ppc__
machtype = "powerpc";
#endif
}
if (machtype != NULL && strcmp(machtype, "powerpc") == 0) {
/* Section tunable for PowerPC */
ar->uwa = 0; /* Use wide memory access */
ar->shfm = 0; /* Use shifts to mask values */
ar->oscale = 8; /* Has scaled indexing up to * 8 */
ar->smmul = 0; /* Doesn't have fast small multiply for index scaling */
if (use64) {
ar->nords = 4; /* Number of ord types */
ar->nints = 4; /* Number of int types */
} else {
ar->nords = 3; /* Number of ord types */
ar->nints = 3; /* Number of int types */
}
ar->natord = 2; /* Most natural type (assume unsigned int) */
ar->natint = 2; /* Most natural type (assume int) */
ar->pbits = sizeof(void *) * 8; /* Number of bits in a pointer */
ar->ords[0].bits = 8 * sizeof(unsigned char);
ar->ords[0].name = "unsigned char";
ar->ords[0].align = 1;
ar->ords[1].bits = 8 * sizeof(unsigned short);
ar->ords[1].name = "unsigned short";
ar->ords[1].align = 1;
ar->ords[2].bits = 8 * sizeof(unsigned int);
ar->ords[2].name = "unsigned int";
ar->ords[2].align = 1;
#ifdef ALLOW64
ar->ords[3].bits = 8 * sizeof(unsigned longlong);
ar->ords[3].name = "unsigned " str_longlong ;
ar->ords[3].align = 0;
#endif /* ALLOW64 */
ar->ints[0].bits = 8 * sizeof(signed char);
ar->ints[0].name = "signed char";
ar->ints[0].align = 1;
ar->ints[1].bits = 8 * sizeof(short);
ar->ints[1].name = "short";
ar->ints[1].align = 1;
ar->ints[2].bits = 8 * sizeof(int);
ar->ints[2].name = "int";
ar->ints[2].align = 1;
#ifdef ALLOW64
ar->ints[3].bits = 8 * sizeof(longlong);
ar->ints[3].name = str_longlong ;
ar->ints[3].align = 0;
#endif /* ALLOW64 */
} else {
/* Currently assume x86 type */
ar->uwa = 0; /* Use wide memory access */
ar->shfm = 0; /* Use shifts to mask values */
ar->oscale = 8; /* Has scaled indexing up to * 8 */
ar->smmul = 0; /* Doesn't have fast small multiply for index scaling */
if (use64) {
ar->nords = 4; /* Number of ord types */
ar->nints = 4; /* Number of int types */
} else {
ar->nords = 3; /* Number of ord types */
ar->nints = 3; /* Number of int types */
}
ar->natord = 2; /* Most natural type (assume unsigned int) */
ar->natint = 2; /* Most natural type (assume int) */
ar->pbits = sizeof(void *) * 8; /* Number of bits in a pointer */
ar->ords[0].bits = 8 * sizeof(unsigned char);
ar->ords[0].name = "unsigned char";
ar->ords[0].align = 1;
ar->ords[1].bits = 8 * sizeof(unsigned short);
ar->ords[1].name = "unsigned short";
ar->ords[1].align = 1;
ar->ords[2].bits = 8 * sizeof(unsigned int);
ar->ords[2].name = "unsigned int";
ar->ords[2].align = 1;
#ifdef ALLOW64
ar->ords[3].bits = 8 * sizeof(unsigned longlong);
ar->ords[3].name = "unsigned " str_longlong ;
ar->ords[3].align = 0;
#endif /* ALLOW64 */
ar->ints[0].bits = 8 * sizeof(signed char);
ar->ints[0].name = "signed char";
ar->ints[0].align = 1;
ar->ints[1].bits = 8 * sizeof(short);
ar->ints[1].name = "short";
ar->ints[1].align = 1;
ar->ints[2].bits = 8 * sizeof(int);
ar->ints[2].name = "int";
ar->ints[2].align = 1;
#ifdef ALLOW64
ar->ints[3].bits = 8 * sizeof(longlong);
ar->ints[3].name = str_longlong ;
ar->ints[3].align = 0;
#endif /* ALLOW64 */
}
}

View File

@@ -0,0 +1,803 @@
/* Integer Multi-Dimensional Interpolation */
/*
* Copyright 2000 - 2007 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
/*
* Run time table allocater and initialiser
*
* The function here that knows how to create the
* appropriate run time tables for our chosen kernel,
* and the type color mapping we want to perform.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdarg.h>
#include <string.h>
#include "imdi.h"
#include "imdi_tab.h"
#undef VERBOSE
#undef ASSERTS /* Check asserts */
#ifdef ASSERTS
#include <numlib.h>
#endif
typedef unsigned char byte;
/* Left shift, handles >= 32 properly */
#define LSHIFT(aa, bb) ((bb) <= 31 ? ((aa) << (bb)) : (((aa) << 31) << ((bb)-31)))
/* The big value type used to represent table entries */
#ifdef ALLOW64
typedef unsigned longlong bvt;
#else
typedef unsigned long bvt;
#endif
/* Specific entry size write routine */
void write_uchar(
byte *p,
bvt v
) {
*((unsigned char *)p) = (unsigned char)v;
}
void write_ushort(
byte *p,
bvt v
) {
*((unsigned short *)p) = (unsigned short)v;
}
void write_uint(
byte *p,
bvt v
) {
*((unsigned int *)p) = (unsigned int)v;
}
void write_ulong(
byte *p,
bvt v
) {
*((unsigned long *)p) = (unsigned long)v;
}
#ifdef ALLOW64
void write_ulonglong(
byte *p,
bvt v
) {
*((unsigned longlong *)p) = (unsigned longlong)v;
}
#endif /* ALLOW64 */
void write_default(
byte *p,
bvt v
) {
fprintf(stderr,"imdi_tabl: internal failure - unexpected write size!\n");
exit(-1);
}
/* Array of write routines */
void (*write_entry[16])(byte *p, bvt v);
static void
init_write_tab(void) {
int i;
for (i = 0; i < 16; i++)
write_entry[i] = write_default; /* Make sure any un-inited access bombs */
write_entry[sizeof(unsigned char)] = write_uchar;
write_entry[sizeof(unsigned short)] = write_ushort;
write_entry[sizeof(unsigned int)] = write_uint;
write_entry[sizeof(unsigned long)] = write_ulong;
#ifdef ALLOW64
write_entry[sizeof(unsigned longlong)] = write_ulonglong;
#endif /* ALLOW64 */
}
/* Input offset adjustment table */
double in_adj[] = {
8.0324820232182659e+281, 1.3051220361353854e+214, 1.5654418860154115e-076,
6.6912978722165055e+281, 1.2369092402930559e+277, 1.4097588049607207e-308,
7.7791723264456369e-260, 3.6184161952648606e+238, 5.8235640814908141e+180,
9.1271554315814989e-072, 5.4310198502711138e+241, 2.7935452404894958e+275,
-2.9408705449902027e+003
};
/* Table creation function */
imdi_imp *
imdi_tab(
genspec *gs, /* Pointer to gen spec */
tabspec *ts, /* Pointer to table spec */
imdi_conv cnv, /* Runtime argument conversion needed */
imdi_pixrep irep, /* High level input pixel representation to match */
imdi_pixrep orep, /* High level output pixel representation to match */
void (*interp)(struct _imdi *s, void **outp, int outst, /* Underlying conversion function */
void **inp, int inst,
unsigned int npixels),
int *inm, /* Input raster channel to callback channel mapping, NULL for none. */
int *outm, /* Output raster channel to callback channel mapping, NULL for none. */
imdi_ooptions oopt, /* Output per channel options (Callback channel, NOT output channel) */
unsigned int *checkv, /* Output channel check values (Callback channel, NULL for none == 0. */
/* Callbacks to lookup the mdi table values */
void (*input_curves) (void *cntx, double *out_vals, double *in_vals),
void (*md_table) (void *cntx, double *out_vals, double *in_vals),
void (*output_curves)(void *cntx, double *out_vals, double *in_vals),
void *cntx /* Context to callbacks */
) {
static int inited = 0;
static int bigend = 0;
int i, e, f;
imdi_imp *it;
unsigned long etest = 0xff;
int idinc[IXDI+1]; /* Increment for each dimension of interp table. */
int ibdinc[IXDI+1]; /* idinc[] in bytes */
int sdinc[IXDI+1]; /* Increment for each dimension of simplex table. */
int sbdinc[IXDI+1]; /* sdinc[] in bytes */
#ifdef VERBOSE
printf("imdi_tab called\n");
#endif
if (inited == 0) {
init_write_tab();
if (*((unsigned char *)&etest) == 0xff)
bigend = 0; /* Little endian */
else
bigend = 1; /* Big endian */
inited = 1;
}
if ((it = (imdi_imp *)calloc(1, sizeof(imdi_imp))) == NULL) {
#ifdef VERBOSE
printf("malloc imdi_imp size %d failed\n",sizeof(imdi_imp));
#endif
return NULL; /* Should we signal error ? How ? */
}
it->size = sizeof(imdi_imp);
#ifdef VERBOSE
printf("Allocated imdi_imp structure size %u\n",it->size);
#endif /* VERBOSE */
/* Set runtime matching conversion provided */
it->cnv = cnv;
it->id = gs->id;
it->od = gs->od;
it->cirep = irep; /* Pixel representation interp is called with */
it->corep = orep;
it->firep = gs->irep; /* Pixel representation of function we are going to use */
it->forep = gs->orep;
it->interp = interp;
it->checkf = 0;
/* Compute number of written channels (allow for skip) */
it->wod = it->od;
for (i = 0; i < it->od; i++) {
if ((oopt & OOPT(oopts_skip,i)) != 0)
it->wod--;
}
/* Setup the raster to callback channel mappings */
if (inm != NULL) {
for (e = 0; e < it->id; e++)
it->it_map[e] = inm[e]; /* Copy input */
} else {
for (e = 0; e < it->id; e++)
it->it_map[e] = e; /* Direct mapping */
}
if (outm != NULL) {
for (e = 0; e < it->od; e++)
it->im_map[e] = outm[e]; /* Copy input */
} else {
for (e = 0; e < it->od; e++)
it->im_map[e] = e; /* Direct mapping */
}
if (checkv != NULL) {
for (e = 0; e < it->od; e++)
it->checkv[e] = checkv[it->im_map[e]]; /* Copy input and convert to Output index */
} else {
for (e = 0; e < it->od; e++)
it->checkv[e] = 0; /* Set to zero */
}
/* Compute interp and simplex table dimension increments & total sizes */
idinc[0] = 1;
ibdinc[0] = ts->im_ts;
for (e = 1; e <= it->id; e++) {
idinc[e] = idinc[e-1] * gs->itres;
ibdinc[e] = ibdinc[e-1] * gs->itres;
}
if (!ts->sort) {
sdinc[0] = 1;
sbdinc[0] = ts->sm_ts;
for (e = 1; e <= it->id; e++) {
sdinc[e] = sdinc[e-1] * gs->stres;
sbdinc[e] = sbdinc[e-1] * gs->stres;
}
}
/* First we setup the input tables */
for (e = 0; e < it->id; e++) {
byte *t, *p; /* Pointer to input table, entry pointer */
int ne; /* Number of entries */
int ex; /* Entry index */
double iaf;
int ix = 0; /* Extract flag */
/* Compute number of entries */
if (ts->it_ix && !gs->in.packed) { /* Input is the whole bpch[] size */
ix = 1; /* Need to do extraction in lookup */
if (gs->in.pint) {
ne = (1 << (gs->in.bpch[0])); /* Same size used for all input tables */
} else {
ne = (1 << (gs->in.bpch[e])); /* This input channels size */
}
} else { /* Input is the value size */
ne = (1 << (gs->in.bpv[e])); /* This input values size */
}
/* Allocate the table */
if ((t = (byte *)malloc(ts->it_ts * ne)) == NULL) {
#ifdef VERBOSE
printf("malloc imdi input table size %d failed\n",ts->it_ts * ne);
#endif
return NULL; /* Should we signal error ? How ? */
}
it->size += ts->it_ts * ne;
#ifdef VERBOSE
printf("Allocated input table %d size %u = %u * %u\n",e, ts->it_ts * ne,ts->it_ts,ne);
#endif /* VERBOSE */
/* Compute input adjustment factor */
for (iaf = 0.0, i = 0; i < (sizeof(in_adj)/sizeof(double)-1); i++)
iaf += log(in_adj[i]);
iaf += in_adj[i];
/* For each possible input value, compute the entry value */
for (ex = 0, p = t; ex < ne; ex++, p += ts->it_ts) {
int iiv; /* Integer input value */
int ivr; /* Input value range */
int isb; /* Input sign bit/signed to offset displacement */
double riv; /* Real input value, 0.0 - 1.0 */
double rtv; /* Real transformed value, 0.0 - 1.0 */
double rmi; /* Real interpolation table index */
double rsi; /* Real simplex index */
int imi; /* Interpiolation table index */
int isi = 0; /* Integer simplex index */
int iwe = 0; /* Integer weighting value */
int vo = 0; /* Vertex offset value */
if (ix) { /* Extract value from index */
ivr = ((1 << (gs->in.bpv[e])) -1);
iiv = (ex >> gs->in.bov[e]) & ((1 << (gs->in.bpv[e])) -1);
} else {
ivr = (ne - 1); /* (Should be bpv[e], but take no chances!) */
iiv = ex; /* Input value is simply index */
}
isb = ivr & ~(((unsigned int)ivr) >> 1); /* Top bit */
if (gs->in_signed & (1 << e)) /* Treat input as signed */
iiv = (iiv & isb) ? iiv - isb : iiv + isb; /* Convert to offset from signed */
riv = (double) iiv / (double)ivr; /* Compute floating point */
{
double civ[IXDI], cov[IXDI];
for (f = 0; f < it->id; f++)
civ[f] = riv;
input_curves(cntx, cov, civ); /* Lookup the input table transform */
rtv = iaf * cov[it->it_map[e]];
}
if (rtv < 0.0) /* Guard against sillies */
rtv = 0.0;
else if (rtv > 1.0)
rtv = 1.0;
/* divide into interp base and cube sub index */
rmi = rtv * (gs->itres - 1);
imi = (int)floor(rmi); /* Interp. entry coordinate */
if (imi >= (gs->itres-1)) /* Keep cube base one row back from far edge */
imi = gs->itres-2;
rsi = rmi - (double)imi; /* offset into entry cube */
if (ts->sort) {
iwe = (int)((rsi * (1 << gs->prec)) + 0.5); /* Weighting scale */
vo = idinc[e] * ts->vo_om; /* Vertex offset */
} else {
isi = (int)((rsi * gs->stres) + 0.5);
if (isi == gs->stres) { /* Keep simplex index within table */
isi = 0;
imi++; /* Move to next interp. lattice */
}
isi *= sdinc[e]; /* Convert the raw indexes into offset in this dim */
}
imi *= idinc[e]; /* Convert the raw indexes into offset in this dim */
#ifdef ASSERTS
/* ~~~ needs fixing for sort ~~~~ */
if ((imi & (LSHIFT(1,ts->it_ab)-1)) != imi)
error("imdi_tab assert: (imi & ((1 << ts->it_ab)-1)) != imi, imi = 0x%x, it_ab = 0x%x\n",imi,ts->it_ab);
if (imi >= idinc[it->id])
error("imdi_tab assert: imi >= idinc[it->id]\n");
if ((isi & (LSHIFT(1,ts->sx_ab)-1)) != isi)
error("imdi_tab assert: (isi & ((1 << ts->sx_ab)-1)) != isi, isi = 0x%x, sx_ab = 0x%x\n",isi,ts->sx_ab);
if (!ts->sort && isi >= sdinc[it->id])
error("imdi_tab assert: isi >= sdinc[it->id]\n");
#endif
/* Now stuff them into the table entry */
if (ts->sort) {
if (ts->it_xs) { /* Separate interp index and weight/offset*/
if (ts->wo_xs) { /* All 3 are separate */
write_entry[ts->ix_es](p + ts->ix_eo, imi);
write_entry[ts->we_es](p + ts->we_eo, iwe);
write_entry[ts->vo_es](p + ts->vo_eo, vo);
} else {
bvt iwo;
iwo = ((bvt)iwe << ts->vo_ab) | vo; /* Combined weight+vertex offset */
write_entry[ts->ix_es](p + ts->ix_eo, imi);
write_entry[ts->wo_es](p + ts->wo_eo, iwo);
}
} else { /* All 3 are combined */
bvt iit;
iit = ((((bvt)imi << ts->we_ab) | (bvt)iwe) << ts->vo_ab) | vo;
write_entry[ts->it_ts](p, iit);
}
} else {
if (ts->it_xs) { /* Separate interp index and weight/offset*/
write_entry[ts->ix_es](p + ts->ix_eo, imi);
write_entry[ts->sx_es](p + ts->sx_eo, isi);
} else {
bvt iit;
iit = ((bvt)imi << ts->sx_ab) | isi; /* Combine interp and simplex indexes */
write_entry[ts->it_ts](p, iit);
}
}
}
/* Put table into place */
it->in_tables[e] = (void *)t;
}
it->nintabs = e;
/* Setup the interpolation table */
{
byte *t, *p; /* Pointer to interp table, pointer to total entry */
PHILBERT(phc) /* Pseudo Hilbert counter */
double vscale; /* Value scale for fixed point */
int vsize; /* Fixed point storage size */
if (ts->im_cd)
vsize = (gs->prec * 2)/8; /* Fixed point entry & computation size */
else
vsize = gs->prec/8; /* Fixed point entry size */
vscale = (1 << gs->prec) -0.50000001;
/* Value scale for fixed point padding */
/* -0.5 is to prevent carry/rollover after accumulation */
/* Could get better accuracy with saturation arithmatic */
/* Allocate the table */
if ((t = (byte *)malloc(ibdinc[it->id])) == NULL) {
#ifdef VERBOSE
printf("malloc imdi interpolation table size %d failed\n",ibdinc[it->id]);
#endif
return NULL; /* Should we signal error ? How ? */
}
it->size += ibdinc[it->id];
#ifdef VERBOSE
printf("Allocated grid table = %u bytes, composed of %d dim of res %d entry %d\n",ibdinc[it->id], it->id, gs->itres, ts->im_ts);
#endif /* VERBOSE */
/* Get ready to access all the entries in the table */
p = t;
PH_INIT(phc, it->id, gs->itres)
/* Create all the interpolation table entry values */
do {
int ee, ff;
double riv[IXDI]; /* Real input values */
double rev[IXDO]; /* Real entry values */
unsigned long iev;
byte *pp; /* Pointer to sub-entry */
for (e = 0, p = t; e < it->id; e++) {
riv[e] = ((double)phc[e]) / (gs->itres - 1.0);
p += phc[e] * ibdinc[e]; /* Compute pointer to entry value */
}
/* Lookup this vertices value */
{
double mriv[IXDI]; /* Channel mapped real input values */
double mrev[IXDO]; /* Channel mapped real entry values */
for (e = 0; e < it->id; e++)
mriv[it->it_map[e]] = riv[e];
md_table(cntx, mrev, mriv);
for (e = 0; e < it->od; e++)
rev[e] = mrev[it->im_map[e]];
}
/* Create all the output values */
/* I'm trying to avoid having to declare the actual entry sized */
/* variables, since it is difficult dynamically. */
/* For all the full entries */
ff = 0;
pp = p;
for (e = 0; e < ts->im_fn; e++, pp += ts->im_fs) {
/* For all channels within full entry */
for (ee = 0; ee < ts->im_fv; ee++, ff++) {
double revf = rev[ff];
if (revf < 0.0) /* Guard against sillies */
revf = 0.0;
else if (revf > 1.0)
revf = 1.0;
iev = (unsigned long)(revf * vscale + 0.5);
if (bigend) {
write_entry[vsize](pp + (ts->im_fs - (ee+1) * vsize), iev);
} else {
write_entry[vsize](pp + ee * vsize, iev);
}
}
}
/* For all the 0 or 1 partial entry */
for (e = 0; e < ts->im_pn; e++) {
/* For all channels within partial entry */
for (ee = 0; ee < ts->im_pv; ee++, ff++) {
double revf = rev[ff];
if (revf < 0.0) /* Guard against sillies */
revf = 0.0;
else if (revf > 1.0)
revf = 1.0;
iev = (unsigned long)(revf * vscale + 0.5);
if (bigend) {
write_entry[vsize](pp + (ts->im_ps - (ee+1) * vsize), iev);
} else {
write_entry[vsize](pp + ee * vsize, iev);
}
}
}
#ifdef ASSERTS
if (f != it->od)
fprintf(stderr,"imdi_tab assert: f == it->od\n");
#endif
PH_INC(phc)
} while (!PH_LOOPED(phc));
/* Put table into place */
it->im_table = (void *)t;
}
/* Setup the simplex table */
if (ts->sort) {
it->sw_table = (void *)NULL;
} else {
byte *t, *p; /* Pointer to input table, pointer to total entry */
int nsplx; /* Total number of simplexes */
XCOMBO(vcmb, it->id+1, 1 << it->id);/* Simplex dimension id out of cube dimention id */
int comb[24][IXDI]; /* Parameter[id]->Absolute[id] coordinate index */
int ps[IXDI+1]; /* Base simplex parameter space counter */
int pse; /* Base simplex parameter space counter index */
int idioff; /* Interpolation table diagonal offset value */
if (it->id > 4) {
fprintf(stderr,"imdi_tabl: internal failure - trying to create simplex table with di > 4!\n");
exit(-1);
}
/* Allocate the table */
if ((t = (byte *)malloc(sbdinc[it->id])) == NULL) {
#ifdef VERBOSE
printf("malloc imdi simplex table size %d failed\n",sbdinc[it->id]);
#endif
return NULL; /* Should we signal error ? How ? */
}
it->size += sbdinc[it->id];
#ifdef VERBOSE
printf("Allocated simplex table = %u bytes, composed of %d dim of res %d entry %d\n",sbdinc[it->id], it->id, gs->stres, ts->sm_ts);
#endif /* VERBOSE */
/* Compute the interp table offset to the diagonal vertex */
for (idioff = 0, e = 0; e < it->id; e++)
idioff += idinc[e]; /* Sum one offset in each dimension */
/* Figure out how many simplexes fit into this dimension cube, */
/* and how to map from the base simplex to each actual simplex. */
XCB_INIT(vcmb);
for (nsplx = 0; ;) {
int i;
/* XCOMB generates vertices in order from max to min offest */
/* Compute Absolute -> Parameter mapping */
for (e = 0; e < it->id; e++) { /* For each absolute axis */
for (i = 0; i < it->id; i++) { /* For each verticy, order large to small */
if ((vcmb[i] & (1<<e)) != 0 &&
(vcmb[i+1] & (1<<e)) == 0) {/* Transition from offset 1 to 0 */
comb[nsplx][i] = e;
break;
}
}
}
//printf("~~Vertices = ");
//for (i = 0; i <= it->id; i++)
// printf("%d ",vcmb[i]);
//printf("\n");
//printf("~~Parm -> Abs = ");
//for (e = 0; e < it->id; e++)
// printf("%d ",comb[nsplx][e]);
//printf("\n");
/* Increment the counter value */
XCB_INC(vcmb);
nsplx++;
if (XCB_DONE(vcmb))
break;
}
/* Now generate the contents of the base simplex, */
/* and map it to all the symetrical simplexes */
/* Init parameter space counter. */
/* Note that ps[id-1] >= ps[id-2] >= ... >= ps[1] >= ps[0] */
for (pse = 0; pse < it->id; pse++)
ps[pse] = 0;
ps[pse] = gs->stres-1;
/* Itterate through the simplex parameter space */
for (pse = 0; pse < it->id;) {
int qps[IXDI]; /* Quantized parameter values */
int we[IXDI+1]; /* Baricentric coords/vertex weighting */
double wvscale = (1 << gs->prec); /* Weighting value scale */
int sx; /* Simplex */
//printf("Param coord =");
//for (e = it->id-1; e >= 0; e--) {
// printf(" %d",ps[e]);
//}
//printf("\n");
for (e = 0; e < it->id; e++) {
/* (Should try wvscale + 0.49999999, or something ?) */
double tt = (wvscale * (double)ps[e])/((double)gs->stres);
qps[e] = (int)(tt + 0.5);
}
/* Convert quantized parameter values into weighting values */
we[it->id] = (1 << gs->prec) - qps[it->id-1];
for (e = it->id-1; e > 0; e--)
we[e] = qps[e] - qps[e-1];
we[0] = qps[0];
#ifdef ASSERTS
{
int sow = 0;
for (e = it->id; e >= 0; e--)
sow += we[e];
if (sow != (1 << gs->prec))
fprintf(stderr,"imdi_tab assert: sum weights == (1 << gs->prec)\n");
}
#endif
//printf("Baricentric coord =");
//for (e = it->id; e >= 0; e--) {
// printf(" %d",we[e]);
//}
//printf("\n");
/* For each simplex, compute the interp. and */
/* and entry offsets, and write the entry. */
for (sx = 0; sx < nsplx; sx++ ) {
int v; /* Vertex index */
byte *pp; /* Pointer to sub-entry */
unsigned long vofb = 0; /* Vertex offset, base */
unsigned long vwe; /* Vertex weight */
for (e = 0, p = t; e < it->id; e++) {
int ee = comb[sx][e]; /* Absolute coord index */
p += ps[e] * sbdinc[ee]; /* Pointer to entry */
}
/* For each vertex entry */
for (v = 0, pp = p; v <= it->id; v++) {
unsigned long vof;
if (v == 0) {
vofb = idioff; /* Start at diagonal offset */
} else {
vofb -= idinc[comb[sx][v-1]];/* Move to next vertex */
}
vwe = we[v]; /* Weight for this vertex */
if (vwe == 0)
vof = 0; /* Use zero offset if weight is zero */
else
vof = vofb * ts->vo_om; /* Strength reduce kernel scaling */
/* Write vwe and vof to entry */
if (ts->wo_xs) { /* Separate entries */
write_entry[ts->we_es](pp + ts->we_eo, vwe);
write_entry[ts->vo_es](pp + ts->vo_eo, vof);
pp += ts->wo_es;
} else { /* Combined entries */
bvt iwo;
iwo = ((bvt)vwe << ts->vo_ab) | vof; /* Combined weight+vertex offset */
write_entry[ts->wo_es](pp + ts->wo_eo, iwo);
pp += ts->wo_es;
}
}
/* Assert vofb == 0 */
#ifdef ASSERTS
if (vofb != 0)
fprintf(stderr,"imdi_tab assert: vofb == 0\n");
#endif
} /* Next simplex */
/* Increment the parameter coords */
for (pse = 0; pse < it->id; pse++) {
ps[pse]++;
if (ps[pse] <= ps[pse+1])
break; /* No carry */
ps[pse] = 0;
}
}
/* Put table into place */
it->sw_table = (void *)t;
}
/* Last, setup the output tables */
for (e = 0; e < it->od; e++) {
byte *t, *p; /* Pointer to output table, entry pointer */
int ne; /* Number of entries */
int iiv; /* Integer input value */
double ivr = (double)((1 << gs->prec)-1); /* Input value range */
double ovr = (double)((1 << ts->ot_bits[e])-1); /* Output value range */
int osb = (1 << (ts->ot_bits[e]-1)); /* Output offset to signed displacement */
int ooff = ts->ot_off[e]; /* Output value bit offset */
ne = (1 << gs->prec); /* Output of clut is prec bits */
/* Allocate the table */
if ((t = (byte *)malloc(ts->ot_ts * ne)) == NULL) {
#ifdef VERBOSE
printf("malloc imdi output table size %d failed\n",ts->ot_ts * ne);
#endif
return NULL; /* Should we signal error ? How ? */
}
it->size += ts->ot_ts * ne;
#ifdef VERBOSE
printf("Allocated output table %d size %u = %u * %u\n",e, ts->ot_ts * ne,ts->ot_ts,ne);
#endif /* VERBOSE */
/* For each possible output value, compute the entry value */
for (iiv = 0, p = t; iiv < ne; iiv++, p += ts->ot_ts) {
double riv; /* Real input value, 0.0 - 1.0 */
double rtv; /* Real transformed value, 0.0 - 1.0 */
unsigned long iov; /* Integer output value */
riv = (double) iiv / ivr; /* Compute floating point */
{
double civ[IXDO], cov[IXDO];
for (f = 0; f < it->od; f++)
civ[f] = riv;
output_curves(cntx, cov, civ); /* Lookup the input table transform */
rtv = cov[it->im_map[e]];
}
if (rtv < 0.0) /* Guard against sillies */
rtv = 0.0;
else if (rtv > 1.0)
rtv = 1.0;
iov = (unsigned long)(rtv * ovr + 0.5); /* output value */
if (gs->out_signed & (1 << e)) /* Treat output as signed */
iov = (iov & osb) ? iov - osb : iov + osb; /* Convert to signed from offset */
iov <<= ooff; /* Aligned for output */
write_entry[ts->ot_ts](p, iov); /* Write entry */
}
/* Put table into place */
it->out_tables[e] = (void *)t;
}
it->nouttabs = e;
/* Adjust the check values for output value shift */
for (e = 0; e < it->od; e++) {
int ooff = ts->ot_off[e]; /* Output value bit offset */
it->checkv[e] <<= ooff; /* Aligned for output */
}
/* Setup the appropriate skip flags, indexed by Output channel */
it->skipf = 0;
if ((oopt & OOPTS_SKIP) != 0) {
int i;
for (i = 0; i < it->od; i++) {
if (oopt & OOPT(oopts_skip,it->im_map[i])) { /* Skip flag for this output chan */
it->skipf |= (1 << i);
}
}
}
/* Fill in some report information */
it->gres = gs->itres;
if (!ts->sort) {
it->sres = gs->stres;
} else {
it->sres = 0;
}
#ifdef VERBOSE
printf("imdi_tabl returning OK\n");
#endif
return it;
}
/* Free up the data allocated */
void
imdi_tab_free(
imdi_imp *it
) {
int e;
for (e = 0; e < it->nintabs; e++)
free(it->in_tables[e]);
if (it->sw_table != NULL)
free(it->sw_table);
if (it->im_table != NULL)
free(it->im_table);
for (e = 0; e < it->nouttabs; e++)
free(it->out_tables[e]);
free(it);
}

View File

@@ -0,0 +1,170 @@
#ifndef IMDI_TAB_H
#define IMDI_TAB_H
/* Integer Multi-Dimensional Interpolation */
/*
* Copyright 2000 - 2007 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
/*
* Implementation details needed for table initialisation for a particular
* kernel. This is private implementation for imdi.[ch]
*
* The tabspec structure holds detailed information on the algorithms used
* by the runtime code, and (implicit in this) the layout of the runtime
* tables needed to match the algorithm. There are also implicit dependencies on
* the genspec structure, since this determines the overall features
* supported by a particular pixel kernel module.
*
* This is effectively the product of the genspec, the architechure,
* and the coding choices made by the code generator
* (ie. gen_c_kernel() in cgen.c)
*
*/
/* entries marked with '#' are not currently used by imdi_tab() */
/* NOTE :- if you change this, you need to change the code in cgen.c */
/* labeled !genspec and tabspec delta code! */
struct _tabspec {
int sort; /* NZ for explicit sort rather than simplex table lookup */
int it_xs; /* NZ if separate interp index and simplex index/Weighting+Offset values */
int wo_xs; /* NZ if separate weighting and vertex offset entries are to be used */
int it_ix; /* Non-zero if input value extraction should be done in input table */
int it_ab; /* Input table entry size in bits */
int it_ts; /* Input table :- total input table entry size in bytes */
/* Bit packing order is (ms to ls) :
sort: ix, we, vo
sort: ix, wo
!sort: ix, sx
*/
/* Interpolation index is always in the input table */
int ix_ab; /* # Interpolation index entry size in bits */
int ix_es; /* Interpolation index entry size in bytes */
int ix_eo; /* Interpolation index entry offset in bytes */
/* Simplex Index is always in the input table */
int sx_ab; /* Simplex Index entry size in bits */
int sx_es; /* Simplex Index entry size in bytes */
int sx_eo; /* Simplex Index entry offset in bytes */
int sm_ts; /* Simplex table entry total size in bytes */
/* Bit packing order is (ms to ls) : we, vo */
/* Combined Weighting + Offset may be in input table or Simplex entry */
int wo_ab; /* Combined Weighting + Offset entry size in bits */
int wo_es; /* Combined Weighting + Offset entry size in bytes */
int wo_eo; /* Combined Weighting + Offset entry offset in bytes */
/* Weighting may be in input table or Simplex entry */
int we_ab; /* # Weighting entry size in bits */
int we_es; /* Weighting entry size in bytes */
int we_eo; /* Weighting entry offset in bytes */
/* Vertex offset may be in input table or Simplex entry */
int vo_ab; /* Vertex Offset entry size in bits */
int vo_es; /* Vertex Offset entry size in bytes */
int vo_eo; /* Vertex Offset entry offset in bytes */
int vo_om; /* Vertex Offset scaling multiplier */
int im_cd; /* Non-zero if interpolation table entries are padded with fraction */
int im_ts; /* Interp. multidim :- total interp table entry size in bytes */
int im_oc; /* # Interp. multidim :- offset scale to apply to index into interp entry */
int im_fs; /* Interp. multidim :- full table entry size in bytes */
int im_fn; /* Interp. multidim :- number of full entries */
int im_fv; /* Interp. multidim :- output values per full entry . */
int im_ps; /* Interp. multidim :- partial table entry size in bytes, used & unsused */
int im_pn; /* Interp. multidim :- number of partial entries - must be 0 or 1 */
int im_pv; /* Interp. multidim :- used output values per partial entry . */
int ot_ts; /* Output table :- total entry size in bytes of every table */
int ot_off[IXDO]; /* Offset for each output value within the output word needed */
int ot_bits[IXDO]; /* Number of bits for value within the output word needed */
/* Associated interpolation function */
void (*interp)(struct _imdi *s, void **inp, void **outp, unsigned int npix); /* At run time */
}; typedef struct _tabspec tabspec;
/* Runtime conversion needed */
typedef enum {
conv_none = 0x00, /* No conversion needed */
conv_istr = 0x01, /* Input stride conversion */
conv_ostr = 0x02, /* Output stride conversion */
conv_irep = 0x04, /* Input representation conversion */
conv_orep = 0x08, /* Output representation conversion */
conv_rev = 0x10, /* Reverse direction conversion */
conv_skip = 0x20 /* Skip output channel write conversion */
} imdi_conv;
/* The actual run time table that tabspec describes */
typedef struct {
/* Runtime setup */
int id; /* Number of input dimensions */
int od; /* Number of output dimensions (including skip channels) */
int wod; /* Number of written output dimensions ( < od if skipf != 0) */
int it_map[IXDI]; /* Mapping from input raster channels to callback channels. */
int im_map[IXDO]; /* Mapping from output raster channels to callback channels. */
imdi_pixrep cirep; /* High level input pixel representation called with */
imdi_pixrep corep; /* High level output pixel representation called with */
imdi_pixrep firep; /* High level input pixel representation of interp func. */
imdi_pixrep forep; /* High level output pixel representation of interp func. */
imdi_conv cnv; /* Runtime argument conversion needed */
void (*interp)(struct _imdi *s, void **outp, int outst, /* Underlying conversion function */
void **inp, int inst,
unsigned int npixels);
/* Output channel check data */
unsigned long checkv[IXDO]; /* Output per channel check values. Set flag if != checkv */
unsigned int checkf; /* Output per channel check flags (one per bit) */
unsigned int skipf; /* Output per channel skip flags (one per bit) */
/* Table data */
void *in_tables[IXDI]; /* Input dimension input lookup tables */
void *sw_table; /* Simplex weighting lookup table */
void *im_table; /* Interpolation Multi-dimensional lookup table */
void *out_tables[IXDO]; /* Output dimension output lookup tables */
int nintabs; /* Number of input tables */
int nouttabs; /* Number of output tables */
/* Extra reporting data */
unsigned long size; /* Number of bytes allocated to imdi_imp */
unsigned int gres, sres; /* Grid and simplex table resolutions. sres = 0 = sort */
} imdi_imp;
/*
* The runtime function that knows how to setup an imdi_imp
* table for for our chosen kernel and the color mapping we
* want to perform.
*/
imdi_imp *
imdi_tab(
genspec *gs, /* Pointer to gen spec */
tabspec *ts, /* Pointer to table spec */
imdi_conv cnv, /* Runtime argument conversion needed */
imdi_pixrep irep, /* High level input pixel representation to match */
imdi_pixrep orep, /* High level output pixel representation to match */
void (*interp)(struct _imdi *s, void **outp, int outst, /* Underlying conversion function */
void **inp, int inst,
unsigned int npixels),
int *inm, /* Input raster channel to callback channel mapping, NULL for none. */
int *outm, /* Output raster channel to callback channel mapping, NULL for none. */
imdi_ooptions oopt, /* Output per channel options (Callback channel, NOT written channel) */
unsigned int *checkv, /* Output channel check values (Callback channel, NULL for none == 0. */
/* Callbacks to initialse the imdi table values */
void (*input_curves) (void *cntx, double *out_vals, double *in_vals),
void (*md_table) (void *cntx, double *out_vals, double *in_vals),
void (*output_curves)(void *cntx, double *out_vals, double *in_vals),
void *cntx /* Context of callbacks */
);
void imdi_tab_free(imdi_imp *it);
#endif /* IMDI_TAB_H */

View File

@@ -0,0 +1,262 @@
#ifndef IMDI_UTL_H
#define IMDI_UTL_H
/* Integer Multi-Dimensional Interpolation */
/*
* Copyright 2000 - 2007 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
#include <limits.h>
/* Common utility definitions used at both generation and runtime. */
#define IXDI 10 /* maximum input channels/dimensions allowed */
#define IXDO 10 /* maximum output channels/dimensions allowed */
#if IXDI > IXDO /* Maximum of either DI or DO */
# define IXDIDO IXDI
#else
# define IXDIDO IXDO
#endif
#define ALLOW64 /* Allow declarations but not use of 64 bit types */
#ifndef FORCE64
# undef FORCE64 /* Use 64 bit, even on architectures where it's */
/* not a native size. ALLOW64 must be defined */
#endif
/* ------------------------------------------------------ */
#if defined(ALLOW64) && (ULONG_MAX == 0xffffffffffffffffUL || defined(FORCE64))
#ifndef USE64
#pragma message("Using 64 bit integer color kernel")
#endif /* USE64 */
#define USE64 /* Use 64 bits if it's natural or forced */
#endif
/* ------------------------------------------------------- */
/* Macros combination counter */
/* Declare the counter name nn, combinations out of total */
/* Maximum combinations is DI+2 */
#define COMBO(nn, comb, total) \
int nn[IXDI+2]; /* counter value */ \
int nn##_cmb = (comb); /* number of combinations*/ \
int nn##_tot = (total); /* out of total possible */ \
int nn##_e /* dimension index */
/* Set total to new setting */
#define CB_SETT(nn, total) \
nn##_tot = (total) /* total possible */
/* Set combinations to new setting */
#define CB_SETC(nn, comb) \
nn##_cmb = (comb) /* number of combinations*/
/* Set the counter to its initial value */
#define CB_INIT(nn) \
{ \
for (nn##_e = 0; nn##_e < nn##_cmb; nn##_e++) \
nn[nn##_e] = nn##_cmb-nn##_e-1; \
nn##_e = 0; \
}
/* Increment the counter value */
#define CB_INC(nn) \
{ \
for (nn##_e = 0; nn##_e < nn##_cmb; nn##_e++) { \
nn[nn##_e]++; \
if (nn[nn##_e] < (nn##_tot-nn##_e)) { \
int nn##_ee; /* No carry */ \
for (nn##_ee = nn##_e-1; nn##_ee >= 0; nn##_ee--) \
nn[nn##_ee] = nn[nn##_ee+1] + 1; \
break; \
} \
} \
}
/* After increment, expression is TRUE if counter is done */
#define CB_DONE(nn) \
(nn##_e >= nn##_cmb)
/* ------------------------------------------------------- */
/* Macros simplex combination counter. */
/* Based on COMBO, but skips invalid simplex combinations */
#define XCOMBO(nn, comb, total) \
COMBO(nn, comb, total)
/* Set total to new setting */
#define XCB_SETT(nn, total) \
CB_SETT(nn, total)
/* Set combinations to new setting */
#define XCB_SETC(nn, comb) \
CB_SETC(nn, comb)
/* Set the counter to its initial value */
#define XCB_INIT(nn) \
{ \
int nn##_ii; \
\
for (nn##_e = 0; nn##_e < nn##_cmb; nn##_e++) \
nn[nn##_e] = nn##_cmb-nn##_e-1; \
for (nn##_ii = 1; nn##_ii < nn##_cmb; nn##_ii++) { \
if ((nn[nn##_ii-1] ^ nn[nn##_ii]) & nn[nn##_ii])\
break; /* Went from 0 to 1 */ \
} \
if (nn##_ii < nn##_cmb) { /* Fix invalid combination */ \
XCB_INC(nn); \
} \
nn##_e = 0; \
}
/* Increment the counter value */
#define XCB_INC(nn) \
{ \
int nn##_ii = 0; \
\
while (nn##_ii < nn##_cmb) { \
for (nn##_e = 0; nn##_e < nn##_cmb; nn##_e++) { \
nn[nn##_e]++; \
if (nn[nn##_e] < (nn##_tot-nn##_e)) { \
int nn##_ee; /* No carry */ \
for (nn##_ee = nn##_e-1; nn##_ee >= 0; nn##_ee--) \
nn[nn##_ee] = nn[nn##_ee+1] + 1; \
break; \
} \
} \
if (nn##_e >= nn##_cmb) \
break; /* Done */ \
\
/* Reject invalid combinations */ \
for (nn##_ii = 1; nn##_ii < nn##_cmb; nn##_ii++) { \
if ((nn[nn##_ii-1] ^ nn[nn##_ii]) & nn[nn##_ii]) \
break; /* Went from 0 to 1 */ \
} \
} \
}
/* After increment, expression is TRUE if counter is done */
#define XCB_DONE(nn) \
CB_DONE(nn)
/* ------------------------------------------------------- */
/* Macro pseudo-hilbert counter */
/* This multi-dimensional count sequence is a distributed */
/* Gray code sequence, with direction reversal on every */
/* alternate power of 2 scale. */
/* It is intended to aid cache coherence in multi-dimensional */
/* regular sampling. It approximates the Hilbert curve sequence. */
#define PHILBERT(nn) \
int nn[IXDIDO];/* counter value */ \
int nn##di; /* Dimensionality */ \
unsigned nn##res; /* Resolution per coordinate */ \
unsigned nn##bits; /* Bits per coordinate */ \
unsigned nn##ix; /* Current binary index */ \
unsigned nn##tmask; /* Total 2^n count mask */ \
unsigned nn##count; /* Usable count */
/* Init counter for dimenion di, resolution res */
#define PH_INIT(nn, pdi, pres) \
{ \
int nn##e; \
\
nn##di = pdi; \
nn##res = (unsigned)pres; \
\
/* Compute bits */ \
for (nn##bits = 0; (1u << nn##bits) < nn##res; nn##bits++) \
; \
\
/* Compute the total count mask */ \
nn##tmask = ((1u << (nn##bits * nn##di))-1); \
\
/* Compute usable count */ \
nn##count = 1; \
for (nn##e = 0; nn##e < nn##di; nn##e++) \
nn##count *= nn##res; \
\
nn##ix = 0; \
for (nn##e = 0; nn##e < nn##di; nn##e++) \
nn[nn##e] = 0; \
}
/* Increment the counter value */
#define PH_INC(nn) \
{ \
int nn##e; \
do { \
unsigned int nn##b; \
int nn##gix; /* Gray code index */ \
\
nn##ix = (nn##ix + 1) & nn##tmask; \
\
/* Convert to gray code index */ \
nn##gix = nn##ix ^ (nn##ix >> 1); \
\
for (nn##e = 0; nn##e < nn##di; nn##e++) \
nn[nn##e] = 0; \
\
/* Distribute bits */ \
for (nn##b = 0; nn##b < nn##bits; nn##b++) { \
if (nn##b & 1) { /* In reverse order */ \
for (nn##e = nn##di-1; nn##e >= 0; nn##e--) { \
nn[nn##e] |= (nn##gix & 1) << nn##b; \
nn##gix >>= 1; \
} \
} else { /* In normal order */ \
for (nn##e = 0; nn##e < nn##di; nn##e++) { \
nn[nn##e] |= (nn##gix & 1) << nn##b; \
nn##gix >>= 1; \
} \
} \
} \
\
/* Convert from Gray to binary coordinates */ \
for (nn##e = 0; nn##e < nn##di; nn##e++) { \
unsigned nn##sh, nn##tv; \
\
for(nn##sh = 1, nn##tv = nn[nn##e];; nn##sh <<= 1) { \
unsigned nn##ptv = nn##tv; \
nn##tv ^= (nn##tv >> nn##sh); \
if (nn##ptv <= 1 || nn##sh == 16) \
break; \
} \
/* Filter - increment again if outside cube range */ \
if (nn##tv >= nn##res) \
break; \
nn[nn##e] = nn##tv; \
} \
\
} while (nn##e < nn##di); \
\
}
/* After increment, expression is TRUE if counter has looped back to start. */
#define PH_LOOPED(nn) \
(nn##ix == 0) \
/* ------------------------------------------------------- */
#endif /* IMDI_UTL_H */

652
Argyll_V3.5.0/imdi/itest.c Normal file
View File

@@ -0,0 +1,652 @@
/* Verify and benchmark the imdi code */
/*
* Copyright 2000 - 2006 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "copyright.h"
#include "aconfig.h"
#include "numlib.h"
#include "imdi.h"
#include "refi.h"
/* Test parameters */
#undef TEST1 /* Test just one combination */
#define FULL /* Test full range */
#undef VERBOSE /* Report every conversion */
#undef REPORT_ERRORS /* Report conversion with large errors */
#define TRAND /* Test random in/out table contents */
#define TCRAND /* Test random clut table contents */
#undef QUANTIZE /* Quantize the target table values */
#define TBUFSIZE (2 * 1024 * 1024) /* Default number of input bytes to test */
#define ITERS 10 /* Itterations */
double trans1(double in, double t);
double trans2(double in, double t);
/* Context for refi setup callbacks */
typedef struct {
int id;
int od;
double icurve[MXDI]; /* Input curve factors */
double clut[MXDO][MXDI]; /* clut matrix factors */
double ocurve[MXDO]; /* Output curve factors */
} rcntx;
/* Input curve function */
static void input_curves(
void *cntx,
double *out_vals,
double *in_vals
) {
int i;
rcntx *rx = (rcntx *)cntx;
for (i = 0; i < rx->id; i++) {
double val = in_vals[i];
#ifdef TRAND
val = trans1(val, rx->icurve[i]);
#ifdef QUANTIZE
val = ((int)(val * 255.0 + 0.5))/255.0; /* Quantize to 8 bits */
#endif
#endif
out_vals[i] = val;
}
}
/* Multi-dim table function */
static void md_table(
void *cntx,
double *out_vals,
double *in_vals
) {
rcntx *rx = (rcntx *)cntx;
int i, j;
#ifdef TCRAND
for (j = 0; j < rx->od; j++) {
double val = 0.0;
for (i = 0; i < rx->id; i++) {
val += rx->clut[j][i] * in_vals[i];
}
#ifdef QUANTIZE
val = ((int)(val * 255.0 + 0.5))/255.0; /* Quantize to 8 bits */
#endif
out_vals[j] = val;
}
#else
for (j = 0; j < rx->od; j++)
out_vals[j] = in_vals[j % rx->id];
#endif
//printf("~1 out %f %f %f %f from %f\n", out_vals[0], out_vals[1], out_vals[2], out_vals[3], in_vals[0]);
}
/* Output curve function */
static void output_curves(
void *cntx,
double *out_vals,
double *in_vals
) {
int i;
rcntx *rx = (rcntx *)cntx;
for (i = 0; i < rx->od; i++) {
double val = in_vals[i];
#ifdef TRAND
val = trans1(val, rx->ocurve[i]);
#ifdef QUANTIZE
val = ((int)(val * 255.0 + 0.5))/255.0; /* Quantize to 8 bits */
#endif
#endif
out_vals[i] = val;
}
}
/* Complete reference interpolation */
void refi_interp(refi *r, double *out_vals, double *in_vals);
void usage(void) {
fprintf(stderr,"Regression test imdi code Version %s\n",ARGYLL_VERSION_STR);
fprintf(stderr,"usage: itest [-q] [-s]\n");
fprintf(stderr," -q Quick test\n");
fprintf(stderr," -s Stop on error\n");
fprintf(stderr," -r bits Specify bits of randomness in input data\n");
exit(1);
}
int
main(int argc, char *argv[]) {
int fa,nfa; /* argument we're looking at */
int quick = 0;
int stop = 0;
int rbits = 16;
int n, i, j, e;
int pix, iix, oix;
int ip, op, id, od;
int ires, cres, ores;
clock_t stime, ttime; /* Start and total times */
double xtime; /* Total execution time in seconds */
double npixels; /* Number of pixels processed */
rcntx rx;
refi *r;
double ribuf[MXDI];
double robuf[MXDO];
imdi *s;
int iters;
unsigned long tbufsize;
unsigned char *ibuf;
unsigned char *obuf;
unsigned char *inp[MXDI];
unsigned char *outp[MXDO];
unsigned short *ibuf2; /* 16 bit references */
unsigned short *obuf2;
double omxerr = 0; /* Overall max error /1.0 */
/* Define combinations to test */
#ifdef TEST1
#pragma message("!!!!!!!!!!!!!!!!! TEST1 is defined !!!!!!!!!!!!!!!1")
int ids[] = { 3, 0 }; /* Input dimensions */
int ods[] = { 3, 0 }; /* Output dimensions */
int iprs[] = { 16, 0 };
int oprs[] = { 16, 0 };
#else
#ifndef FULL
int ids[] = { 1, 3, 4, 8, 0 };
int ods[] = { 1, 3, 4, 8, 0 };
int iprs[] = { 8, 8, 16, 0};
int oprs[] = { 8, 16, 16, 0};
#else
int ids[] = { 1, 3, 4, 5, 6, 7, /* 8, */ 0 };
int ods[] = { 1, 3, 4, 5, 6, 7, /* 8, */ 0 };
int iprs[] = { 8, 8, 16, 0};
int oprs[] = { 8, 16, 16, 0};
#endif
#endif
/* Process the arguments */
for(fa = 1;fa < argc;fa++) {
nfa = fa; /* skip to nfa if next argument is used */
if (argv[fa][0] == '-') { /* Look for any flags */
char *na = NULL; /* next argument after flag, null if none */
if (argv[fa][2] != '\000')
na = &argv[fa][2]; /* next is directly after flag */
else {
if ((fa+1) < argc) {
if (argv[fa+1][0] != '-') {
nfa = fa + 1;
na = argv[nfa]; /* next is seperate non-flag argument */
}
}
}
if (argv[fa][1] == '?')
usage();
/* Quick test */
else if (argv[fa][1] == 'q' || argv[fa][1] == 'Q') {
quick = 1;
}
/* Stop on error */
else if (argv[fa][1] == 's' || argv[fa][1] == 'S') {
stop = 1;
}
/* Degree of data randomness */
else if (argv[fa][1] == 'r' || argv[fa][1] == 'R') {
fa = nfa;
if (na == NULL) usage();
rbits = atoi(na);
if (rbits < 0)
rbits = 1;
else if (rbits > 16)
rbits = 16;
}
else
usage();
} else
break;
}
for (iix = 0; ids[iix] > 0; iix++) { /* All input dimensions */
for (oix = 0; ods[oix] > 0; oix++) { /* All output dimensions */
for (pix = 0; iprs[pix] > 0; pix++) { /* All precisions */
int rmask = 0;
ip = iprs[pix]; /* Input precision */
op = oprs[pix]; /* Output precision */
id = ids[iix]; /* Input dimensions */
od = ods[oix]; /* Outpu dtimensions */
if (ip != 8 && ip != 16)
error("Can't handle input precision of %d in testing\n",ip);
if (op != 8 && op != 16)
error("Can't handle output precision of %d in testing\n",op);
if (id > MXDI)
error("Can't handle id greater than %d in testing\n",MXDI);
if (od > MXDO)
error("Can't handle od greater than %d in testing\n",MXDO);
printf("Testing id = %d, od = %d, ip = %d, op = %d\n",id,od,ip,op);
ires = 256;
switch (id) {
case 1:
cres = 257;
break;
case 2:
case 3:
cres = 33;
break;
case 4:
cres = 17;
break;
case 5:
cres = 7;
break;
case 6:
cres = 7;
break;
case 7:
cres = 5;
break;
case 8:
cres = 5;
break;
default:
cres = 3;
}
ores = 256;
/* Setup error messages */
error_program = "itest";
/* Create the reference first */
printf("About to create refi\n");
/* Create test curves */
rx.id = id;
rx.od = od;
rand32(0x1234);
for (i = 0; i < id; i++) {
rx.icurve[i] = d_rand(-1.0, 1.0);
}
//printf("Matrix params =\n");
rand32(0x2345);
for (j = 0; j < od; j++) {
double s = 0.0;
for (i = 0; i < id; i++) {
double v = d_rand(1.0, 0.0);
rx.clut[j][i] = v; /* Make them sum to 1.0 */
s += v;
}
for (i = 0; i < id; i++) {
rx.clut[j][i] /= s;
//printf(" %f",rx.clut[j][i]);
}
//printf("\n");
}
rand32(0x3456);
for (j = 0; j < od; j++) {
rx.ocurve[j] = d_rand(-1.0, 1.0);
}
r = new_refi(
id, /* Number of input dimensions */
od, /* Number of output dimensions */
ires, /* Input table resolution */
cres, /* clut resolution */
ores, /* Output table resolution */
input_curves, /* Callback functions */
md_table,
output_curves,
(void *)&rx /* Context to callbacks */
);
if (r == NULL) {
error("new_refi failed");
}
/* Now crate the imdi we want to test, using the */
/* reference as a template */
printf("About to create imdi\n");
s = new_imdi(
id, /* Number of input dimensions */
od, /* Number of output dimensions */
ip == 8 ? pixint8 : pixint16, /* Input pixel representation */
0x0, /* Treat every channel as unsigned */
NULL, /* No raster to callback mapping */
prec_min, /* Minimum of input and output precision */
op == 8 ? pixint8 : pixint16, /* Output pixel representation */
0x0, /* Treat every channel as unsigned */
NULL, /* No raster to callback mapping */
cres, /* Desired table resolution */
oopts_none, /* Desired per channel output options */
NULL, /* Output channel check values */
opts_none, /* Desired processing direction and stride support */
refi_input, /* Callback functions */
refi_clut,
refi_output,
(void *)r /* Context to callbacks */
);
if (s == NULL) {
error("new_imdi failed");
}
if (quick) {
iters = 1;
tbufsize = 4096/id;
} else {
iters = ITERS;
tbufsize = TBUFSIZE/id;
}
/* Allocate the test buffers */
if ((ibuf = malloc(sizeof(unsigned char) * ip/8 * id * tbufsize)) == NULL)
error("Malloc of input buffer failed");
ibuf2 = (unsigned short *)ibuf;
if ((obuf = malloc(sizeof(unsigned char) * op/8 * od * tbufsize)) == NULL)
error("Malloc of output buffer failed");
obuf2 = (unsigned short *)obuf;
/* Initialise the input buffer contents */
rand32(0x12345678);
if (ip == 8) {
unsigned ui;
int rr = rbits;
if (rr > 8)
rr = 8;
rmask = ((1 << rr) -1) << (8-rr);
for (ui = 0; ui < tbufsize; ui += id) {
for (e = 0; e < id; e++) {
unsigned long ran = rand32(0);
ibuf[ui + e] = (unsigned char)(ran & rmask);
}
}
} else {
unsigned ui;
rmask = ((1 << rbits) -1) << (16-rbits);
for (ui = 0; ui < tbufsize; ui += id) {
for (e = 0; e < id; e++) {
unsigned long ran = rand32(0);
ibuf2[ui + e] = (unsigned short)(ran & rmask);
}
}
}
/* We are assuming packed pixel interleaved */
inp[0] = ibuf;
outp[0] = obuf;
/* Benchmark it */
stime = clock();
for (n = 0; n < iters; n++) {
s->interp(s, (void **)outp, 0, (void **)inp, 0, tbufsize);
}
ttime = clock() - stime;
xtime = (double)ttime/(double)CLOCKS_PER_SEC;
npixels = (double)iters * (double)tbufsize;
if (xtime > 0.0)
printf("Speed = rate = %f Mpix/sec\n",1e-6 * npixels / xtime);
else
printf("Speed - too fast!\n");
{
unsigned ui;
double mxerr = 0.0;
double avgerr = 0.0;
/* Verify the accuracy against refi of each sample */
for (ui = j = 0; ui < tbufsize; ui += id, j += od) {
int mxserr;
if (ip == 8) {
for (e = 0; e < id; e++) {
ribuf[e] = ibuf[ui + e]/255.0;
}
} else {
for (e = 0; e < id; e++) {
ribuf[e] = ibuf2[ui + e]/65535.0;
}
}
refi_interp(r, robuf, ribuf);
mxserr = 0;
if (op == 8) {
for (e = 0; e < od; e++) {
double err = robuf[e] * 255.0 - obuf[j + e];
if (err < 0)
err = -err;
if (err > mxerr)
mxerr = err;
if (err > mxserr)
mxserr = err;
avgerr += err;
}
} else {
for (e = 0; e < od; e++) {
double err = robuf[e] * 65535.0 - obuf2[j + e];
if (err < 0)
err = -err;
if (err > mxerr)
mxerr = err;
if (err > mxserr)
mxserr = err;
avgerr += err;
}
}
#if defined(REPORT_ERRORS) || defined(VERBOSE)
if (mxserr >= 37) {
if (ip == 8) {
if (id == 1)
printf("in %d, ", ibuf[ui+0]);
if (id == 2)
printf("in %d %d, ", ibuf[ui+0], ibuf[ui+1]);
if (id == 3)
printf("in %d %d %d, ", ibuf[ui+0], ibuf[ui+1], ibuf[ui+2]);
if (id == 4)
printf("in %d %d %d, ",
ibuf[ui+0], ibuf[ui+1], ibuf[ui+2], ibuf[ui+3]);
} else {
if (id == 1)
printf("in %d, ", ibuf2[ui+0]);
if (id == 2)
printf("in %d %d, ", ibuf2[ui+0], ibuf2[ui+1]);
if (id == 3)
printf("~in %d %d %d, ", ibuf2[ui+0], ibuf2[ui+1], ibuf2[ui+2]);
if (id == 4)
printf("in %d %d %d, ",
ibuf2[ui+0], ibuf2[ui+1], ibuf2[ui+2], ibuf2[ui+3]);
}
if (ip == 8) {
if (od == 1)
printf("is %d, should be %d\n",
obuf[j+0],
(int)(robuf[0] * 255.0 + 0.5));
if (od == 2)
printf("is %d %d, should be %d %d\n",
obuf[j+0], obuf[j+1],
(int)(robuf[0] * 255.0 + 0.5),
(int)(robuf[1] * 255.0 + 0.5));
if (od == 3)
printf("is %d %d %d, should be %d %d %d\n",
obuf[j+0], obuf[j+1], obuf[j+2],
(int)(robuf[0] * 255.0 + 0.5),
(int)(robuf[1] * 255.0 + 0.5),
(int)(robuf[2] * 255.0 + 0.5));
if (od == 4)
printf("is %d %d %d %d, should be %d %d %d %d\n",
obuf[j+0], obuf[j+1], obuf[j+2], obuf[j+3],
(int)(robuf[0] * 255.0 + 0.5),
(int)(robuf[1] * 255.0 + 0.5),
(int)(robuf[2] * 255.0 + 0.5),
(int)(robuf[3] * 255.0 + 0.5));
} else {
if (od == 1)
printf("is %d, should be %d\n",
obuf2[j+0],
(int)(robuf[0] * 65535.0 + 0.5));
if (od == 2)
printf("is %d %d, should be %d %d\n",
obuf2[j+0], obuf2[j+1],
(int)(robuf[0] * 65535.0 + 0.5),
(int)(robuf[1] * 65535.0 + 0.5));
if (od == 3)
printf("is %d %d %d, should be %d %d %d\n",
obuf2[j+0], obuf2[j+1], obuf2[j+2],
(int)(robuf[0] * 65535.0 + 0.5),
(int)(robuf[1] * 65535.0 + 0.5),
(int)(robuf[2] * 65535.0 + 0.5));
if (od == 4)
printf("is %d %d %d %d, should be %d %d %d %d\n",
obuf2[j+0], obuf2[j+1], obuf2[j+2], obuf2[j+3],
(int)(robuf[0] * 65535.0 + 0.5),
(int)(robuf[1] * 65535.0 + 0.5),
(int)(robuf[2] * 65535.0 + 0.5),
(int)(robuf[3] * 65535.0 + 0.5));
}
}
#endif /* VERBOSE || REPORT+ERRORS */
}
avgerr /= ((double)tbufsize * od);
{
double fmxerr; /* Relative maximum error */
double favgerr; /* Relative average error */
/* Always relative to basic precision */
fmxerr = mxerr / ((1 << op) - 1.0);
favgerr = avgerr / ((1 << op) - 1.0);
printf("Worst error = %f = %f%%, average error = %f%%\n",
mxerr, 100.0 * fmxerr, 100.0 * favgerr);
printf("\n");
if (fmxerr > omxerr)
omxerr = fmxerr;
}
}
/* Free everything up */
free(ibuf);
free(obuf);
refi_free(r);
s->del(s);
if (stop && (100.0 * omxerr) > 1.2) {
goto quit;
}
}
}
}
quit:;
printf("Overall worst error = %f%%\n", 100.0 * omxerr);
return 0;
}
/* ------------------------------------------------- */
/* Support */
/* Run an interpolation though the whole refi */
void refi_interp(
refi *r,
double *out_vals,
double *in_vals
) {
#ifdef QUANTIZE
int e;
#endif
double ivals[MXDI];
double ovals[MXDO];
refi_input((void *)r, ivals, in_vals);
#ifdef QUANTIZE
for (e = 0; e < r->id; e++)
ivals[e] = ((int)(ivals[e] * 255.0 + 0.5))/255.0; /* Quantize to 8 bits */
#endif
refi_clut((void *)r, ovals, ivals);
#ifdef QUANTIZE
for (e = 0; e < r->od; e++)
ovals[e] = ((int)(ovals[e] * 255.0 + 0.5))/255.0; /* Quantize to 8 bits */
#endif
refi_output((void *)r, out_vals, ovals);
}
/* ------------------------------------------------- */
/* Some test functions */
/* Single bump version */
double
trans1(
double in,
double t /* Non-linearity factor. 0.0 to +/-1.0 */
) {
double out;
out = in + t * in * (1.0 - in);
return out;
}
/* Double bump version */
double
trans2(
double in,
double t /* Non-linearity factor. 0.0 to +/-1.0 */
) {
double nf, out;
if (in >= 0.5) {
nf = -2.0 * (in - 0.5) * (1.0 - in);
} else {
nf = 2.0 * in * (0.5 - in);
}
out = in + t * nf;
return out;
}

212
Argyll_V3.5.0/imdi/refi.c Normal file
View File

@@ -0,0 +1,212 @@
/* Test support code */
/*
* Copyright 2000 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
#include "stdio.h"
#include "stdlib.h"
#include "refi.h"
/* Callbackes used to setup rspl's */
static void inputlu(
void *cbctx,
double *out,
double *in
) {
int i;
refi *r = (refi *)cbctx;
double ov[MXDI], iv[MXDI];
for (i = 0; i < r->id; i++)
iv[i] = *in;
r->input_curves(r->cntx, ov, iv);
*out = ov[r->chan];
}
static void clutlu(
void *cbctx,
double *out,
double *in
) {
refi *r = (refi *)cbctx;
r->md_table(r->cntx, out, in);
}
static void outputlu(
void *cbctx,
double *out,
double *in
) {
int i;
refi *r = (refi *)cbctx;
double ov[MXDO], iv[MXDO];
for (i = 0; i < r->od; i++)
iv[i] = *in;
r->output_curves(r->cntx, ov, iv);
*out = ov[r->chan];
}
refi *new_refi(
int id, /* Number of input dimensions */
int od, /* Number of output dimensions */
int inres, /* Desired input table resolution */
int clutres, /* Desired clut table resolution */
int outres, /* Desired output table resolution */
/* Callbacks to lookup the table values */
void (*input_curves) (void *cntx, double *out_vals, double *in_vals),
void (*md_table) (void *cntx, double *out_vals, double *in_vals),
void (*output_curves)(void *cntx, double *out_vals, double *in_vals),
void *cntx /* Context to callbacks */
) {
refi *r;
int e;
int gres[MXDI];
if ((r = (refi *)malloc(sizeof(refi))) == NULL) {
fprintf(stderr,"Malloc of refi failed\n");
exit (-1);
}
r->id = id;
r->od = od;
r->inres = inres;
r->clutres = clutres;
r->outres = outres;
r->input_curves = input_curves;
r->md_table = md_table;
r->output_curves = output_curves;
r->cntx = cntx;
/* Create some input interpolations */
for (e = 0; e < id; e++) {
if ((r->in[e] = new_rspl(RSPL_NOFLAGS, 1, 1)) == NULL) {
fprintf(stderr,"new_rspl failed\n");
exit (-1);
}
r->chan = e;
r->in[e]->set_rspl(r->in[e], 0, (void *)r, inputlu, NULL, NULL, &inres, NULL, NULL);
}
/* Clut */
if ((r->clut = new_rspl(RSPL_NOFLAGS, id, od)) == NULL) {
fprintf(stderr,"new_rspl failed\n");
exit (-1);
}
for (e = 0; e < id; e++)
gres[e] = clutres;
r->clut->set_rspl(r->clut, 0, (void *)r, clutlu, NULL, NULL, gres, NULL, NULL);
/* Create some output interpolations */
for (e = 0; e < od; e++) {
if ((r->out[e] = new_rspl(RSPL_NOFLAGS, 1, 1)) == NULL) {
fprintf(stderr,"new_rspl failed\n");
exit (-1);
}
r->chan = e;
r->out[e]->set_rspl(r->out[e], 0, (void *)r, outputlu, NULL, NULL, &outres, NULL, NULL);
}
return r;
}
/* Run an interpolation through an input table */
void refi_input(
void *cntx,
double *out_vals,
double *in_vals
) {
refi *r = (refi *)cntx;
int e;
co vals; /* Input and output values */
for (e = 0; e < r->id; e++) {
vals.p[0] = in_vals[e];
r->in[e]->interp(r->in[e], &vals);
out_vals[e] = vals.v[0];
}
}
/* Run an interpolation through an clut table */
void refi_clut(
void *cntx,
double *out_vals,
double *in_vals
) {
refi *r = (refi *)cntx;
int e;
co vals; /* Input and output values */
for (e = 0; e < r->id; e++)
vals.p[e] = in_vals[e];
r->clut->interp(r->clut, &vals);
for (e = 0; e < r->od; e++)
out_vals[e] = vals.v[e];
}
/* Run an interpolation through an output table */
void refi_output(
void *cntx,
double *out_vals,
double *in_vals
) {
refi *r = (refi *)cntx;
int e;
co vals; /* Input and output values */
for (e = 0; e < r->od; e++) {
vals.p[0] = in_vals[e];
r->out[e]->interp(r->out[e], &vals);
out_vals[e] = vals.v[0];
}
}
void
refi_free(
refi *r
) {
int e;
for (e = 0; e < r->id; e++) {
r->in[e]->del(r->in[e]);
}
r->clut->del(r->clut);
for (e = 0; e < r->od; e++) {
r->out[e]->del(r->out[e]);
}
}

53
Argyll_V3.5.0/imdi/refi.h Normal file
View File

@@ -0,0 +1,53 @@
/* Reference floating point interpolator constructed out of rspl's */
/* This provides imdi functionality in floating point */
/*
* Copyright 2000 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
#include "../rspl/rspl.h"
/* ------------------------------------------------ */
typedef struct {
int id, od; /* Input and output dimensions */
int inres; /* Desired input table resolution */
int clutres; /* Desired clut table resolution */
int outres; /* Desired output table resolution */
rspl *in[MXDI];
rspl *clut;
rspl *out[MXDO];
void (*input_curves) (void *cntx, double *out_vals, double *in_vals);
void (*md_table) (void *cntx, double *out_vals, double *in_vals);
void (*output_curves)(void *cntx, double *out_vals, double *in_vals);
void *cntx; /* Context to callbacks */
int chan; /* Current callback channel */
} refi;
refi *new_refi(
int id, /* Number of input dimensions */
int od, /* Number of output dimensions */
int inres, /* Desired input table resolution */
int clutres, /* Desired clut table resolution */
int outres, /* Desired output table resolution */
/* Callbacks to lookup the table values */
void (*input_curves) (void *cntx, double *out_vals, double *in_vals),
void (*md_table) (void *cntx, double *out_vals, double *in_vals),
void (*output_curves)(void *cntx, double *out_vals, double *in_vals),
void *cntx /* Context to callbacks */
);
void refi_free(refi *r);
/* Component interpolations */
void refi_input(void *cntx, double *out_vals, double *in_vals);
void refi_clut(void *cntx, double *out_vals, double *in_vals);
void refi_output(void *cntx, double *out_vals, double *in_vals);

322
Argyll_V3.5.0/imdi/ssort.c Normal file
View File

@@ -0,0 +1,322 @@
/* Test code that generates optimised C sorting */
/* code, suitable for classifying an input vector */
/* into a particular simplex. */
/*
* Copyright 2000 Graeme W. Gill
* All rights reserved.
*
* This material is licenced under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 :-
* see the License.txt file for licencing details.
*/
/* Intended for inclusion in IMDI for 16 bit support */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
/* Sorting data */
#define MAXSV 50 /* Maximum sort variables */
typedef struct {
int bot; /* 0 if we are doing ==, 1 if >, 2 if else */
int dval; /* Difference value to apply */
int vals[MAXSV]; /* Variable values */
int sort[MAXSV]; /* Sorted index */
} sortd;
/* Context */
typedef struct {
FILE *of; /* Output file */
int indt; /* Indent */
/* Sort data */
int nv; /* Number of variables to sort */
int sl; /* Non-zero to generate code for smallest to largest */
int eq; /* Non-zero to generate code for equal case */
int la; /* Non-zero to generate labels */
int rl; /* Recursion level */
sortd sd[MAXSV]; /* Data at each recursion level */
int ln; /* Label number */
} fileo;
void line(fileo *f, char *fmt, ...); /* Output one line */
void niline(fileo *f, char *fmt, ...); /* Output one line, no indent */
void sline(fileo *f, char *fmt, ...); /* Output start of line line */
void mline(fileo *f, char *fmt, ...); /* Output middle of line */
void eline(fileo *f, char *fmt, ...); /* Output end of line */
void cr(fileo *f) { line(f,""); } /* Output a blank line */
void inc(fileo *f) { f->indt++; } /* Increment the indent level */
void dec(fileo *f) { f->indt--; } /* Decrement the indent level */
int
main(void) {
fileo f[1];
f->of = fopen("ttt.c","w");
f->indt = 0;
line(f,"/* This is the top */");
cr(f);
line(f,"#include <stdio.h>");
cr(f);
line(f,"void main(void) {");
inc(f);
line(f,"int v0, v1, v2, v3, v4;");
line(f,"printf(\"Hi there!\\n\");");
line(f,"v0 = 1;");
line(f,"v1 = 9;");
line(f,"v2 = 3;");
line(f,"v3 = 2;");
line(f,"v4 = 0;");
/* ================ */
/* Sort development */
{
int xx;
int i, j;
f->nv = 6; /* No variables */
f->sl = 1; /* Smallest to largest */
f->eq = 0; /* No equals case */
f->la = 0; /* No labels */
f->rl = 0; /* Top recursion level */
f->ln = 0; /* Start label number */
f->sd[f->rl].bot = f->eq ? 0 : 1;
f->sd[f->rl].dval = 256;
for (i = 0; i < f->nv; i++) {
f->sd[f->rl].vals[i] = -99999; /* Initial sort value = unknown */
f->sd[f->rl].sort[i] = i; /* Initial sort order */
}
f->sd[f->rl].vals[0] = 0; /* Make sure one is known */
/* First label is for no known sort */
if (f->la)
niline(f," label%d:;",f->ln++);
/* Until we have done every sort condition */
for (;f->rl >= 0;) {
int ix, nix; /* Variable index that needs comparison */
int six, snix; /* Sorted references to ix, nix */
//printf("\n~~recursion level %d\n",f->rl);
//for (i = 0; i < f->nv; i++) {
//xx = f->sd[f->rl].sort[i];
//printf("Current = %d (index %d)\n",f->sd[f->rl].vals[xx],xx);
//}
/* see if we have resolved a sort */
for (i = 1; i < f->nv; i++) {
six = i-1;
ix = f->sd[f->rl].sort[i-1];
snix = i;
nix = f->sd[f->rl].sort[i];
if (f->sd[f->rl].vals[ix] == f->sd[f->rl].vals[nix]
|| f->sd[f->rl].vals[nix] == -99999) {
break; /* Not distinguishable or not known */
}
}
//if (i < f->nv)
//printf("~~Unresolved sort indexes %d %d\n",ix,nix);
//else
//printf("~~Resolved sort\n");
if (i < f->nv) {
/* We haven't fully sorted the variables yet. */
/* Compare ix to nix */
if (f->sd[f->rl].bot == 0) {
//printf("~~ Unresolved at level %d, doing comparison for equals\n",f->rl);
line(f,"if (v%d == v%d) {",ix,nix); /* } */
inc(f);
f->sd[f->rl+1] = f->sd[f->rl]; /* Structure copy */
f->sd[f->rl+1].bot = 0;
f->sd[f->rl].bot = 1;
f->rl++;
// ~~~~~9
/* Find next lowest value from nix */
for (i = snix+1; i < f->nv; i++) {
int si = f->sd[f->rl].sort[i];
if (f->sd[f->rl].vals[si] == -99999)
continue;
if (f->sd[f->rl].vals[si] < f->sd[f->rl].vals[nix]) {
f->sd[f->rl].vals[nix] =
(f->sd[f->rl].vals[si] + f->sd[f->rl].vals[nix])/2;
break;
}
}
if (i >= f->nv) { /* Not between next lowest */
f->sd[f->rl].vals[nix] = f->sd[f->rl].vals[ix] -256;
}
} else if (f->sd[f->rl].bot == 1) { /* { */
//printf("~~ Unresolved at level %d, doing comparison for greater\n",f->rl);
if (f->eq) {
dec(f);
line(f,"} else if (v%d %c v%d) {",ix, f->sl ? '<':'>',nix); /* } */
} else
line(f,"if (v%d %c v%d) {",ix,f->sl ? '<':'>', nix); /* } */
inc(f);
if (f->la)
niline(f," label%d:;",f->ln++);
f->sd[f->rl+1] = f->sd[f->rl]; /* Structure copy */
f->sd[f->rl+1].bot = f->eq ? 0 : 1;
f->sd[f->rl].bot = 2;
f->rl++;
/* Find next lowest value from nix */
for (i = snix+1; i < f->nv; i++) {
int si = f->sd[f->rl].sort[i];
if (f->sd[f->rl].vals[si] == -99999)
continue;
if (f->sd[f->rl].vals[si] < f->sd[f->rl].vals[nix]) {
f->sd[f->rl].vals[nix] =
(f->sd[f->rl].vals[si] + f->sd[f->rl].vals[nix])/2;
break;
}
}
if (i >= f->nv) { /* Not between next lowest */
f->sd[f->rl].vals[nix] = f->sd[f->rl].vals[ix] -256;
}
} else if (f->sd[f->rl].bot == 2) { /* { */
//printf("~~ Unresolved at level %d, doing else\n",f->rl);
dec(f);
line(f,"} else { /* v%d %c v%d */",ix,f->sl ? '>':'<', nix); /* } */
inc(f);
if (f->la)
niline(f," label%d:;",f->ln++);
f->sd[f->rl+1] = f->sd[f->rl]; /* Structure copy */
f->sd[f->rl+1].bot = f->eq ? 0 : 1;
f->sd[f->rl].bot = 3;
f->rl++;
if (six-1 >= 0) { /* If there is a higher value */
int si = f->sd[f->rl].sort[six-1];
/* Make equal to next highest, since never been compared */
f->sd[f->rl].vals[nix] = f->sd[f->rl].vals[si];
} else { /* Nothing above */
f->sd[f->rl].vals[nix] = f->sd[f->rl].vals[ix] + 256;
}
/* sort nix above ix */
j = f->sd[f->rl].sort[six];
f->sd[f->rl].sort[six] = f->sd[f->rl].sort[snix];
f->sd[f->rl].sort[snix] = j;
} else { /* We've done both cases - return from recursion */
//printf("~~ Unresolved at level %d, going up a level\n",f->rl);
dec(f); /* { */
line(f,"}");
f->rl--; /* Back a recursion level */
}
} else {
//printf("~~ Resolved at level %d, outputing sort code, up a level\n",f->rl);
/* We have a resolved sort */
/* So output the code for this sort combination */
sline(f,"/* Sorted ");
for (i = 0; i < f->nv; i++) {
mline(f," %d",f->sd[f->rl].sort[i]);
}
eline(f," */");
#ifdef NEVER
sline(f,"printf(\"Sorted = %%d %%d %%d %%d %%d\\n\"");
for (i = 0; i < f->nv; i++) {
mline(f,",v%d",f->sd[f->rl].sort[i]);
}
eline(f,");");
#else
for (i = 0; i < f->nv; i++) {
sline(f,"");
mline(f,"op[%d] = v%d",i,f->sd[f->rl].sort[i]);
eline(f,";");
}
line(f,"ip += %d;",f->nv);
line(f,"op += %d;",f->nv);
line(f,"continue;");
#endif
f->rl--; /* Back a recursion level */
}
}
}
/* ================ */
dec(f);
line(f,"}");
fclose(f->of);
return 0;
}
/* Output a line to the file (including trailing \n) */
void
line(fileo *f, char *fmt, ...)
{
int i;
va_list args;
/* Indent to the correct level */
for (i = 0; i < f->indt; i++)
fprintf(f->of," ");
va_start(args, fmt);
vfprintf(f->of, fmt, args);
va_end(args);
fprintf(f->of, "\n");
}
/* Output a line to the file (including trailing \n) */
/* No indent */
void
niline(fileo *f, char *fmt, ...)
{
int i;
va_list args;
va_start(args, fmt);
vfprintf(f->of, fmt, args);
va_end(args);
fprintf(f->of, "\n");
}
/* Output the start of a line to the file) */
void
sline(fileo *f, char *fmt, ...)
{
int i;
va_list args;
/* Indent to the correct level */
for (i = 0; i < f->indt; i++)
fprintf(f->of," ");
va_start(args, fmt);
vfprintf(f->of, fmt, args);
va_end(args);
}
/* Output the middle of a line to the file) */
void
mline(fileo *f, char *fmt, ...)
{
int i;
va_list args;
va_start(args, fmt);
vfprintf(f->of, fmt, args);
va_end(args);
}
/* Output the end of a line to the file (including trailing \n) */
void
eline(fileo *f, char *fmt, ...)
{
int i;
va_list args;
va_start(args, fmt);
vfprintf(f->of, fmt, args);
va_end(args);
fprintf(f->of, "\n");
}