pax_global_header00006660000000000000000000000064150327471700014520gustar00rootroot0000000000000052 comment=8283d632c194b962a4e2dcd6fb37b2ff10eed00f libimagequant-4.4.0/000077500000000000000000000000001503274717000143475ustar00rootroot00000000000000libimagequant-4.4.0/.github/000077500000000000000000000000001503274717000157075ustar00rootroot00000000000000libimagequant-4.4.0/.github/workflows/000077500000000000000000000000001503274717000177445ustar00rootroot00000000000000libimagequant-4.4.0/.github/workflows/ci.yml000066400000000000000000000012701503274717000210620ustar00rootroot00000000000000name: CI on: push: branches: [ main ] pull_request: branches: [ main ] env: CARGO_TERM_COLOR: always CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable - uses: actions-rs/cargo@v1 with: command: test args: --no-default-features - uses: actions-rs/cargo@v1 with: command: test args: --all-features --all - uses: actions-rs/cargo@v1 with: command: test args: --all-features --all --release libimagequant-4.4.0/.gitignore000066400000000000000000000002601503274717000163350ustar00rootroot00000000000000imagequant.pc *.lo *.o *.a *.so.0 *.so *.bz2 *.dylib *.dylib.0 *.jnilib *.dSYM org/pngquant/*.class org/pngquant/*.h target/ quantized_example.png example lodepng.? Cargo.lock libimagequant-4.4.0/CHANGELOG000066400000000000000000000057061503274717000155710ustar00rootroot00000000000000version 4.2 ----------- - rewritten and improved handling of fixed palette colors - support for palettes larger than 256 colors - fix for remapping when importance_map has lots of pixels with 0 importance version 4.1 ----------- - improved dithering over preset background - remap_into_vec method - fix for images over 16 megapixels version 4.0 ----------- - rewritten in Rust - replaced Makefiles with Cargo version 2.17 ------------ - quality improvement - ARM64 build fix version 2.16 ------------ - fixed LCMS2 error handling version 2.15 ------------ - speed and quality improvements version 2.14 ------------ - improved Rust API - quality improvements for remapping overlays over a background version 2.13 ------------ - support OpenMP in clang - dropped old Internet Explorer workarounds - speed and quality improvements version 2.12 ------------ - new liq_histogram_add_fixed_color() - faster for large/complex images - workarounds for Microsoft's outdated C compiler version 2.11 ------------ - new liq_image_set_background() for high-quality remapping of GIF frames - new liq_image_set_importance_map() for controlling which parts of the image get more palette colors - improved OpenMP support version 2.10 ----------- - supports building with Rust/Cargo version 2.9 ----------- - new liq_histogram_add_colors() version 2.8 ----------- - standalone version - added Java interface (JNI) - new API for remapping multiple images to a single shared palette version 2.7 ----------- - improved dithering of saturated and semitransparent colors - libimagequant reports detailed progress and supports aborting of operations via callbacks - fixed order of log output when using openmp version 2.5 ----------- - replaced color search algorithm with vantage point tree, which is much faster and more reliable - deprecated IE6 workaround - warn when compiled without color profile support - improved support for predefined colors in libimagequant version 2.4 ----------- - fixed remapping of bright colors when dithering - added libimagequant API to add fixed preset colors to the palette version 2.3 ----------- - added ./configure script for better support of Intel C compiler and dependencies [thanks to pdknsk] - tweaked quality metric to better estimate quality of images with large solid backgrounds [thanks to Rolf Timmermans] - avoid applying quality setting to images that use palette already version 2.2 ----------- - OpenMP acceleration - improved support for Intel C Compiler, speedup in 32-bit GCC, and some workarounds for Visual Studio's incomplete C support version 2.1 ----------- - option to generate posterized output (for use with 16-bit textures) version 2.0 ----------- - refactored codebase into pngquant and standalone libimagequant - reduced memory usage by further 30% (and more for very large images) - less precise remapping improving speed by 25% in higher speed settings - fixed regression in dithering of alpha channel libimagequant-4.4.0/CODE_OF_CONDUCT.md000066400000000000000000000062331503274717000171520ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at kornel@geekhood.net. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ libimagequant-4.4.0/CONTRIBUTING.md000066400000000000000000000027211503274717000166020ustar00rootroot00000000000000 Thank you for contributing! pngquant and libimagequant are licensed under multiple licenses, so to make things clear, I'm accepting contributions as licensed under the BSD 2-clause license: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. libimagequant-4.4.0/COPYRIGHT000066400000000000000000001010321503274717000156370ustar00rootroot00000000000000 libimagequant is derived from code by Jef Poskanzer and Greg Roelofs licensed under pngquant's original license (at the end of this file), and contains extensive changes and additions by Kornel Lesiński licensed under GPL v3 or later. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - libimagequant © 2009-2018 by Kornel Lesiński. GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - © 1989, 1991 by Jef Poskanzer. © 1997, 2000, 2002 by Greg Roelofs. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. This software is provided "as is" without express or implied warranty. libimagequant-4.4.0/Cargo.toml000066400000000000000000000027241503274717000163040ustar00rootroot00000000000000[package] name = "imagequant" version = "4.4.0" description = "Convert 24/32-bit images to 8-bit palette with alpha channel.\nFor lossy PNG compression and high-quality GIF images\nDual-licensed like pngquant. See https://pngquant.org for details." authors = ["Kornel Lesiński "] license = "GPL-3.0-or-later" homepage = "https://pngquant.org/lib" repository = "https://github.com/ImageOptim/libimagequant" documentation = "https://docs.rs/imagequant" categories = ["multimedia::images"] keywords = ["quantization", "palette", "pngquant", "compression", "gif"] include = ["COPYRIGHT", "src/*.rs", "*.h", "README.md", "Cargo.toml"] readme = "README.md" edition = "2021" rust-version = "1.65" [features] default = ["threads"] threads = ["dep:rayon", "dep:thread_local"] # supports up to 2048 colors for palettes, but NOT FOR REMAPPING large_palettes = [] # this is private and unstable for imagequant-sys only, do not use _internal_c_ffi = [] [profile.release] debug = false panic = "abort" [lib] doctest = false [dependencies] arrayvec = "0.7.4" rgb = { version = "0.8.47", default-features = false, features = ["bytemuck"] } rayon = { version = "1.10.0", optional = true } thread_local = { version = "1.1.8", optional = true } once_cell = "1.19.0" [dev-dependencies] lodepng = "3.10" [workspace] members = ["imagequant-sys", "imagequant-sys/c_test"] [package.metadata.release] consolidate-commits = true tag-message = "" tag-prefix = "" tag-name = "{{version}}" libimagequant-4.4.0/README.md000066400000000000000000000153461503274717000156370ustar00rootroot00000000000000# [libimagequant](https://pngquant.org/lib/) — Image Quantization Library Imagequant library converts RGBA images to palette-based 8-bit indexed images, *including* alpha component. It's ideal for generating tiny PNG images and [nice-looking GIFs](https://gif.ski). Image encoding/decoding isn't handled by the library itself, bring your own encoder. If you're looking for a command-line tool, see [pngquant](https://pngquant.org). ## Getting started in C This library can be used in C programs via [imagequant-sys](https://github.com/ImageOptim/libimagequant/tree/main/imagequant-sys) [Rust](https://www.rust-lang.org/) package. ```bash rustup update git clone https://github.com/ImageOptim/libimagequant cd imagequant-sys cargo build --release # makes target/release/libimagequant_sys.a ``` See [the C library documentation for more details](https://pngquant.org/lib/). ## Getting started in Rust Add to `Cargo.toml`: ```bash rustup update cargo add imagequant ``` [See docs.rs for the library API documentation](https://docs.rs/imagequant). ## License Libimagequant is dual-licensed: * For Free/Libre Open Source Software it's available under GPL v3 or later with additional [copyright notices](https://raw.github.com/ImageOptim/libimagequant/master/COPYRIGHT) for historical reasons. * For use in closed-source software, AppStore distribution, and other non-GPL uses, you can [obtain a commercial license](https://supso.org/projects/pngquant). Feel free to ask kornel@pngquant.org for details and custom licensing terms if you need them. ## Upgrading instructions libimagequant v2 used to be a C library. libimagequant v4 is written entirely in Rust, but still exports the same C interface for C programs. You will need to install Rust 1.70+ to build it, and adjust your build commands. If you do not want to upgrade, you can keep using [the C version of the library](https://github.com/imageoptim/libimagequant/tree/2.x) in the `2.x` branch of the [repo](https://github.com/ImageOptim/libimagequant). ### C static library users Files for C/C++ are now in the `imagequant-sys/` subdirectory, not in the root of the repo. There is no `configure && make` any more. To build the library, install [Rust via rustup](https://rustup.rs), and run: ```bash rustup update cd imagequant-sys cargo build --release ``` It produces `target/release/libimagequant_sys.a` static library. The API, ABI, and header files remain the same, so everything else should work the same. If you're building for macOS or iOS, see included xcodeproj file (add it as a [subproject](https://gitlab.com/kornelski/cargo-xcode#usage) to yours). If you're building for Android, run `rustup target add aarch64-linux-android; cargo build --release --target aarch64-linux-android` and use `target/aarch64-linux-android/release/libimagequant_sys.a`. Same for cross-compiling to other platforms. See `rustup target list`. ### C dynamic library for package maintainers If you're an application developer, please use the static linking option above — that option is much easier, and gives smaller executables. The API and ABI of this library remains the same. It has the same sover, so it can be a drop-in replacement for the previous C version. This library is now a typical Rust/Cargo library. If you want to set up [off-line builds](https://doc.rust-lang.org/cargo/faq.html#how-can-cargo-work-offline) or [override dependencies](https://doc.rust-lang.org/cargo/reference/overriding-dependencies.html), it works the same as for every other Rust project. See [Cargo docs](https://doc.rust-lang.org/cargo/) for things like [`cargo fetch`](https://doc.rust-lang.org/cargo/commands/cargo-fetch.html) or [`cargo vendor`](https://doc.rust-lang.org/cargo/commands/cargo-vendor.html) (but I don't recommend vendoring). If you want to build a dynamic library, but aren't bothered by soname and rpath being wrong, modify `imagequant-sys/Cargo.toml` and add `"cdylib"` to the existing `crate-type` property, and then `cargo build --release` will do its usual half-finished job and build `target/release/libimagequant.{so,dylib,dll}`. #### Building with `make` `configure && make` is gone. I hoped I could build a dynamic library just by wrapping the static library, but apparently that won't work, so I can't easily recreate the old `make install`. I wish there was a more standard and lightweight solution than using the `cargo-c` tool, so if you're good at wrangling linker flags and symbol visibility, please send pull requests. #### Building with `cargo-c` The [`cargo-c`](https://lib.rs/cargo-c) tool knows how to build and link so/dylib properly, and generates an accurate pkg-config file, so it's de-facto required for a correct system-wide install of a dynamic library. ```bash rustup update cd imagequant-sys cargo install cargo-c cargo cinstall --prefix=/usr/local --destdir=. ``` This makes Rust 1.70 and `cargo-c` package a build-time dependency. No runtime deps (apart from Cargo-internal ones). OpenMP has been dropped entirely. #### Interaction with pngquant pngquant v2 can use this library as a dynamic library. However, pngquant v4 does not support unbundling. It uses this library as a Cargo dependency via its Rust-native interface. The shared libimagequant library exports only a stable ABI for C programs, and this interface is not useful for Rust programs. ### Upgrading for Rust users If you've used the [`imagequant-sys`](https://lib.rs/imagequant-sys) crate, switch to the higher-level [`imagequant`](https://lib.rs/imagequant) crate. The `imagequant` v4 is almost entirely backwards-compatible, with small changes that the Rust compiler will point out (e.g. changed use of `c_int` to `u32`). See [docs](https://docs.rs/imagequant). Please fix any deprecation warnings you may get, because the deprecated functions will be removed. The `openmp` Cargo feature has been renamed to `threads`. `.new_image()` can now take ownership of its argument to avoid copying. If you get an error that `From<&Vec>` is not implemented, then either don't pass by reference (moves, avoids copying), or call `.as_slice()` on it (to copy the pixels), or use `.new_image_borrowed()` method instead. ### Threads support and WASM By default, when the `threads` Cargo feature is enabled, this library uses multi-threading. Number of threads can be controlled via `RAYON_NUM_THREADS` environment variable. Threads in WASM are experimental, and require [special handling](https://github.com/GoogleChromeLabs/wasm-bindgen-rayon). If you're targeting WASM, you'll most likely want to disable threads. To disable threads when using this library as a dependency, disable default features like this in `Cargo.toml`: ```toml [dependencies] imagequant = { version = "4.0", default-features = false } ``` When you compile the library directly, add `--no-default-features` flag instead. libimagequant-4.4.0/benches/000077500000000000000000000000001503274717000157565ustar00rootroot00000000000000libimagequant-4.4.0/benches/bench.rs000066400000000000000000000046271503274717000174140ustar00rootroot00000000000000#![feature(test)] extern crate test; use test::Bencher; use imagequant::*; #[bench] fn histogram(b: &mut Bencher) { let img = lodepng::decode32_file("/Users/kornel/Desktop/canvas.png").unwrap(); let liq = Attributes::new(); b.iter(move || { let mut img = liq.new_image(&*img.buffer, img.width, img.height, 0.).unwrap(); let mut hist = Histogram::new(&liq); hist.add_image(&liq, &mut img).unwrap(); }); } #[bench] fn remap_ord(b: &mut Bencher) { let img = lodepng::decode32_file("/Users/kornel/Desktop/canvas.png").unwrap(); let mut buf = vec![std::mem::MaybeUninit::uninit(); img.width * img.height]; let mut liq = Attributes::new(); liq.set_speed(10).unwrap(); let mut img = liq.new_image(img.buffer, img.width, img.height, 0.).unwrap(); liq.set_max_colors(256).unwrap(); let mut res = liq.quantize(&mut img).unwrap(); res.set_dithering_level(0.).unwrap(); b.iter(move || { res.remap_into(&mut img, &mut buf).unwrap(); res.remap_into(&mut img, &mut buf).unwrap(); }); } #[bench] fn kmeans(b: &mut Bencher) { b.iter(_unstable_internal_kmeans_bench()); } #[bench] fn remap_floyd(b: &mut Bencher) { let img = lodepng::decode32_file("/Users/kornel/Desktop/canvas.png").unwrap(); let mut buf = vec![std::mem::MaybeUninit::uninit(); img.width * img.height]; let mut liq = Attributes::new(); liq.set_speed(10).unwrap(); let mut img = liq.new_image(img.buffer, img.width, img.height, 0.).unwrap(); let mut res = liq.quantize(&mut img).unwrap(); res.set_dithering_level(1.).unwrap(); b.iter(move || { res.remap_into(&mut img, &mut buf).unwrap(); res.remap_into(&mut img, &mut buf).unwrap(); }); } #[bench] fn quantize_s8(b: &mut Bencher) { let img = lodepng::decode32_file("/Users/kornel/Desktop/canvas.png").unwrap(); let mut liq = Attributes::new(); liq.set_speed(8).unwrap(); b.iter(move || { let mut img = liq.new_image(&*img.buffer, img.width, img.height, 0.).unwrap(); liq.quantize(&mut img).unwrap(); }); } #[bench] fn quantize_s1(b: &mut Bencher) { let img = lodepng::decode32_file("/Users/kornel/Desktop/canvas.png").unwrap(); let mut liq = Attributes::new(); liq.set_speed(1).unwrap(); b.iter(move || { let mut img = liq.new_image(&*img.buffer, img.width, img.height, 0.).unwrap(); liq.quantize(&mut img).unwrap(); }); } libimagequant-4.4.0/examples/000077500000000000000000000000001503274717000161655ustar00rootroot00000000000000libimagequant-4.4.0/examples/basic.rs000066400000000000000000000020541503274717000176150ustar00rootroot00000000000000//! fn main() { // Image loading/saving is outside scope of this library let width = 10; let height = 10; let fakebitmap = vec![imagequant::RGBA {r:100, g:200, b:250, a:255}; width * height]; // Configure the library let mut liq = imagequant::new(); liq.set_speed(5).unwrap(); liq.set_quality(70, 99).unwrap(); // Describe the bitmap let mut img = liq.new_image(&fakebitmap[..], width, height, 0.0).unwrap(); // The magic happens in quantize() let mut res = match liq.quantize(&mut img) { Ok(res) => res, Err(err) => panic!("Quantization failed, because: {err:?}"), }; // Enable dithering for subsequent remappings res.set_dithering_level(1.0).unwrap(); // You can reuse the result to generate several images with the same palette let (palette, pixels) = res.remapped(&mut img).unwrap(); println!( "Done! Got palette {palette:?} and {} pixels with {}% quality", pixels.len(), res.quantization_quality().unwrap() ); } libimagequant-4.4.0/imagequant-sys/000077500000000000000000000000001503274717000173165ustar00rootroot00000000000000libimagequant-4.4.0/imagequant-sys/.gitignore000066400000000000000000000000151503274717000213020ustar00rootroot00000000000000usr/ target/ libimagequant-4.4.0/imagequant-sys/COPYRIGHT000077700000000000000000000000001503274717000223122../COPYRIGHTustar00rootroot00000000000000libimagequant-4.4.0/imagequant-sys/Cargo.toml000066400000000000000000000031771503274717000212560ustar00rootroot00000000000000[package] name = "imagequant-sys" version = "4.1.0" description = "Convert 24/32-bit images to 8-bit palette with alpha channel.\nC API/FFI libimagequant that powers pngquant lossy PNG compressor.\n\nDual-licensed like pngquant. See https://pngquant.org for details." authors = ["Kornel Lesiński "] license = "GPL-3.0-or-later" homepage = "https://pngquant.org/lib" repository = "https://github.com/ImageOptim/libimagequant" documentation = "https://docs.rs/imagequant" categories = ["multimedia::images"] keywords = ["quantization", "palette", "image", "dither", "quant"] include = ["COPYRIGHT", "src/*.rs", "build.rs", "*.h", "README.md", "Cargo.toml"] readme = "README.md" edition = "2021" links = "imagequant" build = "build.rs" rust-version = "1.63" [lib] crate-type = ["staticlib", "lib"] doctest = false path = "src/ffi.rs" name = "imagequant_sys" [dependencies] imagequant = { path = "..", version = "4.4.0", default-features = false, features = ["_internal_c_ffi"] } bitflags = "2.5" libc = "0.2.153" [package.metadata.capi.library] name = "imagequant" version = "0.4.1" [package.metadata.capi.pkg_config] name = "imagequant" filename = "imagequant" description = "Convert 24/32-bit images to 8-bit palette with alpha channel." [package.metadata.capi.header] name = "libimagequant" subdirectory = "" generation = false [package.metadata.capi.install.include] asset = [{from = "libimagequant.h"}] [package.metadata.release] consolidate-commits = true tag-message = "" tag-prefix = "" tag-name = "{{version}}" [features] # internal for cargo-c only capi = [] default = ["imagequant/default"] threads = ["imagequant/threads"] libimagequant-4.4.0/imagequant-sys/Makefile000066400000000000000000000046461503274717000207700ustar00rootroot00000000000000# You can configure these PREFIX ?= /usr/local LIBDIR ?= $(PREFIX)/lib INCLUDEDIR ?= $(PREFIX)/include PKGCONFIGDIR ?= $(LIBDIR)/pkgconfig DESTDIR ?= "" VERSION=$(shell grep '^version = "4' Cargo.toml | grep -Eo "4\.[0-9.]+") STATICLIB=libimagequant.a JNILIB=libimagequant.jnilib JAVACLASSES = org/pngquant/LiqObject.class org/pngquant/PngQuant.class org/pngquant/Image.class org/pngquant/Result.class JAVAHEADERS = $(JAVACLASSES:.class=.h) JAVAINCLUDE = -I'$(JAVA_HOME)/include' -I'$(JAVA_HOME)/include/linux' -I'$(JAVA_HOME)/include/win32' -I'$(JAVA_HOME)/include/darwin' PKGCONFIG = imagequant.pc all: static static: $(STATICLIB) java: $(JNILIB) $(STATICLIB): Cargo.toml cargo build --release cp ../target/release/libimagequant_sys.a $(STATICLIB) $(JNILIB): $(JAVAHEADERS) $(STATICLIB) org/pngquant/PngQuant.c # You may need to set LDFLAGS env var. See: cargo rustc -- --print native-static-libs $(CC) -g $(CFLAGS) $(LDFLAGS) $(JAVAINCLUDE) -shared -o $@ org/pngquant/PngQuant.c $(STATICLIB) $(JAVACLASSES): %.class: %.java javac $< $(JAVAHEADERS): %.h: %.class javah -o $@ $(subst /,., $(patsubst %.class,%,$<)) && touch $@ example: example.c lodepng.h lodepng.c $(STATICLIB) # remove -lpthread on Windows # add -ldl on Linux # You may need to set LDFLAGS env var. See: cargo rustc -- --print native-static-libs $(CC) -g $(CFLAGS) -Wall example.c $(STATICLIB) -lm -lpthread $(LDFLAGS) -o example lodepng.h: curl -o lodepng.h -L https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.h lodepng.c: curl -o lodepng.c -L https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.cpp clean: rm -f $(SHAREDLIBVER) $(SHAREDLIB) $(STATICLIB) rm -f $(JAVAHEADERS) $(JAVACLASSES) $(JNILIB) example rm -rf ../target distclean: clean rm -f imagequant.pc install: all $(PKGCONFIG) install -d $(DESTDIR)$(LIBDIR) install -d $(DESTDIR)$(PKGCONFIGDIR) install -d $(DESTDIR)$(INCLUDEDIR) install -m 644 $(STATICLIB) $(DESTDIR)$(LIBDIR)/$(STATICLIB) install -m 644 $(PKGCONFIG) $(DESTDIR)$(PKGCONFIGDIR)/$(PKGCONFIG) install -m 644 libimagequant.h $(DESTDIR)$(INCLUDEDIR)/libimagequant.h $(FIX_INSTALL_NAME) uninstall: rm -f $(DESTDIR)$(LIBDIR)/$(STATICLIB) rm -f $(DESTDIR)$(PKGCONFIGDIR)/$(PKGCONFIG) rm -f $(DESTDIR)$(INCLUDEDIR)/libimagequant.h $(PKGCONFIG): Cargo.toml sed 's|@PREFIX@|$(PREFIX)|;s|@VERSION@|$(VERSION)|' < imagequant.pc.in > $(PKGCONFIG) .PHONY: all static clean distclean java .DELETE_ON_ERROR: libimagequant-4.4.0/imagequant-sys/README.md000066400000000000000000000766231503274717000206130ustar00rootroot00000000000000# [libimagequant](https://pngquant.org/lib/) — Image Quantization Library Imagequant library converts RGBA images to palette-based 8-bit indexed images, *including* alpha component. It's ideal for generating tiny PNG images and [nice-looking GIFs](https://gif.ski). Image encoding/decoding isn't handled by the library itself, bring your own encoder. If you're looking for a command-line tool, see [pngquant](https://pngquant.org). ## License Libimagequant is dual-licensed: * For Free/Libre Open Source Software it's available under GPL v3 or later with additional [copyright notices](https://raw.github.com/ImageOptim/libimagequant/master/COPYRIGHT) for historical reasons. * For use in closed-source software, AppStore distribution, and other non-GPL uses, you can [obtain a commercial license](https://supso.org/projects/pngquant). Feel free to ask kornel@pngquant.org for details and custom licensing terms if you need them. ## Rust documentation Add to `Cargo.toml`: ```toml [dependencies] imagequant = "4.0" ``` [See docs.rs for the library API documentation](https://docs.rs/imagequant). ## C documentation ### Building for C 1. Get Rust 1.70 or later via [rustup](https://rustup.rs) and run `rustup update`. 2. `cd imagequant-sys` The C API is exposed by a separate package called [`imagequant-sys`](https://github.com/ImageOptim/libimagequant/tree/main/imagequant-sys). 3. Run `cargo build --release` This will build `target/release/libimagequant_sys.a` or `target\release\libimagequant_sys.lib` that you can use for static linking. Please don't worry about the size of the `.a` file. It includes a few unused objects. It only adds 500KB when linked. Use Link-Time-Optimization (LTO) option in your compiler, and/or add `-Wl,--as-needed` to linker flags if necessary. You can make the binary a bit smaller by building with `cargo +nightly build --target $TARGET_ARCH --release -Z build-std=std,panic_abort -Z build-std-features=panic_immediate_abort`. The repository includes an Xcode project file that can be used on iOS and macOS. If you want to build a C dynamic library (DLL, so, dylib), then: 1. `cargo install cargo-c` 2. `cd imagequant-sys` 3. `cargo cinstall --destdir=.` This will build `./usr/local/lib/libimagequant.0.0.0.{so,dylib,dll}` ### C API usage 1. Create attributes object and configure the library. 2. Create image object from RGBA pixels or data source. 3. Perform quantization (generate palette). 4. Store remapped image and final palette. 5. Free memory. Please note that libimagequant only handles raw uncompressed arrays of pixels in memory and is completely independent of any file format. /* See imagequant-sys/example.c for the full code! */ #include "libimagequant.h" liq_attr *attr = liq_attr_create(); liq_image *image = liq_image_create_rgba(attr, example_bitmap_rgba, width, height, 0); liq_result *res; liq_image_quantize(image, attr, &res); liq_write_remapped_image(res, image, example_bitmap_8bpp, example_bitmap_size); const liq_palette *pal = liq_get_palette(res); // Save the image and the palette now. for(int i=0; i < pal->count; i++) { example_copy_palette_entry(pal->entries[i]); } // You'll need a PNG library to write to a file. example_write_image(example_bitmap_8bpp); liq_result_destroy(res); liq_image_destroy(image); liq_attr_destroy(attr); Functions returning `liq_error` return `LIQ_OK` (`0`) on success and non-zero on error. It's safe to pass `NULL` to any function accepting `liq_attr`, `liq_image`, `liq_result` (in that case the error code `LIQ_INVALID_POINTER` will be returned). These objects can be reused multiple times. There are 3 ways to create image object for quantization: * `liq_image_create_rgba()` for simple, contiguous RGBA pixel arrays (width×height×4 bytes large bitmap). * `liq_image_create_rgba_rows()` for non-contiguous RGBA pixel arrays (that have padding between rows or reverse order, e.g. BMP). * `liq_image_create_custom()` for RGB, ABGR, YUV and all other formats that can be converted on-the-fly to RGBA (you have to supply the conversion function). Note that "image" here means raw uncompressed pixels. If you have a compressed image file, such as PNG, you must use another library (e.g. libpng or lodepng) to decode it first. You'll find full example code in "example.c" file in the library source directory. ## C Functions ---- liq_attr* liq_attr_create(void); Returns object that will hold initial settings (attributes) for the library. The object should be freed using `liq_attr_destroy()` after it's no longer needed. Returns `NULL` in the unlikely case that the library cannot run on the current machine (e.g. the library has been compiled for SSE-capable x86 CPU and run on VIA C3 CPU). ---- liq_error liq_set_max_colors(liq_attr* attr, int colors); Specifies maximum number of colors to use. The default is 256. Instead of setting a fixed limit it's better to use `liq_set_quality()`. The first argument is attributes object from `liq_attr_create()`. Returns `LIQ_VALUE_OUT_OF_RANGE` if number of colors is outside the range 2-256. ---- int liq_get_max_colors(liq_attr* attr); Returns the value set by `liq_set_max_colors()`. ---- liq_error liq_set_quality(liq_attr* attr, int minimum, int maximum); Quality is in range `0` (worst) to `100` (best) and values are analoguous to JPEG quality (i.e. `80` is usually good enough). Quantization will attempt to use the lowest number of colors needed to achieve `maximum` quality. `maximum` value of `100` is the default and means conversion as good as possible. If it's not possible to convert the image with at least `minimum` quality (i.e. 256 colors is not enough to meet the minimum quality), then `liq_image_quantize()` will fail. The default minimum is `0` (proceeds regardless of quality). Quality measures how well the generated palette fits image given to `liq_image_quantize()`. If a different image is remapped with `liq_write_remapped_image()` then actual quality may be different. Regardless of the quality settings the number of colors won't exceed the maximum (see `liq_set_max_colors()`). The first argument is attributes object from `liq_attr_create()`. Returns `LIQ_VALUE_OUT_OF_RANGE` if target is lower than minimum or any of them is outside the 0-100 range. Returns `LIQ_INVALID_POINTER` if `attr` appears to be invalid. liq_attr *attr = liq_attr_create(); liq_set_quality(attr, 50, 80); // use quality 80 if possible. Give up if quality drops below 50. ---- int liq_get_min_quality(liq_attr* attr); Returns the lower bound set by `liq_set_quality()`. ---- int liq_get_max_quality(liq_attr* attr); Returns the upper bound set by `liq_set_quality()`. ---- liq_image *liq_image_create_rgba(liq_attr *attr, void* pixels, int width, int height, double gamma); Creates an object that represents the image pixels to be used for quantization and remapping. The pixel array must be contiguous run of RGBA pixels (alpha is the last component, 0 = transparent, 255 = opaque). The first argument is attributes object from `liq_attr_create()`. The same `attr` object should be used for the entire process, from creation of images to quantization. The `pixels` array must not be modified or freed until this object is freed with `liq_image_destroy()`. See also `liq_image_set_memory_ownership()`. `width` and `height` are dimensions in pixels. An image 10x10 pixel large will need a 400-byte array. If the `gamma` argument is `0`, then the default of 1/2.2 [gamma](https://en.wikipedia.org/wiki/Gamma_correction) is assumed, which is good for most sRGB images. Otherwise `gamma` must be > 0 and < 1, e.g. `0.45455` (1/2.2) or `0.55555` (1/1.8). Generated palette will use the same gamma unless `liq_set_output_gamma()` is used. If `liq_set_output_gamma` is not used, then it only affects whether brighter or darker areas of the image will get more palette colors allocated. Returns `NULL` on failure, e.g. if `pixels` is `NULL` or `width`/`height` is <= 0. ---- liq_image *liq_image_create_rgba_rows(liq_attr *attr, void* rows[], int width, int height, double gamma); Same as `liq_image_create_rgba()`, but takes an array of pointers to rows of pixels. This allows defining images with reversed rows (like in BMP), "stride" different than width or using only fragment of a larger bitmap, etc. The `rows` array must have at least `height` elements, and each row must be at least `width` RGBA pixels wide. unsigned char *bitmap = …; void *rows = malloc(height * sizeof(void*)); int bytes_per_row = width * 4 + padding; // stride for(int i=0; i < height; i++) { rows[i] = bitmap + i * bytes_per_row; } liq_image *img = liq_image_create_rgba_rows(attr, rows, width, height, 0); // … liq_image_destroy(img); free(rows); The row pointers and pixels must not be modified or freed until this object is freed with `liq_image_destroy()` (you can change that with `liq_image_set_memory_ownership()`). See also `liq_image_create_rgba()` and `liq_image_create_custom()`. ---- liq_error liq_image_quantize(liq_image *const input_image, liq_attr *const attr, liq_result **out_result); Performs quantization (palette generation) based on settings in `attr` (from `liq_attr_create()`) and pixels of the image. Returns `LIQ_OK` if quantization succeeds and sets `liq_result` pointer in `out_result`. The last argument is used for receiving the `result` object: liq_result *result; if (LIQ_OK == liq_image_quantize(img, attr, &result)) { // Note &result // result pointer is valid here } Returns `LIQ_QUALITY_TOO_LOW` if quantization fails due to limit set in `liq_set_quality()`. See `liq_write_remapped_image()`. If you want to generate one palette for multiple images at once, see `liq_histogram_create()`. ---- liq_error liq_set_dithering_level(liq_result *res, float dither_level); Enables/disables dithering in `liq_write_remapped_image()`. Dithering level must be between `0` and `1` (inclusive). Dithering level `0` enables fast non-dithered remapping. Otherwise a variation of Floyd-Steinberg error diffusion is used. Precision of the dithering algorithm depends on the speed setting, see `liq_set_speed()`. Returns `LIQ_VALUE_OUT_OF_RANGE` if the dithering level is outside the 0-1 range. ---- liq_error liq_write_remapped_image(liq_result *result, liq_image *input_image, void *buffer, size_t buffer_size); Remaps the image to palette and writes its pixels to the given buffer, 1 pixel per byte. The buffer must be large enough to fit the entire image, i.e. width×height bytes large. For safety, pass the size of the buffer as `buffer_size`. For best performance call `liq_get_palette()` *after* this function, as palette is improved during remapping (except when `liq_histogram_quantize()` is used). Returns `LIQ_BUFFER_TOO_SMALL` if given size of the buffer is not enough to fit the entire image. int buffer_size = width*height; char *buffer = malloc(buffer_size); if (LIQ_OK == liq_write_remapped_image(result, input_image, buffer, buffer_size)) { liq_palette *pal = liq_get_palette(result); // save image } See `liq_get_palette()`. The buffer is assumed to be contiguous, with rows ordered from top to bottom, and no gaps between rows. If you need to write rows with padding or upside-down order, then use `liq_write_remapped_image_rows()`. Please note that it only writes raw uncompressed pixels to memory. It does not perform any PNG compression. If you'd like to create a PNG file then you need to pass the raw pixel data to another library, e.g. libpng or lodepng. See `rwpng.c` in `pngquant` project for an example how to do that. ---- const liq_palette *liq_get_palette(liq_result *result); Returns pointer to palette optimized for image that has been quantized or remapped (final refinements are applied to the palette during remapping). It's valid to call this method before remapping, if you don't plan to remap any images or want to use same palette for multiple images. `liq_palette->count` contains number of colors (up to 256), `liq_palette->entries[n]` contains RGBA value for nth palette color. The palette is **temporary and read-only**. You must copy the palette elsewhere *before* calling `liq_result_destroy()`. Returns `NULL` on error. ---- void liq_attr_destroy(liq_attr *); void liq_image_destroy(liq_image *); void liq_result_destroy(liq_result *); void liq_histogram_destroy(liq_histogram *); Releases memory owned by the given object. Object must not be used any more after it has been freed. Freeing `liq_result` also frees any `liq_palette` obtained from it. ## Advanced Functions ---- liq_error liq_set_speed(liq_attr* attr, int speed); Higher speed levels disable expensive algorithms and reduce quantization precision. The default speed is `4`. Speed `1` gives marginally better quality at significant CPU cost. Speed `10` has usually 5% lower quality, but is 8 times faster than the default. High speeds combined with `liq_set_quality()` will use more colors than necessary and will be less likely to meet minimum required quality.
Features dependent on speed
Noise-sensitive ditheringspeed 1 to 5
Forced posterization8-10 or if image has more than million colors
Quantization error known1-7 or if minimum quality is set
Additional quantization techniques1-6
Returns `LIQ_VALUE_OUT_OF_RANGE` if the speed is outside the 1-10 range. ---- int liq_get_speed(liq_attr* attr); Returns the value set by `liq_set_speed()`. ---- liq_error liq_set_min_opacity(liq_attr* attr, int min); This was a workaround for Internet Explorer 6, but because this browser is not used any more, this option has been deprecated and removed. ---- int liq_get_min_opacity(liq_attr* attr); This function has been deprecated. ---- liq_set_min_posterization(liq_attr* attr, int bits); Ignores given number of least significant bits in all channels, posterizing image to `2^bits` levels. `0` gives full quality. Use `2` for VGA or 16-bit RGB565 displays, `4` if image is going to be output on a RGB444/RGBA4444 display (e.g. low-quality textures on Android). Returns `LIQ_VALUE_OUT_OF_RANGE` if the value is outside the 0-4 range. ---- int liq_get_min_posterization(liq_attr* attr); Returns the value set by `liq_set_min_posterization()`. ---- liq_set_last_index_transparent(liq_attr* attr, int is_last); `0` (default) makes alpha colors sorted before opaque colors. Non-`0` mixes colors together except completely transparent color, which is moved to the end of the palette. This is a workaround for programs that blindly assume the last palette entry is transparent. ---- liq_image *liq_image_create_custom(liq_attr *attr, liq_image_get_rgba_row_callback *row_callback, void *user_info, int width, int height, double gamma);

void image_get_rgba_row_callback(liq_color row_out[], int row_index, int width, void *user_info) { for(int column_index=0; column_index < width; column_index++) { row_out[column_index] = /* generate pixel at (row_index, column_index) */; } } Creates image object that will use callback to read image data. This allows on-the-fly conversion of images that are not in the RGBA color space. `user_info` value will be passed to the callback. It may be useful for storing pointer to program's internal representation of the image. The callback must read/generate `row_index`-th row and write its RGBA pixels to the `row_out` array. Row `width` is given for convenience and will always equal to image width. The callback will be called multiple times for each row. Quantization and remapping require at least two full passes over image data, so caching of callback's work makes no sense — in such case it's better to convert entire image and use `liq_image_create_rgba()` instead. To use RGB image: void rgb_to_rgba_callback(liq_color row_out[], int row_index, int width, void *user_info) { unsigned char *rgb_row = ((unsigned char *)user_info) + 3*width*row_index; for(int i=0; i < width; i++) { row_out[i].r = rgb_row[i*3]; row_out[i].g = rgb_row[i*3+1]; row_out[i].b = rgb_row[i*3+2]; row_out[i].a = 255; } } liq_image *img = liq_image_create_custom(attr, rgb_to_rgba_callback, rgb_bitmap, width, height, 0); The library doesn't support RGB bitmaps "natively", because supporting only single format allows compiler to inline more code, 4-byte pixel alignment is faster, and SSE instructions operate on 4 values at once, so alpha support is almost free. ---- liq_error liq_image_set_memory_ownership(liq_image *image, int ownership_flags); Passes ownership of image pixel data and/or its rows array to the `liq_image` object, so you don't have to free it yourself. Memory owned by the object will be freed at its discretion with `free` function specified in `liq_attr_create_with_allocator()` (by default it's stdlib's `free()`). * `LIQ_OWN_PIXELS` makes pixel array owned by the object. The pixels will be freed automatically at any point when it's no longer needed. If you set this flag you must **not** free the pixel array yourself. If the image has been created with `liq_image_create_rgba_rows()` then the starting address of the array of pixels is assumed to be the lowest address of any row. * `LIQ_OWN_ROWS` makes array of row pointers (but not the pixels pointed by these rows) owned by the object. Rows will be freed when object is deallocated. If you set this flag you must **not** free the rows array yourself. This flag is valid only if the object has been created with `liq_image_create_rgba_rows()`. These flags can be combined with binary *or*, i.e. `LIQ_OWN_PIXELS | LIQ_OWN_ROWS`. This function must not be used if the image has been created with `liq_image_create_custom()`. Returns `LIQ_VALUE_OUT_OF_RANGE` if invalid flags are specified or the image object only takes pixels from a callback. ---- liq_error liq_image_set_background(liq_image *image, liq_image *background_image); Analyze and remap this image with assumption that it will be always presented exactly on top of this background. When this image is remapped to a palette with a fully transparent color (use `liq_image_add_fixed_color()` to ensure this) pixels that are better represented by the background than the palette will be made transparent. This function can be used to improve quality of animated GIFs by setting previous animation frame as the background. This function takes full ownership of the background image, so you should **not** free the background object. It will be freed automatically together with the foreground image. Returns `LIQ_BUFFER_TOO_SMALL` if the background image has a different size than the foreground. ---- liq_error liq_image_set_importance_map(liq_image *image, unsigned char map[], size_t buffer_size, liq_ownership ownership); Impotance map controls which areas of the image get more palette colors. Pixels corresponding to 0 values in the map are completely ignored. The higher the value the more weight is placed on the given pixel, giving it higher chance of influencing the final palette. The map is one byte per pixel and must have the same size as the image (width×height bytes). `buffer_size` argument is used to double-check that. If the `ownership` is `LIQ_COPY_PIXELS` then the `map` content be copied immediately (it's up to you to ensure the `map` memory is freed). If the `ownership` is `LIQ_OWN_PIXELS` then the `map` memory will be owned by the image and will be freed automatically when the image is freed. If a custom allocator has been set using `liq_attr_create_with_allocator()`, the `map` must be allocated using the same allocator. This option is deprecated. Use the Rust API or `LIQ_COPY_PIXELS` instead. Returns `LIQ_INVALID_POINTER` if any pointer is `NULL`, `LIQ_BUFFER_TOO_SMALL` if the `buffer_size` does not match the image size, and `LIQ_UNSUPPORTED` if `ownership` isn't a valid value. ---- liq_error liq_write_remapped_image_rows(liq_result *result, liq_image *input_image, unsigned char **row_pointers); Similar to `liq_write_remapped_image()`. Writes remapped image, at 1 byte per pixel, to each row pointed by `row_pointers` array. The array must have at least as many elements as height of the image, and each row must have at least as many bytes as width of the image. Rows must not overlap. For best performance call `liq_get_palette()` *after* this function, as remapping may change the palette (except when `liq_histogram_quantize()` is used). Returns `LIQ_INVALID_POINTER` if `result` or `input_image` is `NULL`. ---- double liq_get_quantization_error(liq_result *result); Returns mean square error of quantization (square of difference between pixel values in the source image and its remapped version). Alpha channel, gamma correction and approximate importance of pixels is taken into account, so the result isn't exactly the mean square error of all channels. For most images MSE 1-5 is excellent. 7-10 is OK. 20-30 will have noticeable errors. 100 is awful. This function may return `-1` if the value is not available (this happens when a high speed has been requested, the image hasn't been remapped yet, and quality limit hasn't been set, see `liq_set_speed()` and `liq_set_quality()`). The value is not updated when multiple images are remapped, it applies only to the image used in `liq_image_quantize()` or the first image that has been remapped. See `liq_get_remapping_error()`. ---- double liq_get_remapping_error(liq_result *result); Returns mean square error of last remapping done (square of difference between pixel values in the remapped image and its remapped version). Alpha channel and gamma correction are taken into account, so the result isn't exactly the mean square error of all channels. This function may return `-1` if the value is not available (this happens when a high speed has been requested or the image hasn't been remapped yet). ---- double liq_get_quantization_quality(liq_result *result); Analoguous to `liq_get_quantization_error()`, but returns quantization error as quality value in the same 0-100 range that is used by `liq_set_quality()`. It may return `-1` if the value is not available (see note in `liq_get_quantization_error()`). This function can be used to add upper limit to quality options presented to the user, e.g. liq_attr *attr = liq_attr_create(); liq_image *img = liq_image_create_rgba(…); liq_result *res; liq_image_quantize(img, attr, &res); int max_attainable_quality = liq_get_quantization_quality(res); printf("Please select quality between 0 and %d: ", max_attainable_quality); int user_selected_quality = prompt(); if (user_selected_quality < max_attainable_quality) { liq_set_quality(user_selected_quality, 0); liq_result_destroy(res); liq_image_quantize(img, attr, &res); } liq_write_remapped_image(…); ---- double liq_get_remapping_quality(liq_result *result); Analoguous to `liq_get_remapping_error()`, but returns quantization error as quality value in the same 0-100 range that is used by `liq_set_quality()`. ---- void liq_set_log_callback(liq_attr*, liq_log_callback_function*, void *user_info);

void log_callback_function(const liq_attr*, const char *message, void *user_info) {} ---- void liq_set_log_flush_callback(liq_attr*, liq_log_flush_callback_function*, void *user_info);

void log_flush_callback_function(const liq_attr*, void *user_info) {} Sets up callback function to be called when the library reports status or errors. The callback must not call any library functions. `user_info` value will be passed through to the callback. It can be `NULL`. `NULL` callback clears the current callback. In the log callback the `message` is a zero-terminated string containing informative message to output. It is valid only until the callback returns, so you must copy it. `liq_set_log_flush_callback()` sets up callback function that will be called after the last log callback, which can be used to flush buffers and free resources used by the log callback. ---- void liq_set_progress_callback(liq_attr*, liq_progress_callback_function*, void *user_info); void liq_result_set_progress_callback(liq_result*, liq_progress_callback_function*, void *user_info);

int progress_callback_function(const liq_attr*, float progress_percent, void *user_info) {} Sets up callback function to be called while the library is processing images. The callback may abort processing by returning `0`. Setting callback to `NULL` clears the current callback. `liq_set_progress_callback` is for quantization progress, and `liq_result_set_progress_callback` is for remapping progress (currently only dithered remapping reports progress). `user_info` value will be passed through to the callback. It can be `NULL`. The callback must not call any library functions. `progress_percent` is a value between 0 and 100 that estimates how much of the current task has been done. The callback should return `1` to continue the operation, and `0` to abort current operation. ---- liq_attr* liq_attr_create_with_allocator(void* (*malloc)(size_t), void (*free)(void*)); This function is deprecated. Same as `liq_attr_create`, but specifies `free` to use for `liq_image_set_memory_ownership`. The `malloc` argument is not used. The library will use Rust's [global allocator](https://doc.rust-lang.org/std/alloc/index.html). ---- liq_attr* liq_attr_copy(liq_attr *orig); Creates an independent copy of `liq_attr`. The copy should also be freed using `liq_attr_destroy()`. --- liq_error liq_set_output_gamma(liq_result* res, double gamma); Sets gamma correction for generated palette and remapped image. Must be > 0 and < 1, e.g. `0.45455` for gamma 1/2.2 in PNG images. By default output gamma is same as gamma of the input image. ---- int liq_image_get_width(const liq_image *img); int liq_image_get_height(const liq_image *img); double liq_get_output_gamma(const liq_result *result); Getters for `width`, `height` and `gamma` of the input image. If the input is invalid, these all return -1. --- liq_error liq_image_add_fixed_color(liq_image* img, liq_color color); liq_error liq_histogram_add_fixed_color(liq_histogram* hist, liq_color color, double gamma); Reserves a color in the output palette created from this image. It behaves as if the given color was used in the image and was very important. RGB values of `liq_color` are assumed to have the same gamma as the image. For the histogram function, the `gamma` can be `0` (see `liq_image_create_rgba()`). It must be called before the image is quantized. Returns error if more than 256 colors are added. If image is quantized to fewer colors than the number of fixed colors added, then excess fixed colors will be ignored. For histograms see also a more flexible `liq_histogram_add_colors()`. --- int liq_version(); Returns version of the library as an integer. Same as `LIQ_VERSION`. Human-readable version is defined as `LIQ_VERSION_STRING`. ## Multiple images with the same palette It's possible to efficiently generate a single palette that is optimal for multiple images, e.g. for an APNG animation. This is done by collecting statistics of images in a `liq_histogram` object. liq_attr *attr = liq_attr_create(); liq_histogram *hist = liq_histogram_create(attr); liq_image *image1 = liq_image_create_rgba(attr, example_bitmap_rgba1, width, height, 0); liq_histogram_add_image(hist, attr, image1); liq_image *image2 = liq_image_create_rgba(attr, example_bitmap_rgba2, width, height, 0); liq_histogram_add_image(hist, attr, image2); liq_result *result; liq_error err = liq_histogram_quantize(attr, hist, &result); if (LIQ_OK == err) { // result will contain shared palette best for both image1 and image2 } --- liq_histogram *liq_histogram_create(liq_attr *attr); Creates histogram object that will be used to collect color statistics from multiple images. It must be freed using `liq_histogram_destroy()`. All options should be set on `attr` before the histogram object is created. Options changed later may not have effect. --- liq_error liq_histogram_add_image(liq_histogram *hist, liq_attr *attr, liq_image* image); "Learns" colors from the image, which will be later used to generate the palette. After the image is added to the histogram it may be freed to save memory (but it's more efficient to keep the image object if it's going to be used for remapping). Fixed colors added to the image are also added to the histogram. If total number of fixed colors exceeds 256, this function will fail with `LIQ_BUFFER_TOO_SMALL`. --- liq_error liq_histogram_add_colors(liq_histogram *hist, liq_attr *attr, liq_histogram_entry entries[], int num_entries, double gamma); Alternative to `liq_histogram_add_image()`. Intead of counting colors in an image, it directly takes an array of colors and their counts (see `liq_histogram_entry` in `libimagequant.h`). This function is only useful if you already have a histogram of the image from another source. For description of gamma, see `liq_image_create_rgba()`. --- liq_error liq_histogram_quantize(liq_histogram *const hist, liq_attr *const attr, liq_result **out_result); Generates palette from the histogram. On success returns `LIQ_OK` and writes `liq_result*` pointer to `out_result`. Use it as follows: liq_result *result; liq_error err = liq_histogram_quantize(attr, hist, &result); if (LIQ_OK == err) { // Use result here to remap and get palette } Returns `LIQ_QUALITY_TOO_LOW` if the palette is worse than limit set in `liq_set_quality()`. One histogram object can be quantized only once. Palette generated using this function won't be improved during remapping. If you're generating palette for only one image, it's better to use `liq_image_quantize()`. ## Multithreading * Different threads can perform unrelated quantizations/remappings at the same time (e.g. each thread working on a different image). * The same `liq_attr`, `liq_result`, etc. can be accessed from different threads, but not at the same time (e.g. you can create `liq_attr` in one thread and free it in another). * By default, this library uses threads internally. You can set `RAYON_NUM_THREADS` environmental variable to control the number of threads used. You can disable threads completely by compiling with `--no-default-features`. ## Working with GIF The library can generate palettes for GIF images. To ensure correct transparency is used you need to preprocess the image yourself and replace alpha values other than 0 or 255 with one of these. For animated GIFs see `liq_image_set_background()` which remaps images for GIF's "keep" frame disposal method. See [gif.ski](https://gif.ski). ## Cross-compilation You can compile the library for other platforms via `cargo build --target=…`. See `rustup target list` for the list of platforms. When compiling for WASM, you need to disable default features of this library (compile with `--no-default-features` flag). Otherwise it will use mult-threading, which requires [special handling in WASM](https://github.com/GoogleChromeLabs/wasm-bindgen-rayon). If you're cross-compiling a dynamic library (so/dylib/DLL), you may need to [configure a linker](https://doc.rust-lang.org/cargo/reference/config.html#target) for Cargo. For building for Android see [this tutorial](https://mozilla.github.io/firefox-browser-architecture/experiments/2017-09-21-rust-on-android.html) and [cargo-ndk](https://lib.rs/crates/cargo-ndk). libimagequant-4.4.0/imagequant-sys/build.rs000066400000000000000000000001361503274717000207630ustar00rootroot00000000000000fn main() { println!("cargo:include={}", std::env::var("CARGO_MANIFEST_DIR").unwrap()); } libimagequant-4.4.0/imagequant-sys/c_test/000077500000000000000000000000001503274717000205775ustar00rootroot00000000000000libimagequant-4.4.0/imagequant-sys/c_test/Cargo.toml000066400000000000000000000003671503274717000225350ustar00rootroot00000000000000[package] name = "c_test" version = "0.1.0" edition = "2021" publish = false [lib] doctest = false [package.metadata.release] release = false [dependencies] imagequant-sys = { version = "4.0.3", path = ".." } [build-dependencies] cc = "1.1.7" libimagequant-4.4.0/imagequant-sys/c_test/build.rs000066400000000000000000000001711503274717000222430ustar00rootroot00000000000000fn main() { cc::Build::new() .include("..") .file("test.c") .compile("imagequanttestbin"); } libimagequant-4.4.0/imagequant-sys/c_test/src/000077500000000000000000000000001503274717000213665ustar00rootroot00000000000000libimagequant-4.4.0/imagequant-sys/c_test/src/lib.rs000066400000000000000000000002441503274717000225020ustar00rootroot00000000000000#[cfg(test)] extern crate imagequant_sys; #[cfg(test)] extern "C" { fn run_liq_tests(); } #[test] fn c_test() { unsafe { run_liq_tests(); } } libimagequant-4.4.0/imagequant-sys/c_test/test.c000066400000000000000000000111021503274717000217150ustar00rootroot00000000000000#undef NDEBUG #include #include "libimagequant.h" #include #include static char magic[] = "magic"; static void test_log_callback_function(const liq_attr *at, const char *message, void* user_info) { assert(at); assert(user_info == magic); assert(message); assert(strlen(message)); } static int test_abort_callback(float progress_percent, void* user_info) { assert(progress_percent >= 0.0 && progress_percent <= 100.0); assert(user_info == magic); return 0; } static int progress_called = 0; static int test_continue_callback(float progress_percent, void* user_info) { assert(progress_percent >= 0.0 && progress_percent <= 100.0); assert(user_info == magic); progress_called++; return 1; } static void test_abort() { liq_attr *attr = liq_attr_create(); unsigned char dummy[4] = {0}; liq_image *img = liq_image_create_rgba(attr, dummy, 1, 1, 0); liq_attr_set_progress_callback(attr, test_abort_callback, magic); liq_result *res = liq_quantize_image(attr, img); assert(!res); liq_attr_destroy(attr); } static void test_zero_histogram() { liq_attr *attr = liq_attr_create(); liq_histogram *hist = liq_histogram_create(attr); assert(hist); liq_result *res; liq_error err = liq_histogram_quantize(hist, attr, &res); assert(!res); assert(err); liq_attr_destroy(attr); liq_histogram_destroy(hist); } static void test_histogram() { liq_attr *attr = liq_attr_create(); liq_histogram *hist = liq_histogram_create(attr); assert(hist); const unsigned char dummy1[4] = {255,0,255,255}; liq_image *const img1 = liq_image_create_rgba(attr, dummy1, 1, 1, 0); assert(img1); const liq_error err1 = liq_histogram_add_image(hist, attr, img1); assert(LIQ_OK == err1); const unsigned char dummy2[4] = {0,0,0,0}; liq_image *const img2 = liq_image_create_rgba(attr, dummy2, 1, 1, 0); assert(img2); liq_image_add_fixed_color(img2, (liq_color){255,255,255,255}); const liq_error err2 = liq_histogram_add_image(hist, attr, img2); assert(LIQ_OK == err2); liq_image_destroy(img1); liq_image_destroy(img2); liq_result *res; liq_error err = liq_histogram_quantize(hist, attr, &res); assert(LIQ_OK == err); assert(res); liq_attr_destroy(attr); liq_histogram_destroy(hist); const liq_palette *pal = liq_get_palette(res); assert(pal); assert(pal->count == 3); liq_result_destroy(res); } static void test_fixed_colors() { liq_attr *attr = liq_attr_create(); liq_attr_set_progress_callback(attr, test_continue_callback, magic); liq_set_log_callback(attr, test_log_callback_function, magic); unsigned char dummy[4] = {0}; liq_image *img = liq_image_create_rgba(attr, dummy, 1, 1, 0); assert(img); liq_image_add_fixed_color(img, (liq_color){0,0,0,0}); liq_result *res = liq_quantize_image(attr, img); assert(res); assert(progress_called); const liq_palette *pal = liq_get_palette(res); assert(pal); assert(pal->count == 1); liq_result_destroy(res); liq_image_destroy(img); liq_attr_destroy(attr); } static void test_fixed_colors_order() { liq_attr *attr = liq_attr_create(); unsigned char dummy[4] = {0}; liq_image *img = liq_image_create_rgba(attr, dummy, 1, 1, 0); assert(img); liq_color colors[17] = { {0,0,0,0}, {1,1,1,1}, {2,2,2,2}, {3,3,3,3}, {4,4,4,4}, {5,4,4,4}, {6,4,4,4}, {6,7,4,4}, {6,7,8,4}, {6,7,8,9}, {10,7,8,9}, {10,11,8,9}, {10,11,12,9}, {10,11,12,13}, {14,11,12,13}, {14,15,12,13}, {253,254,255,254}, }; for(int i=0; i < 17; i++) { liq_image_add_fixed_color(img, colors[i]); } liq_result *res = liq_quantize_image(attr, img); assert(res); const liq_palette *pal = liq_get_palette(res); assert(pal); assert(pal->count == 17); for(int i=0; i < 17; i++) { assert(pal->entries[i].r == colors[i].r); assert(pal->entries[i].g == colors[i].g); assert(pal->entries[i].b == colors[i].b); assert(pal->entries[i].a == colors[i].a); } liq_set_dithering_level(res, 1.0); char buf[1]; assert(LIQ_OK == liq_write_remapped_image(res, img, buf, 1)); liq_result_set_progress_callback(res, test_abort_callback, magic); assert(LIQ_ABORTED == liq_write_remapped_image(res, img, buf, 1)); liq_result_destroy(res); liq_image_destroy(img); liq_attr_destroy(attr); } void run_liq_tests() { test_fixed_colors(); test_fixed_colors_order(); test_abort(); test_histogram(); test_zero_histogram(); } libimagequant-4.4.0/imagequant-sys/example.c000066400000000000000000000076411503274717000211250ustar00rootroot00000000000000/** This is an example how to write your own simple pngquant using libimagequant. libimagequant works with any PNG library. This example uses lodepng, because it's easier to use than libpng. 1. Get lodepng.c (download lodepng.cpp and rename it) and lodepng.h from https://lodev.org/lodepng/ and put them in this directry 2. Compile libimagequant (see README.md) 3. Compile and run the example: gcc -O3 example.c libimagequant.a -o example ./example truecolor_file.png This example code can be freely copied under CC0 (public domain) license. */ #include "lodepng.h" // Get it from https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.h #include "lodepng.c" // Get it from https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.cpp and rename #include #include #include "libimagequant.h" int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Please specify a path to a PNG file\n"); return EXIT_FAILURE; } const char *input_png_file_path = argv[1]; // Load PNG file and decode it as raw RGBA pixels // This uses lodepng library for PNG reading (not part of libimagequant) unsigned int width, height; unsigned char *raw_rgba_pixels; unsigned int status = lodepng_decode32_file(&raw_rgba_pixels, &width, &height, input_png_file_path); if (status) { fprintf(stderr, "Can't load %s: %s\n", input_png_file_path, lodepng_error_text(status)); return EXIT_FAILURE; } // Use libimagequant to make a palette for the RGBA pixels liq_attr *handle = liq_attr_create(); liq_image *input_image = liq_image_create_rgba(handle, raw_rgba_pixels, width, height, 0); // You could set more options here, like liq_set_quality liq_result *quantization_result; if (liq_image_quantize(input_image, handle, &quantization_result) != LIQ_OK) { fprintf(stderr, "Quantization failed\n"); return EXIT_FAILURE; } // Use libimagequant to make new image pixels from the palette size_t pixels_size = width * height; unsigned char *raw_8bit_pixels = malloc(pixels_size); liq_set_dithering_level(quantization_result, 1.0); liq_write_remapped_image(quantization_result, input_image, raw_8bit_pixels, pixels_size); const liq_palette *palette = liq_get_palette(quantization_result); // Save converted pixels as a PNG file // This uses lodepng library for PNG writing (not part of libimagequant) LodePNGState state; lodepng_state_init(&state); state.info_raw.colortype = LCT_PALETTE; state.info_raw.bitdepth = 8; state.info_png.color.colortype = LCT_PALETTE; state.info_png.color.bitdepth = 8; for(int i=0; i < palette->count; i++) { lodepng_palette_add(&state.info_png.color, palette->entries[i].r, palette->entries[i].g, palette->entries[i].b, palette->entries[i].a); lodepng_palette_add(&state.info_raw, palette->entries[i].r, palette->entries[i].g, palette->entries[i].b, palette->entries[i].a); } unsigned char *output_file_data; size_t output_file_size; unsigned int out_status = lodepng_encode(&output_file_data, &output_file_size, raw_8bit_pixels, width, height, &state); if (out_status) { fprintf(stderr, "Can't encode image: %s\n", lodepng_error_text(out_status)); return EXIT_FAILURE; } const char *output_png_file_path = "quantized_example.png"; FILE *fp = fopen(output_png_file_path, "wb"); if (!fp) { fprintf(stderr, "Unable to write to %s\n", output_png_file_path); return EXIT_FAILURE; } fwrite(output_file_data, 1, output_file_size, fp); fclose(fp); printf("Written %s\n", output_png_file_path); // Done. Free memory. liq_result_destroy(quantization_result); // Must be freed only after you're done using the palette liq_image_destroy(input_image); liq_attr_destroy(handle); free(raw_8bit_pixels); lodepng_state_cleanup(&state); } libimagequant-4.4.0/imagequant-sys/imagequant.pc.in000066400000000000000000000004701503274717000224030ustar00rootroot00000000000000prefix=@PREFIX@ includedir=${prefix}/include libdir=${prefix}/lib Name: imagequant Description: Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images. URL: https://pngquant.org/lib/ Version: @VERSION@ Libs: -L${libdir} -limagequant Cflags: -I${includedir} libimagequant-4.4.0/imagequant-sys/imagequant.xcodeproj/000077500000000000000000000000001503274717000234455ustar00rootroot00000000000000libimagequant-4.4.0/imagequant-sys/imagequant.xcodeproj/project.pbxproj000066400000000000000000000323211503274717000265220ustar00rootroot00000000000000// !$*UTF8*$! { /* generated with cargo-xcode 1.4.3 */ archiveVersion = 1; classes = { }; objectVersion = 53; objects = { /* Begin PBXBuildFile section */ CA60077B6400A6A410610A27 /* Cargo.toml in Sources */ = { isa = PBXBuildFile; fileRef = CA6091AFFEBB3EF4668187A5 /* Cargo.toml */; settings = { COMPILER_FLAGS = "--lib"; /* == OTHER_INPUT_FILE_FLAGS */ }; }; /* End PBXBuildFile section */ /* Begin PBXBuildRule section */ CA6091AFFEBBAC6C1400ACA8 /* PBXBuildRule */ = { isa = PBXBuildRule; compilerSpec = com.apple.compilers.proxy.script; dependencyFile = "$(DERIVED_FILE_DIR)/$(CARGO_XCODE_TARGET_ARCH)-$(EXECUTABLE_NAME).d"; filePatterns = "*/Cargo.toml"; /* must contain asterisk */ fileType = pattern.proxy; inputFiles = (); isEditable = 0; name = "Cargo project build"; outputFiles = ( "$(OBJECT_FILE_DIR)/$(CARGO_XCODE_TARGET_ARCH)-$(EXECUTABLE_NAME)", ); script = "# generated with cargo-xcode 1.4.3\n\nset -eu; export PATH=$PATH:~/.cargo/bin:/usr/local/bin;\nif [ \"${IS_MACCATALYST-NO}\" = YES ]; then\n CARGO_XCODE_TARGET_TRIPLE=\"${CARGO_XCODE_TARGET_ARCH}-apple-ios-macabi\"\nelse\n CARGO_XCODE_TARGET_TRIPLE=\"${CARGO_XCODE_TARGET_ARCH}-apple-${CARGO_XCODE_TARGET_OS}\"\nfi\nif [ \"$CARGO_XCODE_TARGET_OS\" != \"darwin\" ]; then\n PATH=\"${PATH/\\/Contents\\/Developer\\/Toolchains\\/XcodeDefault.xctoolchain\\/usr\\/bin:/xcode-provided-ld-cant-link-lSystem-for-the-host-build-script:}\"\nfi\nPATH=\"$PATH:/opt/homebrew/bin\" # Rust projects often depend on extra tools like nasm, which Xcode lacks\nif [ \"$CARGO_XCODE_BUILD_MODE\" == release ]; then\n OTHER_INPUT_FILE_FLAGS=\"${OTHER_INPUT_FILE_FLAGS} --release\"\nfi\nif command -v rustup &> /dev/null; then\n if ! rustup target list --installed | egrep -q \"${CARGO_XCODE_TARGET_TRIPLE}\"; then\n echo \"warning: this build requires rustup toolchain for $CARGO_XCODE_TARGET_TRIPLE, but it isn\'t installed\"\n rustup target add \"${CARGO_XCODE_TARGET_TRIPLE}\" || echo >&2 \"warning: can\'t install $CARGO_XCODE_TARGET_TRIPLE\"\n fi\nfi\nif [ \"$ACTION\" = clean ]; then\n ( set -x; cargo clean --manifest-path=\"$SCRIPT_INPUT_FILE\" ${OTHER_INPUT_FILE_FLAGS} --target=\"${CARGO_XCODE_TARGET_TRIPLE}\"; );\nelse\n ( set -x; cargo build --manifest-path=\"$SCRIPT_INPUT_FILE\" --features=\"${CARGO_XCODE_FEATURES:-}\" ${OTHER_INPUT_FILE_FLAGS} --target=\"${CARGO_XCODE_TARGET_TRIPLE}\"; );\nfi\n# it\'s too hard to explain Cargo\'s actual exe path to Xcode build graph, so hardlink to a known-good path instead\nBUILT_SRC=\"${CARGO_TARGET_DIR}/${CARGO_XCODE_TARGET_TRIPLE}/${CARGO_XCODE_BUILD_MODE}/${CARGO_XCODE_CARGO_FILE_NAME}\"\nln -f -- \"$BUILT_SRC\" \"$SCRIPT_OUTPUT_FILE_0\"\n\n# xcode generates dep file, but for its own path, so append our rename to it\nDEP_FILE_SRC=\"${CARGO_TARGET_DIR}/${CARGO_XCODE_TARGET_TRIPLE}/${CARGO_XCODE_BUILD_MODE}/${CARGO_XCODE_CARGO_DEP_FILE_NAME}\"\nif [ -f \"$DEP_FILE_SRC\" ]; then\n DEP_FILE_DST=\"${DERIVED_FILE_DIR}/${CARGO_XCODE_TARGET_ARCH}-${EXECUTABLE_NAME}.d\"\n cp -f \"$DEP_FILE_SRC\" \"$DEP_FILE_DST\"\n echo >> \"$DEP_FILE_DST\" \"$SCRIPT_OUTPUT_FILE_0: $BUILT_SRC\"\nfi\n\n# lipo script needs to know all the platform-specific files that have been built\n# archs is in the file name, so that paths don\'t stay around after archs change\n# must match input for LipoScript\nFILE_LIST=\"${DERIVED_FILE_DIR}/${ARCHS}-${EXECUTABLE_NAME}.xcfilelist\"\ntouch \"$FILE_LIST\"\nif ! egrep -q \"$SCRIPT_OUTPUT_FILE_0\" \"$FILE_LIST\" ; then\n echo >> \"$FILE_LIST\" \"$SCRIPT_OUTPUT_FILE_0\"\nfi\n"; }; /* End PBXBuildRule section */ /* Begin PBXFileReference section */ CA60A7F2A4D647C0CE156F07 /* staticlib */ = { isa = PBXFileReference; explicitFileType = "archive.ar"; includeInIndex = 0; name = "libimagequant_sys_static.a"; sourceTree = TARGET_BUILD_DIR; }; CA6091AFFEBB3EF4668187A5 /* Cargo.toml */ = { isa = PBXFileReference; lastKnownFileType = text; fileEncoding = 4; name = "Cargo.toml"; path = "Cargo.toml"; sourceTree = ""; }; /* Rust needs libresolv */ ADDEDBA66A6E1 = { isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libresolv.tbd; path = usr/lib/libresolv.tbd; sourceTree = SDKROOT; }; /* End PBXFileReference section */ /* Begin PBXGroup section */ CA6091AFFEBB98AF0B5890DB /* Frameworks */ = { isa = PBXGroup; children = ( ADDEDBA66A6E2, ); name = Frameworks; sourceTree = ""; }; ADDEDBA66A6E2 /* Required for static linking */ = { isa = PBXGroup; children = ( ADDEDBA66A6E1 ); name = "Required for static linking"; sourceTree = ""; }; CA6091AFFEBB22869D176AE5 /* Products */ = { isa = PBXGroup; children = ( CA60A7F2A4D647C0CE156F07, ); name = Products; sourceTree = ""; }; CA6091AFFEBBD65BC3C892A8 /* Main */ = { isa = PBXGroup; children = ( CA6091AFFEBB3EF4668187A5, CA6091AFFEBB22869D176AE5, CA6091AFFEBB98AF0B5890DB, ); sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ CA60A7F2A4D6A6A410610A27 /* imagequant_sys-staticlib */ = { isa = PBXNativeTarget; buildConfigurationList = CA601449CA94A6A410610A27; buildPhases = ( CA607796DFF0A6A410610A27 /* Sources */, CA6091AFFEBBAF6EBB7F357C /* Universal Binary lipo */, ); buildRules = ( CA6091AFFEBBAC6C1400ACA8 /* PBXBuildRule */, ); dependencies = ( ); name = "imagequant_sys-staticlib"; productName = "libimagequant_sys_static.a"; productReference = CA60A7F2A4D647C0CE156F07; productType = "com.apple.product-type.library.static"; }; /* End PBXNativeTarget section */ CA607796DFF0A6A410610A27 = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( CA60077B6400A6A410610A27 ); runOnlyForDeploymentPostprocessing = 0; }; CA601449CA94A6A410610A27 /* staticlib */ = { isa = XCConfigurationList; buildConfigurations = ( CA60994CA1EBA6A410610A27 /* Release */, CA60FBBF8BCDA6A410610A27 /* Debug */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; CA60994CA1EBA6A410610A27 /* staticlib */ = { isa = XCBuildConfiguration; buildSettings = { PRODUCT_NAME = "imagequant_sys_static"; "CARGO_XCODE_CARGO_FILE_NAME" = "libimagequant_sys.a"; "CARGO_XCODE_CARGO_DEP_FILE_NAME" = "libimagequant_sys.d"; SUPPORTED_PLATFORMS = "macosx iphonesimulator iphoneos appletvsimulator appletvos"; SKIP_INSTALL = YES; INSTALL_GROUP = ""; INSTALL_MODE_FLAG = ""; INSTALL_OWNER = ""; }; name = Release; }; CA60FBBF8BCDA6A410610A27 /* staticlib */ = { isa = XCBuildConfiguration; buildSettings = { PRODUCT_NAME = "imagequant_sys_static"; "CARGO_XCODE_CARGO_FILE_NAME" = "libimagequant_sys.a"; "CARGO_XCODE_CARGO_DEP_FILE_NAME" = "libimagequant_sys.d"; SUPPORTED_PLATFORMS = "macosx iphonesimulator iphoneos appletvsimulator appletvos"; SKIP_INSTALL = YES; INSTALL_GROUP = ""; INSTALL_MODE_FLAG = ""; INSTALL_OWNER = ""; }; name = Debug; }; CA6091AFFEBBAF6EBB7F357C /* LipoScript */ = { name = "Universal Binary lipo"; isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = (); inputFileListPaths = (); inputPaths = ( "$(DERIVED_FILE_DIR)/$(ARCHS)-$(EXECUTABLE_NAME).xcfilelist", ); outputFileListPaths = (); outputPaths = ( "$(TARGET_BUILD_DIR)/$(EXECUTABLE_PATH)" ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "# generated with cargo-xcode 1.4.3\nset -eux; cat \"$DERIVED_FILE_DIR/$ARCHS-$EXECUTABLE_NAME.xcfilelist\" | tr '\\n' '\\0' | xargs -0 lipo -create -output \"$TARGET_BUILD_DIR/$EXECUTABLE_PATH\""; }; CA6091AFFEBB80E02D6C7F57 = { isa = XCConfigurationList; buildConfigurations = ( CA60B3CFE6713CC16B37690B /* Release */, CA60B3CFE671228BE02872F8 /* Debug */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; CA60B3CFE6713CC16B37690B = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; SUPPORTS_MACCATALYST = YES; CARGO_TARGET_DIR = "$(PROJECT_TEMP_DIR)/cargo_target"; /* for cargo */ CARGO_XCODE_FEATURES = ""; /* configure yourself */ "CARGO_XCODE_TARGET_ARCH[arch=arm64*]" = "aarch64"; "CARGO_XCODE_TARGET_ARCH[arch=x86_64*]" = "x86_64"; /* catalyst adds h suffix */ "CARGO_XCODE_TARGET_ARCH[arch=i386]" = "i686"; "CARGO_XCODE_TARGET_OS[sdk=macosx*]" = "darwin"; "CARGO_XCODE_TARGET_OS[sdk=iphonesimulator*]" = "ios-sim"; "CARGO_XCODE_TARGET_OS[sdk=iphonesimulator*][arch=x86_64*]" = "ios"; "CARGO_XCODE_TARGET_OS[sdk=iphoneos*]" = "ios"; "CARGO_XCODE_TARGET_OS[sdk=appletvsimulator*]" = "tvos"; "CARGO_XCODE_TARGET_OS[sdk=appletvos*]" = "tvos"; PRODUCT_NAME = "imagequant-sys"; SDKROOT = macosx; "CARGO_XCODE_BUILD_MODE" = "release"; /* for xcode scripts */ }; name = Release; }; CA60B3CFE671228BE02872F8 = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; SUPPORTS_MACCATALYST = YES; CARGO_TARGET_DIR = "$(PROJECT_TEMP_DIR)/cargo_target"; /* for cargo */ CARGO_XCODE_FEATURES = ""; /* configure yourself */ "CARGO_XCODE_TARGET_ARCH[arch=arm64*]" = "aarch64"; "CARGO_XCODE_TARGET_ARCH[arch=x86_64*]" = "x86_64"; /* catalyst adds h suffix */ "CARGO_XCODE_TARGET_ARCH[arch=i386]" = "i686"; "CARGO_XCODE_TARGET_OS[sdk=macosx*]" = "darwin"; "CARGO_XCODE_TARGET_OS[sdk=iphonesimulator*]" = "ios-sim"; "CARGO_XCODE_TARGET_OS[sdk=iphonesimulator*][arch=x86_64*]" = "ios"; "CARGO_XCODE_TARGET_OS[sdk=iphoneos*]" = "ios"; "CARGO_XCODE_TARGET_OS[sdk=appletvsimulator*]" = "tvos"; "CARGO_XCODE_TARGET_OS[sdk=appletvos*]" = "tvos"; PRODUCT_NAME = "imagequant-sys"; SDKROOT = macosx; "CARGO_XCODE_BUILD_MODE" = "debug"; /* for xcode scripts */ ONLY_ACTIVE_ARCH = YES; }; name = Debug; }; CA6091AFFEBBE04653AD465F = { isa = PBXProject; attributes = { LastUpgradeCheck = 1300; TargetAttributes = { CA60A7F2A4D6A6A410610A27 = { CreatedOnToolsVersion = 9.2; ProvisioningStyle = Automatic; }; }; }; buildConfigurationList = CA6091AFFEBB80E02D6C7F57; compatibilityVersion = "Xcode 11.4"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = CA6091AFFEBBD65BC3C892A8; productRefGroup = CA6091AFFEBB22869D176AE5 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( CA60A7F2A4D6A6A410610A27, ); }; }; rootObject = CA6091AFFEBBE04653AD465F; } libimagequant-4.4.0/imagequant-sys/libimagequant.cs000066400000000000000000000147171503274717000225010ustar00rootroot00000000000000/* This is an example demonstrating use of libimagequant from C#. This example code can be freely copied under CC0 (public domain) license. */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Sequential)] struct liq_color { public byte r, g, b, a; }; [StructLayout(LayoutKind.Sequential)] struct liq_palette { public int count; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public liq_color[] entries; }; enum liq_error { LIQ_OK = 0, LIQ_QUALITY_TOO_LOW = 99, LIQ_VALUE_OUT_OF_RANGE = 100, LIQ_OUT_OF_MEMORY, LIQ_ABORTED, LIQ_BITMAP_NOT_AVAILABLE, LIQ_BUFFER_TOO_SMALL, LIQ_INVALID_POINTER, }; namespace liq { using liq_attr_ptr = IntPtr; using liq_image_ptr = IntPtr; using liq_result_ptr = IntPtr; using size_t = UIntPtr; class Liq { [DllImport(@"imagequant.dll")] public static extern liq_attr_ptr liq_attr_create(); [DllImport(@"imagequant.dll")] public static extern liq_attr_ptr liq_attr_copy(liq_attr_ptr attr); [DllImport(@"imagequant.dll")] public static extern void liq_attr_destroy(liq_attr_ptr attr); [DllImport(@"imagequant.dll")] public static extern liq_error liq_set_max_colors(liq_attr_ptr attr, int colors); [DllImport(@"imagequant.dll")] public static extern int liq_get_max_colors(liq_attr_ptr attr); [DllImport(@"imagequant.dll")] public static extern liq_error liq_set_speed(liq_attr_ptr attr, int speed); [DllImport(@"imagequant.dll")] public static extern int liq_get_speed(liq_attr_ptr attr); [DllImport(@"imagequant.dll")] public static extern liq_error liq_set_min_opacity(liq_attr_ptr attr, int min); [DllImport(@"imagequant.dll")] public static extern int liq_get_min_opacity(liq_attr_ptr attr); [DllImport(@"imagequant.dll")] public static extern liq_error liq_set_min_posterization(liq_attr_ptr attr, int bits); [DllImport(@"imagequant.dll")] public static extern int liq_get_min_posterization(liq_attr_ptr attr); [DllImport(@"imagequant.dll")] public static extern liq_error liq_set_quality(liq_attr_ptr attr, int minimum, int maximum); [DllImport(@"imagequant.dll")] public static extern int liq_get_min_quality(liq_attr_ptr attr); [DllImport(@"imagequant.dll")] public static extern int liq_get_max_quality(liq_attr_ptr attr); [DllImport(@"imagequant.dll")] public static extern void liq_set_last_index_transparent(liq_attr_ptr attr, int is_last); [DllImport(@"imagequant.dll")] public static extern liq_image_ptr liq_image_create_rgba(liq_attr_ptr attr, [In, MarshalAs(UnmanagedType.LPArray)] byte[] bitmap, int width, int height, double gamma); [DllImport(@"imagequant.dll")] public static extern liq_error liq_image_set_memory_ownership(liq_image_ptr image, int ownership_flags); [DllImport(@"imagequant.dll")] public static extern liq_error liq_image_add_fixed_color(liq_image_ptr img, liq_color color); [DllImport(@"imagequant.dll")] public static extern int liq_image_get_width(liq_image_ptr img); [DllImport(@"imagequant.dll")] public static extern int liq_image_get_height(liq_image_ptr img); [DllImport(@"imagequant.dll")] public static extern void liq_image_destroy(liq_image_ptr img); [DllImport(@"imagequant.dll")] public static extern liq_result_ptr liq_quantize_image(liq_attr_ptr attr, liq_image_ptr input_image); [DllImport(@"imagequant.dll")] public static extern liq_error liq_set_dithering_level(liq_result_ptr res, float dither_level); [DllImport(@"imagequant.dll")] public static extern liq_error liq_set_output_gamma(liq_result_ptr res, double gamma); [DllImport(@"imagequant.dll")] public static extern double liq_get_output_gamma(liq_result_ptr res); [DllImport(@"imagequant.dll")] public static extern IntPtr liq_get_palette(liq_result_ptr res); [DllImport(@"imagequant.dll")] public static extern liq_error liq_write_remapped_image(liq_result_ptr res, liq_image_ptr input_image, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] buffer, size_t buffer_size); [DllImport(@"imagequant.dll")] public static extern double liq_get_quantization_error(liq_result_ptr res); [DllImport(@"imagequant.dll")] public static extern int liq_get_quantization_quality(liq_result_ptr res); [DllImport(@"imagequant.dll")] public static extern double liq_get_remapping_error(liq_result_ptr res); [DllImport(@"imagequant.dll")] public static extern int liq_get_remapping_quality(liq_result_ptr res); [DllImport(@"imagequant.dll")] public static extern void liq_result_destroy(liq_result_ptr res); [DllImport(@"imagequant.dll")] public static extern int liq_version(); static void Main(string[] args) { Console.WriteLine("library version: {0}", liq_version()); int width = 3; int height = 1; var attr = liq_attr_create(); if (attr == IntPtr.Zero) throw new Exception("can't create attr"); byte[] bitmap = { // R, G, B, A, R, G, B, A, ... 111, 222, 33, 255, 255, 0, 255, 255, 255, 0, 255, 255, }; var img = liq_image_create_rgba(attr, bitmap, width, height, 0); if (img == IntPtr.Zero) throw new Exception("can't create image"); var res = liq_quantize_image(attr, img); if (res == IntPtr.Zero) throw new Exception("can't quantize image"); var buffer_size = width * height; var remapped = new byte[buffer_size]; var err = liq_write_remapped_image(res, img, remapped, (UIntPtr)buffer_size); if (err != liq_error.LIQ_OK) { throw new Exception("remapping error"); } Console.WriteLine("first pixel is {0}th palette entry", remapped[0]); liq_palette pal = (liq_palette)Marshal.PtrToStructure(liq_get_palette(res), typeof(liq_palette)); Console.WriteLine("palette entries: {0}; red of first entry: {1}", pal.count, pal.entries[0].r); liq_image_destroy(img); liq_result_destroy(res); liq_attr_destroy(attr); } } } libimagequant-4.4.0/imagequant-sys/libimagequant.h000066400000000000000000000157211503274717000223170ustar00rootroot00000000000000/* * https://pngquant.org */ #ifndef LIBIMAGEQUANT_H #define LIBIMAGEQUANT_H #ifdef IMAGEQUANT_EXPORTS #define LIQ_EXPORT __declspec(dllexport) #endif #ifndef LIQ_EXPORT #define LIQ_EXPORT extern #endif #define LIQ_VERSION 40003 #define LIQ_VERSION_STRING "4.0.3" #ifndef LIQ_PRIVATE #if defined(__GNUC__) || defined (__llvm__) #define LIQ_PRIVATE __attribute__((visibility("hidden"))) #define LIQ_NONNULL __attribute__((nonnull)) #define LIQ_USERESULT __attribute__((warn_unused_result)) #else #define LIQ_PRIVATE #define LIQ_NONNULL #define LIQ_USERESULT #endif #endif #ifdef __cplusplus extern "C" { #endif #include typedef struct liq_attr liq_attr; typedef struct liq_image liq_image; typedef struct liq_result liq_result; typedef struct liq_histogram liq_histogram; typedef struct liq_color { unsigned char r, g, b, a; } liq_color; typedef struct liq_palette { unsigned int count; liq_color entries[256]; } liq_palette; typedef enum liq_error { LIQ_OK = 0, LIQ_QUALITY_TOO_LOW = 99, LIQ_VALUE_OUT_OF_RANGE = 100, LIQ_OUT_OF_MEMORY, LIQ_ABORTED, LIQ_BITMAP_NOT_AVAILABLE, LIQ_BUFFER_TOO_SMALL, LIQ_INVALID_POINTER, LIQ_UNSUPPORTED, } liq_error; enum liq_ownership { LIQ_OWN_ROWS=4, LIQ_OWN_PIXELS=8, LIQ_COPY_PIXELS=16, }; typedef struct liq_histogram_entry { liq_color color; unsigned int count; } liq_histogram_entry; LIQ_EXPORT LIQ_USERESULT liq_attr* liq_attr_create(void); LIQ_EXPORT LIQ_USERESULT liq_attr* liq_attr_create_with_allocator(void* removed, void *unsupported); LIQ_EXPORT LIQ_USERESULT liq_attr* liq_attr_copy(const liq_attr *orig) LIQ_NONNULL; LIQ_EXPORT void liq_attr_destroy(liq_attr *attr) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT liq_histogram* liq_histogram_create(const liq_attr* attr); LIQ_EXPORT liq_error liq_histogram_add_image(liq_histogram *hist, const liq_attr *attr, liq_image* image) LIQ_NONNULL; LIQ_EXPORT liq_error liq_histogram_add_colors(liq_histogram *hist, const liq_attr *attr, const liq_histogram_entry entries[], int num_entries, double gamma) LIQ_NONNULL; LIQ_EXPORT liq_error liq_histogram_add_fixed_color(liq_histogram *hist, liq_color color, double gamma) LIQ_NONNULL; LIQ_EXPORT void liq_histogram_destroy(liq_histogram *hist) LIQ_NONNULL; LIQ_EXPORT liq_error liq_set_max_colors(liq_attr* attr, int colors) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT int liq_get_max_colors(const liq_attr* attr) LIQ_NONNULL; LIQ_EXPORT liq_error liq_set_speed(liq_attr* attr, int speed) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT int liq_get_speed(const liq_attr* attr) LIQ_NONNULL; LIQ_EXPORT liq_error liq_set_min_opacity(liq_attr* attr, int min) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT int liq_get_min_opacity(const liq_attr* attr) LIQ_NONNULL; LIQ_EXPORT liq_error liq_set_min_posterization(liq_attr* attr, int bits) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT int liq_get_min_posterization(const liq_attr* attr) LIQ_NONNULL; LIQ_EXPORT liq_error liq_set_quality(liq_attr* attr, int minimum, int maximum) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT int liq_get_min_quality(const liq_attr* attr) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT int liq_get_max_quality(const liq_attr* attr) LIQ_NONNULL; LIQ_EXPORT void liq_set_last_index_transparent(liq_attr* attr, int is_last) LIQ_NONNULL; typedef void liq_log_callback_function(const liq_attr*, const char *message, void* user_info); typedef void liq_log_flush_callback_function(const liq_attr*, void* user_info); LIQ_EXPORT void liq_set_log_callback(liq_attr*, liq_log_callback_function*, void* user_info); LIQ_EXPORT void liq_set_log_flush_callback(liq_attr*, liq_log_flush_callback_function*, void* user_info); typedef int liq_progress_callback_function(float progress_percent, void* user_info); LIQ_EXPORT void liq_attr_set_progress_callback(liq_attr*, liq_progress_callback_function*, void* user_info); LIQ_EXPORT void liq_result_set_progress_callback(liq_result*, liq_progress_callback_function*, void* user_info); // The rows and their data are not modified. The type of `rows` is non-const only due to a bug in C's typesystem design. LIQ_EXPORT LIQ_USERESULT liq_image *liq_image_create_rgba_rows(const liq_attr *attr, void *const rows[], int width, int height, double gamma) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT liq_image *liq_image_create_rgba(const liq_attr *attr, const void *bitmap, int width, int height, double gamma) LIQ_NONNULL; typedef void liq_image_get_rgba_row_callback(liq_color row_out[], int row, int width, void* user_info); LIQ_EXPORT LIQ_USERESULT liq_image *liq_image_create_custom(const liq_attr *attr, liq_image_get_rgba_row_callback *row_callback, void* user_info, int width, int height, double gamma); LIQ_EXPORT liq_error liq_image_set_memory_ownership(liq_image *image, int ownership_flags) LIQ_NONNULL; LIQ_EXPORT liq_error liq_image_set_background(liq_image *img, liq_image *background_image) LIQ_NONNULL; LIQ_EXPORT liq_error liq_image_set_importance_map(liq_image *img, unsigned char buffer[], size_t buffer_size, enum liq_ownership memory_handling) LIQ_NONNULL; LIQ_EXPORT liq_error liq_image_add_fixed_color(liq_image *img, liq_color color) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT int liq_image_get_width(const liq_image *img) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT int liq_image_get_height(const liq_image *img) LIQ_NONNULL; LIQ_EXPORT void liq_image_destroy(liq_image *img) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT liq_error liq_histogram_quantize(liq_histogram *const input_hist, liq_attr *const options, liq_result **result_output) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT liq_error liq_image_quantize(liq_image *const input_image, liq_attr *const options, liq_result **result_output) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT liq_error liq_result_from_palette(const liq_attr *options, const liq_color *palette, unsigned int palette_size, double gamma, liq_result **result_output) LIQ_NONNULL; LIQ_EXPORT liq_error liq_set_dithering_level(liq_result *res, float dither_level) LIQ_NONNULL; LIQ_EXPORT liq_error liq_set_output_gamma(liq_result* res, double gamma) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT double liq_get_output_gamma(const liq_result *result) LIQ_NONNULL; LIQ_EXPORT LIQ_USERESULT const liq_palette *liq_get_palette(liq_result *result) LIQ_NONNULL; LIQ_EXPORT liq_error liq_write_remapped_image(liq_result *result, liq_image *input_image, void *buffer, size_t buffer_size) LIQ_NONNULL; LIQ_EXPORT liq_error liq_write_remapped_image_rows(liq_result *result, liq_image *input_image, unsigned char **row_pointers) LIQ_NONNULL; LIQ_EXPORT double liq_get_quantization_error(const liq_result *result) LIQ_NONNULL; LIQ_EXPORT int liq_get_quantization_quality(const liq_result *result) LIQ_NONNULL; LIQ_EXPORT double liq_get_remapping_error(const liq_result *result) LIQ_NONNULL; LIQ_EXPORT int liq_get_remapping_quality(const liq_result *result) LIQ_NONNULL; LIQ_EXPORT void liq_result_destroy(liq_result *) LIQ_NONNULL; LIQ_EXPORT int liq_version(void); // Deprecated LIQ_EXPORT LIQ_USERESULT liq_result *liq_quantize_image(liq_attr *options, liq_image *input_image) LIQ_NONNULL; #ifdef __cplusplus } #endif #endif libimagequant-4.4.0/imagequant-sys/org/000077500000000000000000000000001503274717000201055ustar00rootroot00000000000000libimagequant-4.4.0/imagequant-sys/org/pngquant/000077500000000000000000000000001503274717000217425ustar00rootroot00000000000000libimagequant-4.4.0/imagequant-sys/org/pngquant/Image.java000066400000000000000000000051101503274717000236240ustar00rootroot00000000000000package org.pngquant; import org.pngquant.*; import java.awt.image.*; /** * PngQuant's representation of an Image constructed from BufferedImage. */ public class Image extends LiqObject { /** * Converts BufferedImage to internal representation (pixel data is copied). * It's best to use BufferedImage in RGB/RGBA format backed by DataBufferByte. * Throws if conversion fails. */ public Image(BufferedImage image) throws PngQuantException { this(new PngQuant(), image); } public Image(PngQuant attr, BufferedImage image) throws PngQuantException { handle = handleFromImage(attr, image); if (handle == 0) { BufferedImage converted = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); converted.getGraphics().drawImage(image, 0, 0, null); handle = handleFromImage(attr, converted); if (handle == 0) { throw new PngQuantException(); } } } /** * Guarantees presence of the given color in the palette (subject to setMaxColors()) * if this image is used for quantization. */ public native boolean addFixedColor(int r, int g, int b, int a); public boolean addFixedColor(int r, int g, int b) { return addFixedColor(r, g, b, 255); } public native int getWidth(); public native int getHeight(); public void close() { if (handle != 0) { liq_image_destroy(handle); handle = 0; } } private static long handleFromImage(PngQuant attr, BufferedImage image) { // The JNI wrapper will accept non-premultiplied ABGR and BGR only. int type = image.getType(); if (type != BufferedImage.TYPE_3BYTE_BGR && type != BufferedImage.TYPE_4BYTE_ABGR && type != BufferedImage.TYPE_4BYTE_ABGR_PRE) return 0; WritableRaster raster = image.getRaster(); ColorModel color = image.getColorModel(); if (type == BufferedImage.TYPE_4BYTE_ABGR_PRE) color.coerceData(raster, false); DataBuffer buffer = raster.getDataBuffer(); if (buffer instanceof DataBufferByte) { byte[] imageData = ((DataBufferByte)buffer).getData(); return liq_image_create(attr.handle, imageData, raster.getWidth(), raster.getHeight(), color.getNumComponents()); } return 0; } private static native long liq_image_create(long attr, byte[] bitmap, int width, int height, int components); private static native void liq_image_destroy(long handle); } libimagequant-4.4.0/imagequant-sys/org/pngquant/LiqObject.java000066400000000000000000000006451503274717000244660ustar00rootroot00000000000000package org.pngquant; abstract class LiqObject { static { // libimagequant.jnilib or libimagequant.so must be in java.library.path System.loadLibrary("imagequant"); } long handle; /** * Free memory used by the library. The object must not be used after this call. */ abstract public void close(); protected void finalize() throws Throwable { close(); } } libimagequant-4.4.0/imagequant-sys/org/pngquant/PngQuant.c000066400000000000000000000146661503274717000236600ustar00rootroot00000000000000#include "org/pngquant/PngQuant.h" #include "org/pngquant/Image.h" #include "org/pngquant/Result.h" #include "libimagequant.h" #include typedef struct { liq_image *image; jbyte *data; } liq_jni_image; static void *handle(JNIEnv *env, jobject obj) { jlong h = (*env)->GetLongField(env, obj, (*env)->GetFieldID(env, (*env)->GetObjectClass(env, obj), "handle", "J")); return (void*)h; } JNIEXPORT jlong JNICALL Java_org_pngquant_PngQuant_liq_1attr_1create(JNIEnv *env, jclass class) { return (jlong)liq_attr_create(); } JNIEXPORT jlong JNICALL Java_org_pngquant_PngQuant_liq_1attr_1copy(JNIEnv *env, jclass class, jlong attr) { return (jlong)liq_attr_copy((liq_attr*)attr); } JNIEXPORT void JNICALL Java_org_pngquant_PngQuant_liq_1attr_1destroy(JNIEnv *env, jclass class, jlong attr) { return liq_attr_destroy((liq_attr*)attr); } JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setMaxColors(JNIEnv *env, jobject obj, jint colors) { return LIQ_OK == liq_set_max_colors(handle(env, obj), colors); } JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setSpeed(JNIEnv *env, jobject obj, jint speed) { return LIQ_OK == liq_set_speed(handle(env, obj), speed); } JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setMinPosterization(JNIEnv *env, jobject obj, jint p) { return LIQ_OK == liq_set_min_posterization(handle(env, obj), p); } JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setQuality__I(JNIEnv *env, jobject obj, jint q) { return LIQ_OK == liq_set_quality(handle(env, obj), q/2, q); } JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setQuality__II(JNIEnv *env, jobject obj, jint qmin, jint qmax) { return LIQ_OK == liq_set_quality(handle(env, obj), qmin, qmax); } static void convert_abgr(liq_color row_out[], int row_index, int width, void* user_info) { liq_jni_image *jniimg = user_info; int column_index; for(column_index=0; column_index < width; column_index++) { row_out[column_index].r = jniimg->data[4*(width*row_index + column_index) + 3]; row_out[column_index].g = jniimg->data[4*(width*row_index + column_index) + 2]; row_out[column_index].b = jniimg->data[4*(width*row_index + column_index) + 1]; row_out[column_index].a = jniimg->data[4*(width*row_index + column_index) + 0]; } } static void convert_bgr(liq_color row_out[], int row_index, int width, void* user_info) { liq_jni_image *jniimg = user_info; int column_index; for(column_index=0; column_index < width; column_index++) { row_out[column_index].r = jniimg->data[3*(width*row_index + column_index) + 2]; row_out[column_index].g = jniimg->data[3*(width*row_index + column_index) + 1]; row_out[column_index].b = jniimg->data[3*(width*row_index + column_index) + 0]; row_out[column_index].a = 255; } } JNIEXPORT jlong JNICALL Java_org_pngquant_Image_liq_1image_1create(JNIEnv *env, jclass class, jlong attr, jbyteArray bytearray, jint w, jint h, jint components) { /* liq_image needs to be wrapped to keep track of allocated buffer */ liq_jni_image *jniimg = malloc(sizeof(liq_jni_image)); /* copying buffer, since ReleaseByteArrayElements was crashing when called from finalize() */ jsize size = (*env)->GetArrayLength(env, bytearray); jniimg->data = malloc(size); (*env)->GetByteArrayRegion(env, bytearray, 0, size, jniimg->data); jniimg->image = liq_image_create_custom((liq_attr*)attr, components == 4 ? convert_abgr : convert_bgr, jniimg, w, h, 0); if (!jniimg->image) { free(jniimg->data); free(jniimg); return 0; } return (jlong)jniimg; } JNIEXPORT jboolean JNICALL Java_org_pngquant_Image_addFixedColor(JNIEnv *env, jobject obj, jint r, jint g, jint b, jint a) { liq_color c = {r,g,b,a}; return LIQ_OK == liq_image_add_fixed_color(((liq_jni_image*)handle(env,obj))->image, c); } JNIEXPORT jint JNICALL Java_org_pngquant_Image_getWidth(JNIEnv *env, jobject obj) { return liq_image_get_width(((liq_jni_image*)handle(env,obj))->image); } JNIEXPORT jint JNICALL Java_org_pngquant_Image_getHeight(JNIEnv *env, jobject obj) { return liq_image_get_height(((liq_jni_image*)handle(env,obj))->image); } JNIEXPORT void JNICALL Java_org_pngquant_Image_liq_1image_1destroy(JNIEnv *env, jclass class, jlong handle) { liq_jni_image *jniimg = (liq_jni_image*)handle; liq_image_destroy(jniimg->image); free(jniimg->data); free(jniimg); } JNIEXPORT jlong JNICALL Java_org_pngquant_Result_liq_1quantize_1image(JNIEnv *env, jclass class, jlong attr, jlong handle) { return (jlong)liq_quantize_image((liq_attr*)attr, ((liq_jni_image*)handle)->image); } JNIEXPORT jboolean JNICALL Java_org_pngquant_Result_setDitheringLevel(JNIEnv *env, jobject obj, jfloat l) { return LIQ_OK == liq_set_dithering_level(handle(env, obj), l); } JNIEXPORT jboolean JNICALL Java_org_pngquant_Result_setGamma(JNIEnv *env, jobject obj, jdouble gamma) { return LIQ_OK == liq_set_output_gamma(handle(env, obj), gamma); } JNIEXPORT jdouble JNICALL Java_org_pngquant_Result_getGamma(JNIEnv *env, jobject obj) { return liq_get_output_gamma(handle(env, obj)); } JNIEXPORT jboolean JNICALL Java_org_pngquant_Result_liq_1write_1remapped_1image(JNIEnv *env, jclass class, jlong result, jlong image_handle, jbyteArray bytearray) { jsize size = (*env)->GetArrayLength(env, bytearray); jbyte *bitmap = (*env)->GetByteArrayElements(env, bytearray, 0); liq_error err = liq_write_remapped_image((liq_result*)result, ((liq_jni_image*)image_handle)->image, bitmap, size); (*env)->ReleaseByteArrayElements(env, bytearray, bitmap, 0); return LIQ_OK == err; } JNIEXPORT jdouble JNICALL Java_org_pngquant_Result_getMeanSquareError(JNIEnv *env, jobject obj) { return liq_get_quantization_error(handle(env, obj)); } JNIEXPORT jint JNICALL Java_org_pngquant_Result_getQuality(JNIEnv *env, jobject obj) { return liq_get_quantization_quality(handle(env, obj)); } JNIEXPORT void JNICALL Java_org_pngquant_Result_liq_1result_1destroy(JNIEnv *env, jclass class, jlong result) { return liq_result_destroy((liq_result*)result); } JNIEXPORT jbyteArray JNICALL Java_org_pngquant_Result_liq_1get_1palette(JNIEnv *env, jclass class, jlong result) { const liq_palette *pal = liq_get_palette((liq_result*)result); jbyteArray arr = (*env)->NewByteArray(env, pal->count * 4); int i; for(i=0; i < pal->count; i++) { (*env)->SetByteArrayRegion(env, arr, i*4, 4, ((jbyte*)&pal->entries[i])); } return arr; } libimagequant-4.4.0/imagequant-sys/org/pngquant/PngQuant.java000066400000000000000000000063561503274717000243540ustar00rootroot00000000000000package org.pngquant; import org.pngquant.*; import java.awt.image.*; /** * Starting point for the library. Holds configuration. Equivalent of liq_attr* in libimagequant. */ public class PngQuant extends LiqObject { /** * Single instance can be "recycled" for many remappings. */ public PngQuant() { handle = liq_attr_create(); } public PngQuant(PngQuant other) { handle = liq_attr_copy(other.handle); } /** * 1-shot quantization and remapping with current settings. * @see quantize() * * @return 8-bit indexed image or null on failure */ public BufferedImage getRemapped(BufferedImage bufimg) { try { Image liqimg = new Image(this, bufimg); BufferedImage remapped = getRemapped(liqimg); liqimg.close(); return remapped; } catch(PngQuantException e) { return null; } } /** @return remapped image or null on failure */ public BufferedImage getRemapped(Image liqimg) { Result result = quantize(liqimg); if (result == null) return null; BufferedImage remapped = result.getRemapped(liqimg); result.close(); return remapped; } /** * Performs quantization (chooses optimal palette for the given Image). * Returned object can be used to customize remapping and reused to remap other images to the same palette. * @link http://pngquant.org/lib/#liq_quantize_image * * @return null on failure */ public Result quantize(Image img) { try { return new Result(this, img); } catch(PngQuantException e) { return null; } } /** * Remapped images won't use more than given number of colors (may use less if setQuality() is used) * * @link http://pngquant.org/lib/#liq_set_max_colors */ public native boolean setMaxColors(int colors); /** * Equivalent of setQuality(target/2, target) * * @link http://pngquant.org/lib/#liq_set_quality */ public native boolean setQuality(int target); /** * Quality in range 0-100. Quantization will fail if minimum quality cannot * be achieved with given number of colors. * * @link http://pngquant.org/lib/#liq_set_quality */ public native boolean setQuality(int min, int max); /** * Speed in range 1 (slowest) and 11 (fastest). 3 is the optimum. * Higher speeds quantize quicker, but at cost of quality and sometimes larger images. * * @link http://pngquant.org/lib/#liq_set_speed */ public native boolean setSpeed(int speed); /** * Reduces color precision by truncating number of least significant bits. * Slightly improves speed and helps generating images for low-fidelity displays/textures. * * @link http://pngquant.org/lib/#liq_set_min_posterization */ public native boolean setMinPosterization(int bits); public void close() { if (handle != 0) { liq_attr_destroy(handle); handle = 0; } } private static native long liq_attr_create(); private static native long liq_attr_copy(long orig); private static native void liq_attr_destroy(long handle); } libimagequant-4.4.0/imagequant-sys/org/pngquant/PngQuantException.java000066400000000000000000000001141503274717000262150ustar00rootroot00000000000000package org.pngquant; public class PngQuantException extends Exception { } libimagequant-4.4.0/imagequant-sys/org/pngquant/Result.java000066400000000000000000000057331503274717000240730ustar00rootroot00000000000000package org.pngquant; import org.pngquant.*; import java.awt.image.*; /** * Quantization result that holds palette and options for remapping. */ public class Result extends LiqObject { /** * Throws when quantization fails (e.g. due to failing to achieve minimum quality) */ public Result(PngQuant pngquant, Image image) throws PngQuantException { handle = liq_quantize_image(pngquant.handle, image.handle); if (handle == 0) { throw new PngQuantException(); } } /** * @return BufferedImage remapped to palette this Result has been created with or null on failure. */ public BufferedImage getRemapped(Image orig_image) { byte[] pal = liq_get_palette(handle); IndexColorModel color = new IndexColorModel(8, pal.length/4, pal, 0, true); BufferedImage img = new BufferedImage( orig_image.getWidth(), orig_image.getHeight(), BufferedImage.TYPE_BYTE_INDEXED, color); byte[] data = get8bitDataFromImage(img); if (data == null) return null; if (!liq_write_remapped_image(handle, orig_image.handle, data)) return null; return img; } /** * Dithering strength. Floyd-Steinberg is always used and in * speed settings 1-5 high-quality adaptive dithering is used. * @see PngQuant.setSpeed() * @link http://pngquant.org/lib/#liq_set_dithering_level * * @param dither_level Dithering in range 0 (none) and 1 (full) */ public native boolean setDitheringLevel(float dither_level); /** * The default is 0.45455 (1/2.2) which is PNG's approximation of sRGB. */ public native boolean setGamma(double gamma); public native double getGamma(); /** * Mean Square Error of remapping of image used to create this result. * @link http://pngquant.org/lib/#liq_get_quantization_error * * @return MSE or -1 if not available */ public native double getMeanSquareError(); /** * @link http://pngquant.org/lib/#liq_get_quantization_quality * @return Actually achieved quality in 0-100 range on scale compatible with PngQuant.setQuality() */ public native int getQuality(); public void close() { if (handle != 0) { liq_result_destroy(handle); handle = 0; } } private static byte[] get8bitDataFromImage(BufferedImage image) { if (image.getType() == BufferedImage.TYPE_BYTE_INDEXED) { DataBuffer buffer = image.getRaster().getDataBuffer(); if (buffer instanceof DataBufferByte) { return ((DataBufferByte)buffer).getData(); } } return null; } private static native byte[] liq_get_palette(long handle); private static native long liq_quantize_image(long attr, long image); private static native boolean liq_write_remapped_image(long handle, long image, byte[] buffer); private static native void liq_result_destroy(long handle); } libimagequant-4.4.0/imagequant-sys/pom.xml000066400000000000000000000047751503274717000206500ustar00rootroot00000000000000 4.0.0 org.pngquant libimagequant jar 4.0.3 pngquant https://pngquant.org . org.codehaus.mojo exec-maven-plugin 1.1 build compile exec make -j8 USE_SSE=1 java clean clean exec make clean mac-x64 Mac x64 org.pngquant libimagequant-jni 1 jnilib mac-x64 linux-x64 unix Linux x64 org.pngquant libimagequant-jni so 1 linux-x64 libimagequant-4.4.0/imagequant-sys/src/000077500000000000000000000000001503274717000201055ustar00rootroot00000000000000libimagequant-4.4.0/imagequant-sys/src/ffi.rs000066400000000000000000000710031503274717000212200ustar00rootroot00000000000000//! Exports API for C programs and C-FFI-compatible languages. See `libimagequant.h` or for C docs. //! //! This crate is not supposed to be used in Rust directly. For Rust, see the parent [imagequant](https://lib.rs/imagequant) crate. #![allow(non_camel_case_types)] #![allow(clippy::missing_safety_doc)] #![allow(clippy::wildcard_imports)] #![allow(clippy::items_after_statements)] #![allow(clippy::cast_possible_truncation)] #![allow(clippy::cast_possible_wrap)] use imagequant::capi::*; use imagequant::Error::LIQ_OK; use imagequant::*; use std::ffi::CString; use std::mem::{ManuallyDrop, MaybeUninit}; use std::os::raw::{c_char, c_int, c_uint, c_void}; use std::ptr; pub use imagequant::Error as liq_error; #[repr(C)] pub struct liq_attr { magic_header: MagicTag, inner: Attributes, c_api_free: unsafe extern "C" fn(*mut c_void), } #[repr(C)] pub struct liq_image<'pixels> { magic_header: MagicTag, inner: ManuallyDrop>, c_api_free: unsafe extern "C" fn(*mut c_void), } #[repr(C)] pub struct liq_result { magic_header: MagicTag, inner: QuantizationResult, } #[repr(C)] pub struct liq_histogram { magic_header: MagicTag, inner: Histogram, } pub type liq_palette = Palette; pub type liq_histogram_entry = HistogramEntry; pub type liq_color = RGBA; pub type liq_log_callback_function = unsafe extern "C" fn(liq: &liq_attr, message: *const c_char, user_info: AnySyncSendPtr); pub type liq_log_flush_callback_function = unsafe extern "C" fn(liq: &liq_attr, user_info: AnySyncSendPtr); pub type liq_progress_callback_function = unsafe extern "C" fn(progress_percent: f32, user_info: AnySyncSendPtr) -> c_int; pub type liq_image_get_rgba_row_callback = unsafe extern "C" fn(row_out: *mut MaybeUninit, row: c_int, width: c_int, user_info: AnySyncSendPtr); bitflags::bitflags! { #[repr(C)] #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)] pub struct liq_ownership: c_int { /// Moves ownership of the rows array. It will free it using `free()` or custom allocator. const LIQ_OWN_ROWS = 4; /// Moves ownership of the pixel data. It will free it using `free()` or custom allocator. const LIQ_OWN_PIXELS = 8; /// Makes a copy of the pixels, so the `liq_image` is not tied to pixel's lifetime. const LIQ_COPY_PIXELS = 16; } } #[repr(transparent)] #[derive(PartialEq, Debug, Copy, Clone)] pub(crate) struct MagicTag(*const u8); // Safety: Rust overreacts about C pointers. Data behind this ptr isn't used. unsafe impl Sync for MagicTag {} unsafe impl Send for MagicTag {} pub(crate) static LIQ_ATTR_MAGIC: MagicTag = MagicTag(b"liq_attr_magic\0".as_ptr()); pub(crate) static LIQ_IMAGE_MAGIC: MagicTag = MagicTag(b"liq_image_magic\0".as_ptr()); pub(crate) static LIQ_RESULT_MAGIC: MagicTag = MagicTag(b"liq_result_magic\0".as_ptr()); pub(crate) static LIQ_HISTOGRAM_MAGIC: MagicTag = MagicTag(b"liq_histogram_magic\0".as_ptr()); pub(crate) static LIQ_FREED_MAGIC: MagicTag = MagicTag(b"liq_freed_magic\0".as_ptr()); #[no_mangle] #[inline(never)] unsafe extern "C" fn liq_received_invalid_pointer(ptr: *const u8) -> bool { if ptr.is_null() { return true; } let _ = ptr::read_volatile(ptr); false } macro_rules! bad_object { ($obj:expr, $tag:expr) => {{ let obj = &*$obj; #[allow(unused_unsafe)] #[allow(clippy::ptr_as_ptr)] let bork = if cfg!(miri) { false } else { unsafe { liq_received_invalid_pointer((obj as *const _ as *const u8)) } }; (bork || (($obj).magic_header != $tag)) }}; } impl Drop for liq_attr { fn drop(&mut self) { if bad_object!(self, LIQ_ATTR_MAGIC) { return; } self.magic_header = LIQ_FREED_MAGIC; } } impl Drop for liq_image<'_> { fn drop(&mut self) { if bad_object!(self, LIQ_IMAGE_MAGIC) { return; } unsafe { ManuallyDrop::drop(&mut self.inner); } self.magic_header = LIQ_FREED_MAGIC; } } impl Drop for liq_result { fn drop(&mut self) { if bad_object!(self, LIQ_RESULT_MAGIC) { return; } self.magic_header = LIQ_FREED_MAGIC; } } impl Drop for liq_histogram { fn drop(&mut self) { if bad_object!(self, LIQ_HISTOGRAM_MAGIC) { return; } self.magic_header = LIQ_FREED_MAGIC; } } #[no_mangle] #[inline(never)] pub extern "C" fn liq_version() -> c_uint { LIQ_VERSION } #[no_mangle] #[inline(never)] #[deprecated] pub extern "C" fn liq_set_min_opacity(_: &mut liq_attr, _: c_int) -> liq_error { LIQ_OK } #[no_mangle] #[inline(never)] #[deprecated] pub extern "C" fn liq_get_min_opacity(_: &liq_attr) -> c_int { 0 } #[no_mangle] #[inline(never)] pub extern "C" fn liq_set_last_index_transparent(attr: &mut liq_attr, is_last: c_int) { if bad_object!(attr, LIQ_ATTR_MAGIC) { return; } attr.inner.set_last_index_transparent(is_last != 0); } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_palette(result: &mut liq_result) -> Option<&liq_palette> { if bad_object!(result, LIQ_RESULT_MAGIC) { return None; } Some(liq_get_palette_impl(&mut result.inner)) } /// A `void*` pointer to any data, as long as it's thread-safe #[repr(transparent)] #[derive(Clone, Copy)] pub struct AnySyncSendPtr(pub *mut c_void); impl Default for AnySyncSendPtr { fn default() -> Self { Self(ptr::null_mut()) } } /// C callback user is responsible for ensuring safety unsafe impl Send for AnySyncSendPtr {} unsafe impl Sync for AnySyncSendPtr {} #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_attr_set_progress_callback(attr: &mut liq_attr, callback: liq_progress_callback_function, user_info: AnySyncSendPtr) { if bad_object!(attr, LIQ_ATTR_MAGIC) { return; } let cb = move |f| if callback(f, user_info) == 0 { ControlFlow::Break} else { ControlFlow::Continue}; attr.inner.set_progress_callback(cb); } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_result_set_progress_callback(result: &mut liq_result, callback: liq_progress_callback_function, user_info: AnySyncSendPtr) { if bad_object!(result, LIQ_RESULT_MAGIC) { return; } result.inner.set_progress_callback(move |f| if callback(f, user_info) == 0 { ControlFlow::Break} else { ControlFlow::Continue}); } #[allow(clippy::cast_ptr_alignment)] unsafe fn attr_to_liq_attr_ptr(ptr: &Attributes) -> &liq_attr { let liq_attr = std::ptr::NonNull::::dangling(); let outer_addr = std::ptr::addr_of!(*liq_attr.as_ptr()) as isize; let inner_addr = std::ptr::addr_of!((*liq_attr.as_ptr()).inner) as isize; &*(ptr as *const Attributes).cast::().offset(outer_addr - inner_addr).cast::() } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_set_log_callback(attr: &mut liq_attr, callback: liq_log_callback_function, user_info: AnySyncSendPtr) { if bad_object!(attr, LIQ_ATTR_MAGIC) { return; } attr.inner.set_log_callback(move |attr, msg| { if let Ok(tmp) = CString::new(msg) { callback(attr_to_liq_attr_ptr(attr), tmp.as_ptr(), user_info); } }); } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_set_log_flush_callback(attr: &mut liq_attr, callback: liq_log_flush_callback_function, user_info: AnySyncSendPtr) { if bad_object!(attr, LIQ_ATTR_MAGIC) { return; } attr.inner.set_log_flush_callback(move |attr| callback(attr_to_liq_attr_ptr(attr), user_info)); } #[no_mangle] #[inline(never)] pub extern "C" fn liq_set_max_colors(attr: &mut liq_attr, colors: c_uint) -> liq_error { if bad_object!(attr, LIQ_ATTR_MAGIC) { return Error::InvalidPointer; } attr.inner.set_max_colors(colors).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_max_colors(attr: &liq_attr) -> c_uint { if bad_object!(attr, LIQ_ATTR_MAGIC) { return !0; } attr.inner.max_colors() } #[no_mangle] #[inline(never)] pub extern "C" fn liq_set_min_posterization(attr: &mut liq_attr, bits: c_int) -> liq_error { if bad_object!(attr, LIQ_ATTR_MAGIC) { return Error::InvalidPointer; } attr.inner.set_min_posterization(bits as u8).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_min_posterization(attr: &liq_attr) -> c_uint { if bad_object!(attr, LIQ_ATTR_MAGIC) { return !0; } attr.inner.min_posterization().into() } #[no_mangle] #[inline(never)] pub extern "C" fn liq_set_speed(attr: &mut liq_attr, speed: c_int) -> liq_error { attr.inner.set_speed(speed).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_speed(attr: &liq_attr) -> c_uint { if bad_object!(attr, LIQ_ATTR_MAGIC) { return !0; } attr.inner.speed() } #[no_mangle] #[inline(never)] pub extern "C" fn liq_set_quality(attr: &mut liq_attr, minimum: c_uint, target: c_uint) -> liq_error { if bad_object!(attr, LIQ_ATTR_MAGIC) { return Error::InvalidPointer; } attr.inner.set_quality(minimum as u8, target as u8).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_min_quality(attr: &liq_attr) -> c_uint { if bad_object!(attr, LIQ_ATTR_MAGIC) { return !0; } attr.inner.quality().0.into() } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_max_quality(attr: &liq_attr) -> c_uint { if bad_object!(attr, LIQ_ATTR_MAGIC) { return !0; } attr.inner.quality().1.into() } #[no_mangle] #[inline(never)] pub extern "C" fn liq_quantize_image(attr: &mut liq_attr, img: &mut liq_image) -> Option> { if bad_object!(attr, LIQ_ATTR_MAGIC) || bad_object!(img, LIQ_IMAGE_MAGIC) { return None; } let img = &mut img.inner; let attr = &mut attr.inner; attr.quantize(img).ok().map(|inner| Box::new(liq_result { magic_header: LIQ_RESULT_MAGIC, inner, })) } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_write_remapped_image(result: &mut liq_result, input_image: &mut liq_image, buffer_bytes: *mut MaybeUninit, buffer_size: usize) -> liq_error { if bad_object!(result, LIQ_RESULT_MAGIC) || bad_object!(input_image, LIQ_IMAGE_MAGIC) { return Error::InvalidPointer; } let input_image = &mut input_image.inner; let result = &mut result.inner; if liq_received_invalid_pointer(buffer_bytes.cast()) { return Error::InvalidPointer; } let required_size = (input_image.width()) * (input_image.height()); if buffer_size < required_size { return Error::BufferTooSmall; } let buffer_bytes = std::slice::from_raw_parts_mut(buffer_bytes, required_size); liq_write_remapped_image_impl(result, input_image, buffer_bytes).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_write_remapped_image_rows(result: &mut liq_result, input_image: &mut liq_image, row_pointers: *mut *mut MaybeUninit) -> liq_error { if bad_object!(result, LIQ_RESULT_MAGIC) || bad_object!(input_image, LIQ_IMAGE_MAGIC) { return Error::InvalidPointer; } let input_image = &mut input_image.inner; let result = &mut result.inner; if liq_received_invalid_pointer(row_pointers.cast()) { return Error::InvalidPointer; } let rows = std::slice::from_raw_parts_mut(row_pointers, input_image.height()); liq_write_remapped_image_rows_impl(result, input_image, rows).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_image_add_fixed_color(img: &mut liq_image, color: liq_color) -> liq_error { if bad_object!(img, LIQ_IMAGE_MAGIC) { return Error::InvalidPointer; } img.inner.add_fixed_color(color).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_histogram_add_fixed_color(hist: &mut liq_histogram, color: liq_color, gamma: f64) -> liq_error { if bad_object!(hist, LIQ_HISTOGRAM_MAGIC) { return Error::InvalidPointer; } let hist = &mut hist.inner; hist.add_fixed_color(color, gamma).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_image_get_width(img: &liq_image) -> c_uint { if bad_object!(img, LIQ_IMAGE_MAGIC) { return !0; } img.inner.width() as _ } #[no_mangle] #[inline(never)] pub extern "C" fn liq_image_get_height(img: &liq_image) -> c_uint { if bad_object!(img, LIQ_IMAGE_MAGIC) { return !0; } img.inner.height() as _ } #[no_mangle] #[inline(never)] pub extern "C" fn liq_image_destroy(_: Option>) {} #[no_mangle] #[inline(never)] pub extern "C" fn liq_image_set_background<'pixels>(img: &mut liq_image<'pixels>, background: Box>) -> liq_error { if bad_object!(img, LIQ_IMAGE_MAGIC) || bad_object!(background, LIQ_IMAGE_MAGIC) { return Error::InvalidPointer; } let background = unsafe { ManuallyDrop::take(&mut ManuallyDrop::new(background).inner) }; img.inner.set_background(background).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_image_set_importance_map(img: &mut liq_image, importance_map: *mut u8, buffer_size: usize, ownership: liq_ownership) -> liq_error { if bad_object!(img, LIQ_IMAGE_MAGIC) { return Error::InvalidPointer; } let free_fn = img.c_api_free; let img = &mut img.inner; if buffer_size == 0 || liq_received_invalid_pointer(importance_map) { return Error::InvalidPointer; } let required_size = img.width() * img.height(); if buffer_size < required_size { return Error::BufferTooSmall; } let importance_map_slice = std::slice::from_raw_parts(importance_map, required_size); if ownership == liq_ownership::LIQ_COPY_PIXELS { img.set_importance_map(importance_map_slice).err().unwrap_or(LIQ_OK) } else if ownership == liq_ownership::LIQ_OWN_PIXELS { let copy: Box<[u8]> = importance_map_slice.into(); free_fn(importance_map.cast()); img.set_importance_map(copy).err().unwrap_or(LIQ_OK); LIQ_OK } else { Error::Unsupported } } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_image_set_memory_ownership(img: &mut liq_image, ownership_flags: liq_ownership) -> liq_error { if bad_object!(img, LIQ_IMAGE_MAGIC) { return Error::InvalidPointer; } let both = liq_ownership::LIQ_OWN_ROWS | liq_ownership::LIQ_OWN_PIXELS; if ownership_flags.is_empty() || (ownership_flags | both) != both { return Error::ValueOutOfRange; } let own_rows = ownership_flags.contains(liq_ownership::LIQ_OWN_ROWS); let own_pixels = ownership_flags.contains(liq_ownership::LIQ_OWN_PIXELS); liq_image_set_memory_ownership_impl(&mut img.inner, own_rows, own_pixels, img.c_api_free).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_histogram_create(attr: &liq_attr) -> Option> { if bad_object!(attr, LIQ_ATTR_MAGIC) { return None; } Some(Box::new(liq_histogram { magic_header: LIQ_HISTOGRAM_MAGIC, inner: Histogram::new(&attr.inner), })) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_histogram_destroy(_hist: Option>) {} #[no_mangle] #[inline(never)] #[deprecated(note = "custom allocators are no longer supported")] pub extern "C" fn liq_attr_create_with_allocator(_unused: *mut c_void, free: unsafe extern "C" fn(*mut c_void)) -> Option> { let attr = Box::new(liq_attr { magic_header: LIQ_ATTR_MAGIC, inner: Attributes::new(), c_api_free: free, }); debug_assert_eq!(std::ptr::addr_of!(*attr), unsafe { attr_to_liq_attr_ptr(&attr.inner) } as *const liq_attr); Some(attr) } #[no_mangle] #[inline(never)] #[allow(deprecated)] pub extern "C" fn liq_attr_create() -> Option> { liq_attr_create_with_allocator(ptr::null_mut(), libc::free) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_attr_copy(attr: &liq_attr) -> Option> { if bad_object!(attr, LIQ_ATTR_MAGIC) { return None; } Some(Box::new(liq_attr { magic_header: LIQ_ATTR_MAGIC, inner: attr.inner.clone(), c_api_free: attr.c_api_free, })) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_attr_destroy(_attr: Option>) {} #[no_mangle] #[inline(never)] pub extern "C" fn liq_result_destroy(_res: Option>) {} #[no_mangle] #[inline(never)] pub extern "C" fn liq_set_output_gamma(result: &mut liq_result, gamma: f64) -> liq_error { if bad_object!(result, LIQ_RESULT_MAGIC) { return Error::InvalidPointer; } result.inner.set_output_gamma(gamma).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_set_dithering_level(result: &mut liq_result, dither_level: f32) -> liq_error { if bad_object!(result, LIQ_RESULT_MAGIC) { return Error::InvalidPointer; } result.inner.set_dithering_level(dither_level).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_output_gamma(result: &liq_result) -> f64 { if bad_object!(result, LIQ_RESULT_MAGIC) { return -1.; } result.inner.output_gamma() } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_quantization_error(result: &liq_result) -> f64 { if bad_object!(result, LIQ_RESULT_MAGIC) { return -1.; } result.inner.quantization_error().unwrap_or(-1.) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_remapping_error(result: &liq_result) -> f64 { if bad_object!(result, LIQ_RESULT_MAGIC) { return -1.; } result.inner.remapping_error().unwrap_or(-1.) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_quantization_quality(result: &liq_result) -> c_int { if bad_object!(result, LIQ_RESULT_MAGIC) { return -1; } result.inner.quantization_quality().map_or(-1, c_int::from) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_get_remapping_quality(result: &liq_result) -> c_int { if bad_object!(result, LIQ_RESULT_MAGIC) { return -1; } result.inner.remapping_quality().map_or(-1, c_int::from) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_image_quantize(img: &mut liq_image, attr: &mut liq_attr, write_only_output: &mut MaybeUninit>>) -> liq_error { if bad_object!(attr, LIQ_ATTR_MAGIC) || bad_object!(img, LIQ_IMAGE_MAGIC) { return Error::InvalidPointer; } let attr = &mut attr.inner; let img = &mut img.inner; let res = attr.quantize(img) .map(|inner| liq_result { magic_header: LIQ_RESULT_MAGIC, inner, }); store_boxed_result(res, write_only_output) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_histogram_quantize(hist: &mut liq_histogram, attr: &liq_attr, write_only_output: &mut MaybeUninit>>) -> liq_error { if bad_object!(attr, LIQ_ATTR_MAGIC) || bad_object!(hist, LIQ_HISTOGRAM_MAGIC) { return Error::InvalidPointer; } let attr = &attr.inner; let hist = &mut hist.inner; let res = hist.quantize(attr) .map(|inner| liq_result { magic_header: LIQ_RESULT_MAGIC, inner, }); store_boxed_result(res, write_only_output) } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_result_from_palette( attr: &liq_attr, palette: *const RGBA, palette_size: c_uint, gamma: f64, write_only_output: &mut MaybeUninit>>, ) -> liq_error { if bad_object!(attr, LIQ_ATTR_MAGIC) { return Error::InvalidPointer; } let Ok(palette_size) = palette_size.try_into() else { return Error::ValueOutOfRange; }; if liq_received_invalid_pointer(palette.cast()) { return Error::InvalidPointer; } let attr = &attr.inner; let palette = std::slice::from_raw_parts(palette, palette_size); let res = QuantizationResult::from_palette(attr, palette, gamma).map(|inner| liq_result { magic_header: LIQ_RESULT_MAGIC, inner, }); store_boxed_result(res, write_only_output) } #[inline] fn store_boxed_result(res: Result, out: &mut MaybeUninit>>) -> liq_error { match res { Ok(res) => { out.write(Some(Box::new(res))); LIQ_OK }, Err(err) => { out.write(None); err }, } } pub(crate) fn check_image_size(attr: &liq_attr, width: u32, height: u32) -> bool { if bad_object!(attr, LIQ_ATTR_MAGIC) { return false; } if width == 0 || height == 0 { return false; } if width as usize > c_int::MAX as usize / std::mem::size_of::() / height as usize || width as usize > c_int::MAX as usize / 16 / std::mem::size_of::() || height as usize > c_int::MAX as usize / std::mem::size_of::() { return false; } true } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_image_create_custom(attr: &liq_attr, row_callback: liq_image_get_rgba_row_callback, user_info: AnySyncSendPtr, width: c_uint, height: c_uint, gamma: f64) -> Option>> { let cb: Box], usize) + Send + Sync> = Box::new(move |row, y| row_callback(row.as_mut_ptr(), y as _, row.len() as _, user_info)); liq_image_create_custom_impl(&attr.inner, cb, width as _, height as _, gamma) .map(move |inner| Box::new(liq_image { magic_header: LIQ_IMAGE_MAGIC, inner: ManuallyDrop::new(inner), c_api_free: attr.c_api_free, })) } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_image_create_rgba_rows<'rows>(attr: &liq_attr, rows: *const *const RGBA, width: c_uint, height: c_uint, gamma: f64) -> Option>> { if !check_image_size(attr, width, height) { return None; } if rows.is_null() { return None; } let rows = std::slice::from_raw_parts(rows, height as _); liq_image_create_rgba_rows_impl(&attr.inner, rows, width as _, height as _, gamma) .map(move |inner| Box::new(liq_image { magic_header: LIQ_IMAGE_MAGIC, inner: ManuallyDrop::new(inner), c_api_free: attr.c_api_free, })) } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_image_create_rgba<'pixels>(attr: &liq_attr, pixels: *const liq_color, width: c_uint, height: c_uint, gamma: f64) -> Option>> { if liq_received_invalid_pointer(pixels.cast()) { return None; } if !check_image_size(attr, width, height) { return None; } let rows = (0..height as usize).map(move |i| pixels.add(width as usize * i)).collect(); liq_image_create_rgba_bitmap_impl(&attr.inner, rows, width as _, height as _, gamma) .map(move |inner| Box::new(liq_image { magic_header: LIQ_IMAGE_MAGIC, inner: ManuallyDrop::new(inner), c_api_free: attr.c_api_free, })) } #[no_mangle] #[inline(never)] pub unsafe extern "C" fn liq_histogram_add_colors(input_hist: &mut liq_histogram, attr: &liq_attr, entries: *const HistogramEntry, num_entries: c_int, gamma: f64) -> liq_error { if bad_object!(attr, LIQ_ATTR_MAGIC) || bad_object!(input_hist, LIQ_HISTOGRAM_MAGIC) { return Error::InvalidPointer; } let input_hist = &mut input_hist.inner; if num_entries == 0 { return LIQ_OK; } let Ok(num_entries) = num_entries.try_into() else { return Error::ValueOutOfRange; }; if liq_received_invalid_pointer(entries.cast()) { return Error::InvalidPointer; } let entries = std::slice::from_raw_parts(entries, num_entries); input_hist.add_colors(entries, gamma).err().unwrap_or(LIQ_OK) } #[no_mangle] #[inline(never)] pub extern "C" fn liq_histogram_add_image(input_hist: &mut liq_histogram, attr: &liq_attr, input_image: &mut liq_image) -> liq_error { if bad_object!(attr, LIQ_ATTR_MAGIC) || bad_object!(input_hist, LIQ_HISTOGRAM_MAGIC) || bad_object!(input_image, LIQ_IMAGE_MAGIC) { return Error::InvalidPointer; } let attr = &attr.inner; let input_hist = &mut input_hist.inner; let input_image = &mut input_image.inner; input_hist.add_image(attr, input_image).err().unwrap_or(LIQ_OK) } /// This is just to exist in backtraces of crashes that aren't mine #[no_mangle] #[inline(never)] pub unsafe extern "Rust" fn liq_executing_user_callback(callback: liq_image_get_rgba_row_callback, temp_row: &mut [MaybeUninit], row: usize, user_info: AnySyncSendPtr) { callback(temp_row.as_mut_ptr(), row as _, temp_row.len() as _, user_info); } #[test] fn links_and_runs() { use std::ptr; unsafe { assert!(liq_version() >= 40000); let attr = liq_attr_create().unwrap(); let mut hist = liq_histogram_create(&attr).unwrap(); assert_eq!(LIQ_OK, liq_histogram_add_fixed_color(&mut hist, liq_color {r: 0, g: 0, b: 0, a: 0}, 0.)); liq_histogram_add_colors(&mut hist, &attr, ptr::null(), 0, 0.); let mut res = MaybeUninit::uninit(); // this is fine, because there is 1 fixed color to generate assert_eq!(LIQ_OK, liq_histogram_quantize(&mut hist, &attr, &mut res)); let res = res.assume_init().unwrap(); liq_result_destroy(Some(res)); liq_histogram_destroy(Some(hist)); liq_attr_destroy(Some(attr)); } } #[test] #[allow(deprecated)] fn link_every_symbol() { use std::os::raw::c_void; let x = liq_attr_create as *const c_void as usize + liq_attr_create_with_allocator as *const c_void as usize + liq_attr_copy as *const c_void as usize + liq_attr_destroy as *const c_void as usize + liq_set_max_colors as *const c_void as usize + liq_get_max_colors as *const c_void as usize + liq_set_speed as *const c_void as usize + liq_get_speed as *const c_void as usize + liq_set_min_posterization as *const c_void as usize + liq_get_min_posterization as *const c_void as usize + liq_set_quality as *const c_void as usize + liq_get_min_quality as *const c_void as usize + liq_get_max_quality as *const c_void as usize + liq_set_last_index_transparent as *const c_void as usize + liq_image_create_rgba_rows as *const c_void as usize + liq_image_create_rgba as *const c_void as usize + liq_image_set_memory_ownership as *const c_void as usize + liq_set_log_callback as *const c_void as usize + liq_set_log_flush_callback as *const c_void as usize + liq_attr_set_progress_callback as *const c_void as usize + liq_result_set_progress_callback as *const c_void as usize + liq_image_create_custom as *const c_void as usize + liq_image_set_background as *const c_void as usize + liq_image_set_importance_map as *const c_void as usize + liq_image_add_fixed_color as *const c_void as usize + liq_image_get_width as *const c_void as usize + liq_image_get_height as *const c_void as usize + liq_image_destroy as *const c_void as usize + liq_histogram_create as *const c_void as usize + liq_histogram_add_image as *const c_void as usize + liq_histogram_add_colors as *const c_void as usize + liq_histogram_add_fixed_color as *const c_void as usize + liq_histogram_destroy as *const c_void as usize + liq_quantize_image as *const c_void as usize + liq_histogram_quantize as *const c_void as usize + liq_image_quantize as *const c_void as usize + liq_result_from_palette as *const c_void as usize + liq_set_dithering_level as *const c_void as usize + liq_set_output_gamma as *const c_void as usize + liq_get_output_gamma as *const c_void as usize + liq_get_palette as *const c_void as usize + liq_write_remapped_image as *const c_void as usize + liq_write_remapped_image_rows as *const c_void as usize + liq_get_quantization_error as *const c_void as usize + liq_get_quantization_quality as *const c_void as usize + liq_result_destroy as *const c_void as usize + liq_get_remapping_error as *const c_void as usize + liq_get_remapping_quality as *const c_void as usize + liq_version as *const c_void as usize; assert_ne!(!0, x); } #[test] fn c_callback_test_c() { use std::mem::MaybeUninit; let mut called = 0; let mut res = unsafe { let mut a = liq_attr_create().unwrap(); unsafe extern "C" fn get_row(output_row: *mut MaybeUninit, y: c_int, width: c_int, user_data: AnySyncSendPtr) { assert!((0..5).contains(&y)); assert_eq!(123, width); for i in 0..width as isize { let n = i as u8; (*output_row.offset(i)).write(RGBA::new(n, n, n, n)); } let user_data = user_data.0.cast::(); *user_data += 1; } let mut img = liq_image_create_custom(&a, get_row, AnySyncSendPtr(std::ptr::addr_of_mut!(called).cast::()), 123, 5, 0.).unwrap(); liq_quantize_image(&mut a, &mut img).unwrap() }; assert!(called > 5 && called < 50); let pal = liq_get_palette(&mut res).unwrap(); assert_eq!(123, pal.count); } #[test] fn ownership_bitflags() { assert_eq!(4+16, (liq_ownership::LIQ_OWN_ROWS | liq_ownership::LIQ_COPY_PIXELS).bits()); } libimagequant-4.4.0/src/000077500000000000000000000000001503274717000151365ustar00rootroot00000000000000libimagequant-4.4.0/src/attr.rs000066400000000000000000000340031503274717000164560ustar00rootroot00000000000000use crate::error::Error; use crate::hist::Histogram; use crate::image::Image; use crate::pal::{PalLen, MAX_COLORS, RGBA}; use crate::quant::{mse_to_quality, quality_to_mse, QuantizationResult}; use crate::remap::DitherMapMode; use std::sync::Arc; /// Starting point and settings for the quantization process #[derive(Clone)] pub struct Attributes { pub(crate) max_colors: PalLen, target_mse: f64, max_mse: Option, kmeans_iteration_limit: f64, kmeans_iterations: u16, feedback_loop_trials: u16, pub(crate) max_histogram_entries: u32, min_posterization_output: u8, min_posterization_input: u8, pub(crate) last_index_transparent: bool, pub(crate) use_contrast_maps: bool, pub(crate) single_threaded_dithering: bool, pub(crate) use_dither_map: DitherMapMode, speed: u8, pub(crate) progress_stage1: u8, pub(crate) progress_stage2: u8, pub(crate) progress_stage3: u8, progress_callback: Option ControlFlow + Send + Sync>>, log_callback: Option>, log_flush_callback: Option>, } impl Attributes { /// New handle for library configuration /// /// See also [`Attributes::new_image()`] #[inline] #[must_use] pub fn new() -> Self { let mut attr = Self { target_mse: 0., max_mse: None, max_colors: MAX_COLORS as PalLen, last_index_transparent: false, kmeans_iteration_limit: 0., max_histogram_entries: 0, min_posterization_output: 0, min_posterization_input: 0, kmeans_iterations: 0, feedback_loop_trials: 0, use_contrast_maps: false, use_dither_map: DitherMapMode::None, single_threaded_dithering: false, speed: 0, progress_stage1: 0, progress_stage2: 0, progress_stage3: 0, progress_callback: None, log_callback: None, log_flush_callback: None, }; let _ = attr.set_speed(4); attr } /// Make an image from RGBA pixels. /// /// The `pixels` argument can be `Vec`, or `Box<[RGBA]>` or `&[RGBA]`. /// See [`Attributes::new_image_borrowed`] for a non-copying alternative. /// /// Use 0.0 for gamma if the image is sRGB (most images are). #[inline] pub fn new_image(&self, pixels: VecRGBA, width: usize, height: usize, gamma: f64) -> Result, Error> where VecRGBA: Into> { Image::new(self, pixels, width, height, gamma) } /// Generate palette for the image pub fn quantize(&self, image: &mut Image<'_>) -> Result { let mut hist = Histogram::new(self); hist.add_image(self, image)?; hist.quantize_internal(self, false) } /// It's better to use `set_quality()` #[inline] pub fn set_max_colors(&mut self, colors: u32) -> Result<(), Error> { if !(2..=256).contains(&colors) { return Err(Error::ValueOutOfRange); } self.max_colors = colors as PalLen; Ok(()) } /// Range 0-100, roughly like JPEG. /// /// If the minimum quality can't be met, the quantization will be aborted with an error. /// /// Default is min 0, max 100, which means best effort, and never aborts the process. /// /// If max is less than 100, the library will try to use fewer colors. /// Images with fewer colors are not always smaller, due to increased dithering it causes. pub fn set_quality(&mut self, minimum: u8, target: u8) -> Result<(), Error> { if !(0..=100).contains(&target) || target < minimum { return Err(Error::ValueOutOfRange); } if target < 30 { self.verbose_print(" warning: quality set too low"); } self.target_mse = quality_to_mse(target); self.max_mse = Some(quality_to_mse(minimum)); Ok(()) } /// 1-10. /// /// Faster speeds generate images of lower quality, but may be useful /// for real-time generation of images. /// /// The default is 4. #[inline] pub fn set_speed(&mut self, value: i32) -> Result<(), Error> { if !(1..=10).contains(&value) { return Err(Error::ValueOutOfRange); } let mut iterations = (8 - value).max(0) as u16; iterations += iterations * iterations / 2; self.kmeans_iterations = iterations; self.kmeans_iteration_limit = 1. / f64::from(1 << (23 - value)); self.feedback_loop_trials = (56 - 9 * value).max(0) as _; self.max_histogram_entries = ((1 << 17) + (1 << 18) * (10 - value)) as _; self.min_posterization_input = if value >= 8 { 1 } else { 0 }; self.use_dither_map = if value <= 6 { DitherMapMode::Enabled } else { DitherMapMode::None }; if self.use_dither_map != DitherMapMode::None && value < 3 { self.use_dither_map = DitherMapMode::Always; } self.use_contrast_maps = (value <= 7) || self.use_dither_map != DitherMapMode::None; self.single_threaded_dithering = value == 1; self.speed = value as u8; self.progress_stage1 = if self.use_contrast_maps { 20 } else { 8 }; if self.feedback_loop_trials < 2 { self.progress_stage1 += 30; } self.progress_stage3 = (50 / (1 + value)) as u8; self.progress_stage2 = 100 - self.progress_stage1 - self.progress_stage3; Ok(()) } /// Number of least significant bits to ignore. /// /// Useful for generating palettes for VGA, 15-bit textures, or other retro platforms. #[inline] pub fn set_min_posterization(&mut self, value: u8) -> Result<(), Error> { if !(0..=4).contains(&value) { return Err(Error::ValueOutOfRange); } self.min_posterization_output = value; Ok(()) } /// Returns number of bits of precision truncated #[inline(always)] #[must_use] pub fn min_posterization(&self) -> u8 { self.min_posterization_output } /// Return currently set speed/quality trade-off setting #[inline(always)] #[must_use] pub fn speed(&self) -> u32 { self.speed.into() } /// Return max number of colors set #[inline(always)] #[must_use] pub fn max_colors(&self) -> u32 { self.max_colors.into() } /// Reads values set with `set_quality` #[must_use] pub fn quality(&self) -> (u8, u8) { ( self.max_mse.map_or(0, mse_to_quality), mse_to_quality(self.target_mse), ) } /// Describe dimensions of a slice of RGBA pixels /// /// Use 0.0 for gamma if the image is sRGB (most images are). #[inline] pub fn new_image_borrowed<'pixels>(&self, bitmap: &'pixels [RGBA], width: usize, height: usize, gamma: f64) -> Result, Error> { Image::new_borrowed(self, bitmap, width, height, gamma) } /// Like `new_image_stride_borrowed`, but makes a copy of the pixels. /// /// The `pixels` argument can be `Vec`, or `Box<[RGBA]>` or `&[RGBA]`. #[inline] pub fn new_image_stride(&self, pixels: VecRGBA, width: usize, height: usize, stride: usize, gamma: f64) -> Result, Error> where VecRGBA: Into> { Image::new_stride(self, pixels, width, height, stride, gamma) } #[doc(hidden)] #[deprecated(note = "use new_image_stride")] #[cold] pub fn new_image_stride_copy(&self, bitmap: &[RGBA], width: usize, height: usize, stride: usize, gamma: f64) -> Result, Error> { self.new_image_stride(bitmap, width, height, stride, gamma) } /// Set callback function to be called every time the library wants to print a message. /// /// To share data with the callback, use `Arc` or `Atomic*` types and `move ||` closures. #[inline] pub fn set_log_callback(&mut self, callback: F) { self.verbose_printf_flush(); self.log_callback = Some(Arc::new(callback)); } /// Callback for flushing output (if you buffer messages, that's the time to flush those buffers) #[inline] pub fn set_log_flush_callback(&mut self, callback: F) { self.verbose_printf_flush(); self.log_flush_callback = Some(Arc::new(callback)); } /// Set callback function to be called every time the library makes a progress. /// It can be used to cancel operation early. /// /// To share data with the callback, use `Arc` or `Atomic*` types and `move ||` closures. #[inline] pub fn set_progress_callback ControlFlow + Send + Sync + 'static>(&mut self, callback: F) { self.progress_callback = Some(Arc::new(callback)); } /// Move transparent color to the last entry in the palette /// /// This is less efficient for PNG, but required by some broken software #[inline(always)] pub fn set_last_index_transparent(&mut self, is_last: bool) { self.last_index_transparent = is_last; } // true == abort #[inline] #[must_use] pub(crate) fn progress(&self, percent: f32) -> bool { if let Some(f) = &self.progress_callback { f(percent) == ControlFlow::Break } else { false } } #[inline(always)] pub(crate) fn verbose_print(&self, msg: impl AsRef) { fn print_(a: &Attributes, msg: &str) { if let Some(f) = &a.log_callback { f(a, msg); } } print_(self, msg.as_ref()); } #[inline] pub(crate) fn verbose_printf_flush(&self) { if let Some(f) = &self.log_flush_callback { f(self); } } #[must_use] pub(crate) fn feedback_loop_trials(&self, hist_items: usize) -> u16 { let mut feedback_loop_trials = self.feedback_loop_trials; if hist_items > 5000 { feedback_loop_trials = (feedback_loop_trials * 3 + 3) / 4; } if hist_items > 25000 { feedback_loop_trials = (feedback_loop_trials * 3 + 3) / 4; } if hist_items > 50000 { feedback_loop_trials = (feedback_loop_trials * 3 + 3) / 4; } if hist_items > 100_000 { feedback_loop_trials = (feedback_loop_trials * 3 + 3) / 4; } feedback_loop_trials } /// `max_mse`, `target_mse`, user asked for perfect quality pub(crate) fn target_mse(&self, hist_items_len: usize) -> (Option, f64, bool) { let max_mse = self.max_mse.map(|mse| mse * if hist_items_len <= MAX_COLORS { 0.33 } else { 1. }); let aim_for_perfect_quality = self.target_mse == 0.; let mut target_mse = self.target_mse.max((f64::from(1 << self.min_posterization_output) / 1024.).powi(2)); if let Some(max_mse) = max_mse { target_mse = target_mse.min(max_mse); } (max_mse, target_mse, aim_for_perfect_quality) } /// returns iterations, `iteration_limit` #[must_use] pub(crate) fn kmeans_iterations(&self, hist_items_len: usize, palette_error_is_known: bool) -> (u16, f64) { let mut iteration_limit = self.kmeans_iteration_limit; let mut iterations = self.kmeans_iterations; if hist_items_len > 5000 { iterations = (iterations * 3 + 3) / 4; } if hist_items_len > 25000 { iterations = (iterations * 3 + 3) / 4; } if hist_items_len > 50000 { iterations = (iterations * 3 + 3) / 4; } if hist_items_len > 100_000 { iterations = (iterations * 3 + 3) / 4; iteration_limit *= 2.; } if iterations == 0 && !palette_error_is_known && self.max_mse.is_some() { iterations = 1; } (iterations, iteration_limit) } #[inline] #[must_use] pub(crate) fn posterize_bits(&self) -> u8 { self.min_posterization_output.max(self.min_posterization_input) } } impl Drop for Attributes { fn drop(&mut self) { self.verbose_printf_flush(); } } impl Default for Attributes { #[inline(always)] fn default() -> Self { Self::new() } } /// Result of callback in [`Attributes::set_progress_callback`] #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(C)] pub enum ControlFlow { /// Continue processing as normal Continue = 1, /// Abort processing and fail Break = 0, } #[test] fn counters() { let mut a = Attributes::new(); a.set_speed(10).unwrap(); let (iter, _) = a.kmeans_iterations(1000, false); assert_eq!(iter, 0); a.set_quality(80, 90).unwrap(); let (iter, limit) = a.kmeans_iterations(1000, false); assert_eq!(iter, 1); assert!(limit > 0. && limit < 0.01); let (iter, _) = a.kmeans_iterations(1000, true); assert_eq!(iter, 0); let mut a = Attributes::new(); a.set_quality(50, 80).unwrap(); let (max_mse, target_mse, aim_perfect) = a.target_mse(10000); let max_mse = max_mse.unwrap(); assert!(!aim_perfect); assert!(target_mse > 0. && target_mse < 0.01); assert!(max_mse > 0. && max_mse > target_mse && max_mse < 0.01); } #[test] fn getset() { let mut a = Attributes::new(); assert!(a.set_quality(0, 101).is_err()); assert!(a.set_quality(50, 49).is_err()); assert!(a.feedback_loop_trials(1000) > 0); let (max_mse, target_mse, aim_perfect) = a.target_mse(10000); assert!(aim_perfect); assert!(target_mse < 0.0001); assert_eq!(max_mse, None); a.set_speed(5).unwrap(); assert_eq!(5, a.speed()); assert!(a.set_speed(99).is_err()); assert!(a.set_speed(0).is_err()); a.set_max_colors(5).unwrap(); assert_eq!(5, a.max_colors()); assert!(a.set_max_colors(0).is_err()); a.set_min_posterization(2).unwrap(); assert_eq!(2, a.min_posterization()); assert_eq!(2, a.posterize_bits()); assert!(a.set_min_posterization(8).is_err()); let mut a = Attributes::new(); a.set_speed(10).unwrap(); assert_eq!(1, a.posterize_bits()); } libimagequant-4.4.0/src/blur.rs000066400000000000000000000054121503274717000164520ustar00rootroot00000000000000/// Blurs image horizontally (width 2*size+1) and writes it transposed to dst (called twice gives 2d blur) #[inline(never)] fn transposing_1d_blur(src: &[u8], dst: &mut [u8], width: usize, height: usize, size: u16) { if width < 2 * size as usize + 1 || height < 2 * size as usize + 1 { return; } for (j, row) in src.chunks_exact(width).enumerate() { let mut sum = u16::from(row[0]) * size; for &v in &row[0..size as usize] { sum += u16::from(v); } for i in 0..size as usize { sum -= u16::from(row[0]); sum += u16::from(row[i + size as usize]); dst[i * height + j] = (sum / (size * 2)) as u8; } for i in size as usize..width - size as usize { sum -= u16::from(row[i - size as usize]); sum += u16::from(row[i + size as usize]); dst[i * height + j] = (sum / (size * 2)) as u8; } for i in width - size as usize..width { sum -= u16::from(row[i - size as usize]); sum += u16::from(row[width - 1]); dst[i * height + j] = (sum / (size * 2)) as u8; } } } /// Picks maximum of neighboring pixels (blur + lighten) #[inline(never)] pub(crate) fn liq_max3(src: &[u8], dst: &mut [u8], width: usize, height: usize) { liq_op3(src, dst, width, height, |a, b| a.max(b)); } pub(crate) fn liq_op3(src: &[u8], dst: &mut [u8], width: usize, height: usize, op: impl Fn(u8, u8) -> u8) { for j in 0..height { let row = &src[j * width..][..width]; let dst = &mut dst[j * width..][..width]; let prevrow = &src[j.saturating_sub(1) * width..][..width]; let nextrow = &src[(j + 1).min(height - 1) * width..][..width]; let mut prev: u8; let mut curr = row[0]; let mut next = row[0]; for i in 0..width - 1 { prev = curr; curr = next; next = row[i + 1]; let t1 = op(prev, next); let t2 = op(nextrow[i], prevrow[i]); dst[i] = op(curr, op(t1, t2)); } let t1 = op(curr, next); let t2 = op(nextrow[width - 1], prevrow[width - 1]); dst[width - 1] = op(curr, op(t1, t2)); } } /// Picks minimum of neighboring pixels (blur + darken) #[inline(never)] pub(crate) fn liq_min3(src: &[u8], dst: &mut [u8], width: usize, height: usize) { liq_op3(src, dst, width, height, |a, b| a.min(b)); } /// Filters src image and saves it to dst, overwriting tmp in the process. /// Image must be width*height pixels high. Size controls radius of box blur. pub(crate) fn liq_blur(src_dst: &mut [u8], tmp: &mut [u8], width: usize, height: usize, size: u16) { transposing_1d_blur(src_dst, tmp, width, height, size); transposing_1d_blur(tmp, src_dst, height, width, size); } libimagequant-4.4.0/src/capi.rs000066400000000000000000000053751503274717000164320ustar00rootroot00000000000000//! These are internal unstable private helper methods for imagequant-sys. //! For public stable a C FFI interface, see imagequant-sys crate instead. #![allow(missing_docs)] #![allow(clippy::missing_safety_doc)] use crate::pal::Palette; use crate::rows::RowCallback; use crate::seacow::{Pointer, RowBitmapMut, SeaCow}; use crate::{Attributes, Error, Image, QuantizationResult, RGBA}; use std::mem::MaybeUninit; pub const LIQ_VERSION: u32 = 40202; #[must_use] pub fn liq_get_palette_impl(r: &mut QuantizationResult) -> &Palette { r.int_palette() } #[must_use] pub unsafe fn liq_image_create_rgba_rows_impl<'rows>(attr: &Attributes, rows: &'rows [*const RGBA], width: u32, height: u32, gamma: f64) -> Option> { let rows = SeaCow::borrowed(&*(rows as *const [*const rgb::Rgba] as *const [Pointer>])); let rows_slice = rows.as_slice(); if rows_slice.iter().any(|r| r.0.is_null()) { return None; } crate::image::Image::new_internal(attr, crate::rows::PixelsSource::Pixels { rows, pixels: None }, width, height, gamma).ok() } #[must_use] pub unsafe fn liq_image_create_rgba_bitmap_impl<'rows>(attr: &Attributes, rows: Box<[*const RGBA]>, width: u32, height: u32, gamma: f64) -> Option> { let rows = SeaCow::boxed(std::mem::transmute::, Box<[Pointer]>>(rows)); let rows_slice = rows.as_slice(); if rows_slice.iter().any(|r| r.0.is_null()) { return None; } crate::image::Image::new_internal(attr, crate::rows::PixelsSource::Pixels { rows, pixels: None }, width, height, gamma).ok() } #[must_use] pub unsafe fn liq_image_create_custom_impl<'rows>(attr: &Attributes, row_callback: Box>, width: u32, height: u32, gamma: f64) -> Option> { Image::new_internal(attr, crate::rows::PixelsSource::Callback(row_callback), width, height, gamma).ok() } pub unsafe fn liq_write_remapped_image_impl(result: &mut QuantizationResult, input_image: &mut Image, buffer_bytes: &mut [MaybeUninit]) -> Result<(), Error> { let rows = RowBitmapMut::new_contiguous(buffer_bytes, input_image.width()); result.write_remapped_image_rows_internal(input_image, rows) } pub unsafe fn liq_write_remapped_image_rows_impl(result: &mut QuantizationResult, input_image: &mut Image, rows: &mut [*mut MaybeUninit]) -> Result<(), Error> { let rows = RowBitmapMut::new(rows, input_image.width()); result.write_remapped_image_rows_internal(input_image, rows) } /// Not recommended pub unsafe fn liq_image_set_memory_ownership_impl(image: &mut Image<'_>, own_rows: bool, own_pixels: bool, free_fn: unsafe extern "C" fn(*mut std::os::raw::c_void)) -> Result<(), Error> { image.px.set_memory_ownership(own_rows, own_pixels, free_fn) } libimagequant-4.4.0/src/error.rs000066400000000000000000000037641503274717000166470ustar00rootroot00000000000000use std::collections::TryReserveError; use std::fmt; pub use Error::*; /// Error codes #[cfg_attr(feature = "_internal_c_ffi", repr(C))] #[cfg_attr(not(feature = "_internal_c_ffi"), non_exhaustive)] // it's meant to be always set, but Rust complains for a good but unrelated reason #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[allow(non_camel_case_types)] pub enum Error { /// Not an error. Exists for back-compat with the C API #[cfg(feature = "_internal_c_ffi")] LIQ_OK = 0, /// [`set_quality()`][crate::Attributes::set_quality] was used with a minimum quality, and the minimum could not be achieved QualityTooLow = 99, /// Function called with invalid arguments ValueOutOfRange = 100, /// Either the system/process really hit a limit, or some data like image size was ridiculously wrong. Could be a bug too OutOfMemory, /// Progress callback said to stop Aborted, /// Some terrible inconsistency happened InternalError, /// Slice needs to be bigger, or width/height needs to be smaller BufferTooSmall, /// NULL pointer or use-after-free in the C API InvalidPointer, /// Congratulations, you've discovered an edge case Unsupported, } impl std::error::Error for Error {} impl fmt::Display for Error { #[cold] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match *self { #[cfg(feature = "_internal_c_ffi")] Self::LIQ_OK => "OK", Self::QualityTooLow => "QUALITY_TOO_LOW", Self::ValueOutOfRange => "VALUE_OUT_OF_RANGE", Self::OutOfMemory => "OUT_OF_MEMORY", Self::Aborted => "ABORTED", Self::InternalError => "INTERNAL_ERROR", Self::BufferTooSmall => "BUFFER_TOO_SMALL", Self::InvalidPointer => "INVALID_POINTER", Self::Unsupported => "UNSUPPORTED", }) } } impl From for Error { #[cold] fn from(_: TryReserveError) -> Self { Self::OutOfMemory } } libimagequant-4.4.0/src/hist.rs000066400000000000000000000363231503274717000164620ustar00rootroot00000000000000use crate::error::*; use crate::image::Image; use crate::pal::{f_pixel, gamma_lut, PalIndex, ARGBF, MAX_COLORS, RGBA}; use crate::quant::QuantizationResult; use crate::rows::{temp_buf, DynamicRows}; use crate::Attributes; use std::collections::{HashMap, HashSet}; use std::fmt; use std::hash::Hash; /// Number of pixels in a given color for [`Histogram::add_colors()`] /// /// Used for building a histogram manually. Otherwise see [`Histogram::add_image()`] #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct HistogramEntry { /// The color pub color: RGBA, /// Importance of the color (e.g. number of occurrences) pub count: u32, } /// Generate one shared palette for multiple images /// /// If you're converting one image at a time, see [`Attributes::new_image`] instead pub struct Histogram { gamma: Option, fixed_colors: FixedColorsSet, /// The key is the RGBA cast to u32 /// The value is a (boosted) count or 0 if it's a fixed color hashmap: HashMap, posterize_bits: u8, max_histogram_entries: u32, } pub(crate) type FixedColorsSet = HashSet; #[derive(Clone)] pub(crate) struct HistItem { pub color: f_pixel, pub adjusted_weight: f32, pub perceptual_weight: f32, /// temporary in median cut pub mc_color_weight: f32, pub tmp: HistSortTmp, } impl HistItem { // Safety: just an int, and it's been initialized when constructing the object #[inline(always)] pub fn mc_sort_value(&self) -> u32 { unsafe { self.tmp.mc_sort_value } } // The u32 has been initialized when constructing the object, and u8/u16 is smaller than that #[inline(always)] pub fn likely_palette_index(&self) -> PalIndex { assert!(std::mem::size_of::() <= std::mem::size_of::()); unsafe { self.tmp.likely_palette_index } } } impl fmt::Debug for HistItem { #[cold] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("HistItem") .field("color", &self.color) .field("adjusted_weight", &self.adjusted_weight) .field("perceptual_weight", &self.perceptual_weight) .field("color_weight", &self.mc_color_weight) .finish() } } #[repr(C)] #[derive(Clone, Copy)] pub union HistSortTmp { pub mc_sort_value: u32, pub likely_palette_index: PalIndex, } impl Histogram { /// Creates histogram object that will be used to collect color statistics from multiple images. /// /// All options should be set on `attr` before the histogram object is created. Options changed later may not have effect. #[inline] #[must_use] pub fn new(attr: &Attributes) -> Self { Self { posterize_bits: attr.posterize_bits(), max_histogram_entries: attr.max_histogram_entries, fixed_colors: HashSet::with_hasher(U32Hasher(0)), hashmap: HashMap::with_hasher(U32Hasher(0)), gamma: None, } } /// "Learns" colors from the image, which will be later used to generate the palette. /// /// Fixed colors added to the image are also added to the histogram. If the total number of fixed colors exceeds 256, /// this function will fail with `LIQ_BUFFER_TOO_SMALL`. #[inline(never)] pub fn add_image(&mut self, attr: &Attributes, image: &mut Image) -> Result<(), Error> { let width = image.width(); let height = image.height(); if image.importance_map.is_none() && attr.use_contrast_maps { image.contrast_maps()?; } self.gamma = image.gamma(); if !image.fixed_colors.is_empty() { self.fixed_colors.extend(image.fixed_colors.iter().copied().enumerate().map(|(idx, rgba)| { HashColor { rgba, index: idx as _ } })); } if attr.progress(f32::from(attr.progress_stage1) * 0.40) { return Err(Aborted); // bow can free the RGBA source if copy has been made in f_pixels } let posterize_bits = attr.posterize_bits(); let surface_area = height * width; let estimated_colors = (surface_area / (posterize_bits as usize + if surface_area > 512 * 512 { 7 } else { 5 })).min(250_000); self.reserve(estimated_colors); self.add_pixel_rows(&image.px, image.importance_map.as_deref(), posterize_bits)?; Ok(()) } /// Alternative to `add_image()`. Intead of counting colors in an image, it directly takes an array of colors and their counts. /// /// This function is only useful if you already have a histogram of the image from another source. /// /// The gamma may be 0 to mean sRGB. All calls to `add_colors` and `add_fixed_color` should use the same gamma value. #[inline(never)] pub fn add_colors(&mut self, entries: &[HistogramEntry], gamma: f64) -> Result<(), Error> { if entries.is_empty() || entries.len() > 1 << 24 { return Err(ValueOutOfRange); } if !(0. ..1.).contains(&gamma) { return Err(ValueOutOfRange); } if self.gamma.is_none() && gamma > 0. { self.gamma = Some(gamma); } self.reserve(entries.len()); for e in entries { self.add_color(e.color, e.count); } Ok(()) } /// Add a color guaranteed to be in the final palette /// /// The gamma may be 0 to mean sRGB. All calls to `add_colors` and `add_fixed_color` should use the same gamma value. pub fn add_fixed_color(&mut self, rgba: RGBA, gamma: f64) -> Result<(), Error> { if self.fixed_colors.len() >= MAX_COLORS { return Err(Unsupported); } if self.gamma.is_none() && gamma > 0. { self.gamma = Some(gamma); } let idx = self.fixed_colors.len(); self.fixed_colors.insert(HashColor { rgba, index: idx as _ }); Ok(()) } /// Generate palette for all images/colors added to the histogram. /// /// Palette generated using this function won't be improved during remapping. /// If you're generating palette for only one image, it's better not to use the `Histogram`. #[inline] pub fn quantize(&mut self, attr: &Attributes) -> Result { self.quantize_internal(attr, true) } #[inline(never)] pub(crate) fn quantize_internal(&mut self, attr: &Attributes, freeze_result_colors: bool) -> Result { if self.hashmap.is_empty() && self.fixed_colors.is_empty() { return Err(Unsupported); } if attr.progress(0.) { return Err(Aborted); } if attr.progress(f32::from(attr.progress_stage1) * 0.89) { return Err(Aborted); } let gamma = self.gamma.unwrap_or(0.45455); let hist = self.finalize_builder(gamma).map_err(|_| OutOfMemory)?; attr.verbose_print(format!(" made histogram...{} colors found", hist.items.len())); QuantizationResult::new(attr, hist, freeze_result_colors, gamma) } #[inline(always)] fn add_color(&mut self, rgba: RGBA, boost: u32) { if boost == 0 { return; } let px_int = if rgba.a != 0 { self.posterize_mask() & unsafe { RGBAInt { rgba }.int } } else { 0 }; self.hashmap.entry(px_int) // it can overflow on images over 2^24 pixels large .and_modify(move |e| e.0 = e.0.saturating_add(boost)) .or_insert((boost, rgba)); } fn reserve(&mut self, entries: usize) { let new_entries = entries.saturating_sub(self.hashmap.len() / 3); // assume some will be dupes, if called multiple times self.hashmap.reserve(new_entries); } #[inline(always)] const fn posterize_mask(&self) -> u32 { let channel_mask = 255 << self.posterize_bits; u32::from_ne_bytes([channel_mask, channel_mask, channel_mask, channel_mask]) } /// optionallys et fn init_posterize_bits(&mut self, posterize_bits: u8) { if self.posterize_bits >= posterize_bits { return; } self.posterize_bits = posterize_bits; let new_posterize_mask = self.posterize_mask(); let new_size = (self.hashmap.len() / 3).max(self.hashmap.capacity() / 5); let old_hashmap = std::mem::replace(&mut self.hashmap, HashMap::with_capacity_and_hasher(new_size, U32Hasher(0))); self.hashmap.extend(old_hashmap.into_iter().map(move |(k, v)| { (k & new_posterize_mask, v) })); } pub(crate) fn add_pixel_rows(&mut self, image: &DynamicRows<'_, '_>, importance_map: Option<&[u8]>, posterize_bits: u8) -> Result<(), Error> { let width = image.width as usize; let height = image.height as usize; debug_assert!(importance_map.map_or(true, |m| m.len() == image.width() * image.height())); let mut importance_map = importance_map.unwrap_or(&[]).chunks_exact(width).fuse(); let image_iter = image.rgba_rows_iter()?; let mut temp_row = temp_buf(width)?; for row in 0..height { let pixels_row = &image_iter.row_rgba(&mut temp_row, row)[..width]; let importance_map = importance_map.next().map(move |m| &m[..width]).unwrap_or(&[]); for (col, px) in pixels_row.iter().copied().enumerate() { let boost = importance_map.get(col).copied().unwrap_or(255); self.add_color(px, boost.into()); } } self.init_posterize_bits(posterize_bits); if self.hashmap.len() > self.max_histogram_entries as usize && self.posterize_bits < 3 { self.init_posterize_bits(self.posterize_bits + 1); } Ok(()) } pub(crate) fn finalize_builder(&mut self, gamma: f64) -> Result { debug_assert!(gamma > 0.); // Fixed colors will be put into normal hashmap, but with very high weight, // and temporarily 0 means this fixed max weight for &HashColor { rgba, .. } in &self.fixed_colors { let px_int = if rgba.a != 0 { unsafe { RGBAInt { rgba }.int } } else { 0 }; self.hashmap.insert(px_int, (0, rgba)); } let mut temp = Vec::new(); temp.try_reserve_exact(self.hashmap.len())?; let mut counts = [0; LIQ_MAXCLUSTER]; temp.extend(self.hashmap.values().map(|&(boost, color)| { let cluster_index = ((color.r >> 7) << 3) | ((color.g >> 7) << 2) | ((color.b >> 7) << 1) | (color.a >> 7); counts[cluster_index as usize] += 1; // fixed colors result in weight == 0. let weight = boost as f32; TempHistItem { color, weight, cluster_index } })); let mut clusters = [Cluster { begin: 0, end: 0 }; LIQ_MAXCLUSTER]; let mut next_begin = 0; for (cluster, count) in clusters.iter_mut().zip(counts) { cluster.begin = next_begin; cluster.end = next_begin; next_begin += count; } let mut items = Vec::new(); items.try_reserve_exact(temp.len())?; items.resize(temp.len(), HistItem { color: if cfg!(debug_assertions) { f_pixel( ARGBF { r:f32::NAN, g:f32::NAN, b:f32::NAN, a:f32::NAN } ) } else { f_pixel::default() }, adjusted_weight: if cfg!(debug_assertions) { f32::NAN } else { 0. }, perceptual_weight: if cfg!(debug_assertions) { f32::NAN } else { 0. }, mc_color_weight: if cfg!(debug_assertions) { f32::NAN } else { 0. }, tmp: HistSortTmp { mc_sort_value: if cfg!(debug_assertions) { !0 } else { 0 } }, }); let mut items = items.into_boxed_slice(); // Limit perceptual weight to 1/10th of the image surface area to prevent // a single color from dominating all others. let max_perceptual_weight = 0.1 * (temp.iter().map(|t| f64::from(t.weight)).sum::() / 256.) as f32; let lut = gamma_lut(gamma); let mut total_perceptual_weight = 0.; for temp_item in temp { let cluster = &mut clusters[temp_item.cluster_index as usize]; let next_index = cluster.end as usize; cluster.end += 1; // weight == 0 means it's a fixed color let weight = if temp_item.weight > 0. { (temp_item.weight * (1. / 256.)).min(max_perceptual_weight) } else { max_perceptual_weight * 10. }; total_perceptual_weight += f64::from(weight); items[next_index].color = f_pixel::from_rgba(&lut, temp_item.color); items[next_index].perceptual_weight = weight; items[next_index].adjusted_weight = weight; } let mut fixed_colors: Vec<_> = self.fixed_colors.iter().collect(); fixed_colors.sort_by_key(|c| c.index); // original order let fixed_colors = fixed_colors.iter().map(|c| f_pixel::from_rgba(&lut, c.rgba)).collect(); Ok(HistogramInternal { items, total_perceptual_weight, clusters, fixed_colors }) } } #[derive(Copy, Clone)] struct TempHistItem { color: RGBA, weight: f32, cluster_index: u8, } #[repr(C)] union RGBAInt { rgba: RGBA, int: u32, } /// Clusters form initial boxes for quantization, to ensure extreme colors are better represented pub const LIQ_MAXCLUSTER: usize = 16; pub(crate) struct HistogramInternal { pub items: Box<[HistItem]>, pub total_perceptual_weight: f64, pub clusters: [Cluster; LIQ_MAXCLUSTER], pub fixed_colors: Box<[f_pixel]>, } // Pre-grouped colors #[derive(Copy, Clone, Debug)] pub(crate) struct Cluster { pub begin: u32, pub end: u32, } // Simple deterministic hasher for the color hashmap impl std::hash::BuildHasher for U32Hasher { type Hasher = Self; #[inline(always)] fn build_hasher(&self) -> Self { Self(0) } } pub(crate) struct U32Hasher(pub u32); impl std::hash::Hasher for U32Hasher { // magic constant from fxhash. For a single 32-bit key that's all it needs! #[inline(always)] fn finish(&self) -> u64 { u64::from(self.0).wrapping_mul(0x517cc1b727220a95) } #[inline(always)] fn write_u32(&mut self, i: u32) { self.0 = i; } fn write(&mut self, _bytes: &[u8]) { unimplemented!() } fn write_u8(&mut self, _i: u8) { unimplemented!() } fn write_u16(&mut self, _i: u16) { unimplemented!() } fn write_u64(&mut self, _i: u64) { unimplemented!() } fn write_u128(&mut self, _i: u128) { unimplemented!() } fn write_usize(&mut self, _i: usize) { unimplemented!() } fn write_i8(&mut self, _i: i8) { unimplemented!() } fn write_i16(&mut self, _i: i16) { unimplemented!() } fn write_i32(&mut self, _i: i32) { unimplemented!() } fn write_i64(&mut self, _i: i64) { unimplemented!() } fn write_i128(&mut self, _i: i128) { unimplemented!() } fn write_isize(&mut self, _i: isize) { unimplemented!() } } /// ignores the index #[derive(PartialEq, Debug)] pub(crate) struct HashColor { pub rgba: RGBA, pub index: PalIndex, } #[allow(clippy::derived_hash_with_manual_eq)] impl Hash for HashColor { #[inline] fn hash(&self, state: &mut H) { let s: &[u8] = self.rgba.as_ref(); u32::from_ne_bytes(s.try_into().unwrap()).hash(state); } } impl Eq for HashColor { fn assert_receiver_is_total_eq(&self) {} } libimagequant-4.4.0/src/image.rs000066400000000000000000000361171503274717000165760ustar00rootroot00000000000000use crate::attr::Attributes; use crate::blur::{liq_blur, liq_max3, liq_min3}; use crate::error::*; use crate::pal::{f_pixel, PalF, PalIndexRemap, MAX_COLORS, MIN_OPAQUE_A, RGBA}; use crate::remap::DitherMapMode; use crate::rows::{DynamicRows, PixelsSource}; use crate::seacow::{RowBitmap, SeaCow}; use crate::{PushInCapacity, LIQ_HIGH_MEMORY_LIMIT}; use rgb::prelude::*; use std::mem::MaybeUninit; /// Describes image dimensions and pixels for the library /// /// Create one using [`Attributes::new_image()`]. /// /// All images are internally in the RGBA format. #[derive(Clone)] pub struct Image<'pixels> { pub(crate) px: DynamicRows<'pixels, 'pixels>, pub(crate) importance_map: Option>, pub(crate) edges: Option>, pub(crate) dither_map: Option>, pub(crate) background: Option>>, pub(crate) fixed_colors: Vec, } impl<'pixels> Image<'pixels> { /// Makes an image from RGBA pixels. /// /// See the [`rgb`] and [`bytemuck`](https://lib.rs/bytemuck) crates for making `[RGBA]` slices from `[u8]` slices. /// /// The `pixels` argument can be `Vec`, or `Box<[RGBA]>` or `&[RGBA]`. /// /// If you want to supply RGB or ARGB pixels, convert them to RGBA first, or use [`Image::new_fn`] to supply your own pixel-swapping function. /// /// Use `0.` for gamma if the image is sRGB (most images are). #[inline(always)] pub fn new(attr: &Attributes, pixels: VecRGBA, width: usize, height: usize, gamma: f64) -> Result where VecRGBA: Into> { Self::new_stride(attr, pixels, width, height, width, gamma) } /// Describe dimensions of a slice of RGBA pixels. /// /// Same as [`Image::new`], except it doesn't copy the pixels, but holds a temporary reference instead. /// /// If you want to supply RGB or ARGB pixels, use [`Image::new_fn`] to supply your own pixel-swapping function. /// /// See the [`rgb`] and [`bytemuck`](https://lib.rs/bytemuck) crates for making `[RGBA]` slices from `[u8]` slices. /// /// Use `0.` for gamma if the image is sRGB (most images are). #[inline(always)] pub fn new_borrowed(attr: &Attributes, pixels: &'pixels [RGBA], width: usize, height: usize, gamma: f64) -> Result { Self::new_stride_borrowed(attr, pixels, width, height, width, gamma) } /// Generate rows on demand using a callback function. /// /// The callback function should be cheap (e.g. just byte-swap pixels). The parameters are: line of RGBA pixels (slice's len is equal to image width), and row number (0-indexed). /// The callback will be called multiple times per row. May be called from multiple threads at once. /// /// Use `0.` for gamma if the image is sRGB (most images are). /// /// ## Safety /// /// This function is marked as unsafe, because the callback function MUST initialize the entire row (call `write` on every `MaybeUninit` pixel). /// pub unsafe fn new_fn], usize) + Send + Sync>(attr: &Attributes, convert_row_fn: F, width: usize, height: usize, gamma: f64) -> Result { let width = width.try_into().map_err(|_| ValueOutOfRange)?; let height = height.try_into().map_err(|_| ValueOutOfRange)?; Image::new_internal(attr, PixelsSource::Callback(Box::new(convert_row_fn)), width, height, gamma) } pub(crate) fn free_histogram_inputs(&mut self) { // importance_map must stay for remapping, because remap performs kmeans on potentially-unimportant pixels self.px.free_histogram_inputs(); } pub(crate) fn new_internal( attr: &Attributes, pixels: PixelsSource<'pixels, 'pixels>, width: u32, height: u32, gamma: f64, ) -> Result { if !Self::check_image_size(width, height) { return Err(ValueOutOfRange); } if !(0. ..=1.).contains(&gamma) { attr.verbose_print(" error: gamma must be >= 0 and <= 1 (try 1/gamma instead)"); return Err(ValueOutOfRange); } let img = Image { px: DynamicRows::new( width, height, pixels, if gamma > 0. { gamma } else { 0.45455 }, ), importance_map: None, edges: None, dither_map: None, background: None, fixed_colors: Vec::new(), }; // if image is huge or converted pixels are not likely to be reused then don't cache converted pixels let low_memory_hint = !attr.use_contrast_maps && attr.use_dither_map == DitherMapMode::None; let limit = if low_memory_hint { LIQ_HIGH_MEMORY_LIMIT / 8 } else { LIQ_HIGH_MEMORY_LIMIT } / std::mem::size_of::(); if (img.width()) * (img.height()) > limit { attr.verbose_print(" conserving memory"); // for simplicity of this API there's no explicit pixels argument, } Ok(img) } fn check_image_size(width: u32, height: u32) -> bool { if width == 0 || height == 0 { return false; } if width.max(height) as usize > i32::MAX as usize || width as usize > isize::MAX as usize / std::mem::size_of::() / height as usize { return false; } true } pub(crate) fn update_dither_map(&mut self, remapped_image: &RowBitmap<'_, PalIndexRemap>, palette: &PalF, uses_background: bool) -> Result<(), Error> { if self.edges.is_none() { self.contrast_maps()?; } let Some(mut edges) = self.edges.take() else { return Ok(()) }; let colors = palette.as_slice(); let width = self.width(); let mut prev_row: Option<&[_]> = None; let mut rows = remapped_image.rows().zip(edges.chunks_exact_mut(width)).peekable(); while let Some((this_row, edges)) = rows.next() { let mut lastpixel = this_row[0]; let mut lastcol = 0; for (col, px) in this_row.iter().copied().enumerate().skip(1) { if uses_background && (colors[px as usize]).a < MIN_OPAQUE_A { // Transparency may or may not create an edge. When there's an explicit background set, assume no edge. continue; } if px != lastpixel || col == width - 1 { let mut neighbor_count = 10 * (col - lastcol); let mut i = lastcol; while i < col { if let Some(prev_row) = prev_row { let pixelabove = prev_row[i]; if pixelabove == lastpixel { neighbor_count += 15; } } if let Some((next_row, _)) = rows.peek() { let pixelbelow = next_row[i]; if pixelbelow == lastpixel { neighbor_count += 15; } } i += 1; } while lastcol <= col { edges[lastcol] = (f32::from(u16::from(edges[lastcol]) + 128) * (255. / (255 + 128) as f32) * (1. - 20. / (20 + neighbor_count) as f32)) as u8; lastcol += 1; } lastpixel = px; } } prev_row = Some(this_row); } self.dither_map = Some(edges); Ok(()) } /// Set which pixels are more important (and more likely to get a palette entry) /// /// The map must be `width`×`height` pixels large. Higher numbers = more important. pub fn set_importance_map(&mut self, map: impl Into>) -> Result<(), Error> { let map = map.into(); if map.len() != self.width() * self.height() { return Err(BufferTooSmall); } self.importance_map = Some(map); Ok(()) } /// Remap pixels assuming they will be displayed on this background. This is designed for GIF's "keep" mode. /// /// Pixels that match the background color will be made transparent if there's a fully transparent color available in the palette. /// /// The background image's pixels must outlive this image. pub fn set_background(&mut self, background: Self) -> Result<(), Error> { if background.background.is_some() { return Err(Unsupported); } if self.px.width != background.px.width || self.px.height != background.px.height { return Err(BufferTooSmall); } self.background = Some(Box::new(background)); Ok(()) } /// Reserves a color in the output palette created from this image. It behaves as if the given color was used in the image and was very important. /// /// The RGB values are assumed to have the same gamma as the image. /// /// It must be called before the image is quantized. /// /// Returns error if more than 256 colors are added. If image is quantized to fewer colors than the number of fixed colors added, then excess fixed colors will be ignored. pub fn add_fixed_color(&mut self, color: RGBA) -> Result<(), Error> { if self.fixed_colors.len() >= MAX_COLORS { return Err(Unsupported); } self.fixed_colors.try_reserve(1)?; self.fixed_colors.push_in_cap(color); Ok(()) } /// Width of the image in pixels #[must_use] #[inline(always)] pub const fn width(&self) -> usize { self.px.width as _ } /// Height of the image in pixels #[must_use] #[inline(always)] pub const fn height(&self) -> usize { self.px.height as _ } #[inline(always)] pub(crate) fn gamma(&self) -> Option { if self.px.gamma > 0. { Some(self.px.gamma) } else { None } } /// Builds two maps: /// `importance_map` - approximation of areas with high-frequency noise, except straight edges. 1=flat, 0=noisy. /// edges - noise map including all edges pub(crate) fn contrast_maps(&mut self) -> Result<(), Error> { let width = self.width(); let height = self.height(); if width < 4 || height < 4 || (3 * width * height) > LIQ_HIGH_MEMORY_LIMIT { return Ok(()); // shrug } let noise = if let Some(n) = self.importance_map.as_deref_mut() { n } else { let vec = try_zero_vec(width * height)?; self.importance_map.get_or_insert_with(move || vec.into_boxed_slice()) }; let edges = if let Some(e) = self.edges.as_mut() { e } else { let vec = try_zero_vec(width * height)?; self.edges.get_or_insert_with(move || vec.into_boxed_slice()) }; let mut rows_iter = self.px.all_rows_f()?.chunks_exact(width); let mut next_row = rows_iter.next().ok_or(Error::InvalidPointer)?; let mut curr_row = next_row; let mut prev_row; for (noise_row, edges_row) in noise[..width * height].chunks_exact_mut(width).zip(edges[..width * height].chunks_exact_mut(width)) { prev_row = curr_row; curr_row = next_row; next_row = rows_iter.next().unwrap_or(next_row); let mut prev; let mut curr = curr_row[0].0; let mut next = curr; for i in 0..width { prev = curr; curr = next; next = curr_row[(i + 1).min(width - 1)].0; // contrast is difference between pixels neighbouring horizontally and vertically let horiz = (prev + next - curr * 2.).map(f32::abs); // noise is amplified let prevl = prev_row[i].0; let nextl = next_row[i].0; let vert = (prevl + nextl - curr * 2.).map(f32::abs); let horiz = horiz.a.max(horiz.r).max(horiz.g.max(horiz.b)); let vert = vert.a.max(vert.r).max(vert.g.max(vert.b)); let edge = horiz.max(vert); let mut z = (horiz - vert).abs().mul_add(-0.5, edge); z = 1. - z.max(horiz.min(vert)); z *= z; z *= z; // 85 is about 1/3rd of weight (not 0, because noisy pixels still need to be included, just not as precisely). noise_row[i] = z.mul_add(176., 80.) as u8; edges_row[i] = ((1. - edge) * 256.) as u8; } } // noise areas are shrunk and then expanded to remove thin edges from the map let mut tmp = try_zero_vec(width * height)?; liq_max3(noise, &mut tmp, width, height); liq_max3(&tmp, noise, width, height); liq_blur(noise, &mut tmp, width, height, 3); liq_max3(noise, &mut tmp, width, height); liq_min3(&tmp, noise, width, height); liq_min3(noise, &mut tmp, width, height); liq_min3(&tmp, noise, width, height); liq_min3(edges, &mut tmp, width, height); liq_max3(&tmp, edges, width, height); for (edges, noise) in edges.iter_mut().zip(noise) { *edges = (*noise).min(*edges); } Ok(()) } /// Stride is in pixels. Allows defining regions of larger images or images with padding without copying. The stride is in pixels. /// /// Otherwise the same as [`Image::new_borrowed`]. #[inline(always)] pub fn new_stride_borrowed(attr: &Attributes, pixels: &'pixels [RGBA], width: usize, height: usize, stride: usize, gamma: f64) -> Result { Self::new_stride_internal(attr, SeaCow::borrowed(pixels), width, height, stride, gamma) } /// Create new image by copying `pixels` to an internal buffer, so that it makes a self-contained type. /// /// The `pixels` argument can be `Vec`, or `Box<[RGBA]>` or `&[RGBA]`. /// /// Otherwise the same as [`Image::new_stride_borrowed`]. #[inline] pub fn new_stride(attr: &Attributes, pixels: VecRGBA, width: usize, height: usize, stride: usize, gamma: f64) -> Result, Error> where VecRGBA: Into> { Self::new_stride_internal(attr, SeaCow::boxed(pixels.into()), width, height, stride, gamma) } fn new_stride_internal<'a>(attr: &Attributes, pixels: SeaCow<'a, RGBA>, width: usize, height: usize, stride: usize, gamma: f64) -> Result, Error> { let width = width.try_into().map_err(|_| ValueOutOfRange)?; let height = height.try_into().map_err(|_| ValueOutOfRange)?; let stride = stride.try_into().map_err(|_| ValueOutOfRange)?; let pixels_len = pixels.as_slice().len(); let pixels_rows = match PixelsSource::for_pixels(pixels, width, height, stride) { Ok(p) => p, Err(e) => { attr.verbose_print(format!("Buffer length is {} bytes, which is not enough for {}×{}×4 RGBA bytes", pixels_len * 4, stride, height)); return Err(e); }, }; Image::new_internal(attr, pixels_rows, width, height, gamma) } } fn try_zero_vec(len: usize) -> Result, Error> { let mut vec = Vec::new(); vec.try_reserve_exact(len)?; vec.resize(len, 0); Ok(vec) } libimagequant-4.4.0/src/kmeans.rs000066400000000000000000000131001503274717000167550ustar00rootroot00000000000000use crate::hist::{HistItem, HistogramInternal}; use crate::nearest::Nearest; use crate::pal::{f_pixel, PalF, PalIndex, PalPop}; use crate::rayoff::*; use crate::{CacheLineAlign, Error}; use rgb::prelude::*; use rgb::Argb; use std::cell::RefCell; /// K-Means iteration: new palette color is computed from weighted average of colors that map best to that palette entry. // avoid false sharing pub(crate) struct Kmeans { averages: Vec, weighed_diff_sum: f64, } #[derive(Copy, Clone, Default)] struct ColorAvg { pub sum: Argb, pub total: f64, } impl Kmeans { #[inline] pub fn new(pal_len: usize) -> Result { let mut averages = Vec::new(); averages.try_reserve_exact(pal_len)?; averages.resize(pal_len, ColorAvg::default()); Ok(Self { averages, weighed_diff_sum: 0., }) } #[inline] pub fn update_color(&mut self, px: f_pixel, value: f32, matched: PalIndex) { let c = &mut self.averages[matched as usize]; c.sum += (px.0 * value).map(f64::from); c.total += f64::from(value); } pub fn finalize(self, palette: &mut PalF) -> f64 { for (avg, (color, pop)) in self.averages.iter().zip(palette.iter_mut()).filter(|(_, (_, pop))| !pop.is_fixed()) { let total = avg.total; *pop = PalPop::new(total as f32); if total > 0. && color.a != 0. { *color = avg.sum.map(move |c| (c / total) as f32).into(); } } self.weighed_diff_sum } #[inline(never)] pub(crate) fn iteration(hist: &mut HistogramInternal, palette: &mut PalF, adjust_weight: bool) -> Result { if hist.items.is_empty() { return Ok(0.); } let n = Nearest::new(palette)?; let colors = palette.as_slice(); let len = colors.len(); let tls = ThreadLocal::new(); let total = hist.total_perceptual_weight; // chunk size is a trade-off between parallelization and overhead hist.items.par_chunks_mut(256).for_each({ let tls = &tls; move |batch| { let kmeans = tls.get_or(move || CacheLineAlign(RefCell::new(Self::new(len)))); if let Ok(ref mut kmeans) = *kmeans.0.borrow_mut() { kmeans.iterate_batch(batch, &n, colors, adjust_weight); } } }); let diff = tls.into_iter() .map(|c| c.0.into_inner()) .reduce(Self::try_merge) .transpose()? .map_or(0., |kmeans| kmeans.finalize(palette) / total); replace_unused_colors(palette, hist)?; Ok(diff) } fn iterate_batch(&mut self, batch: &mut [HistItem], n: &Nearest, colors: &[f_pixel], adjust_weight: bool) { self.weighed_diff_sum += batch.iter_mut().map(|item| { let px = item.color; let (matched, mut diff) = n.search(&px, item.likely_palette_index()); item.tmp.likely_palette_index = matched; if adjust_weight { let remapped = colors[matched as usize]; let (_, new_diff) = n.search(&f_pixel(px.0 + px.0 - remapped.0), matched); diff = new_diff; item.adjusted_weight = 2.0f32.mul_add(item.adjusted_weight, item.perceptual_weight) * (0.5 + diff); } debug_assert!(f64::from(diff) < 1e20); self.update_color(px, item.adjusted_weight, matched); f64::from(diff * item.perceptual_weight) }).sum::(); } #[inline] pub fn merge(mut self, new: Self) -> Self { self.weighed_diff_sum += new.weighed_diff_sum; self.averages.iter_mut().zip(new.averages).for_each(|(p, n)| { p.sum += n.sum; p.total += n.total; }); self } #[inline] pub fn try_merge(old: Result, new: Result) -> Result { match (old, new) { (Ok(old), Ok(new)) => Ok(Self::merge(old, new)), (Err(e), _) | (_, Err(e)) => Err(e), } } } /// kmeans may have merged or obsoleted some palette entries. /// This replaces these entries with histogram colors that are currently least-fitting the palette. fn replace_unused_colors(palette: &mut PalF, hist: &HistogramInternal) -> Result<(), Error> { for pal_idx in 0..palette.len() { let Some(pop) = palette.pop_as_slice().get(pal_idx) else { break }; if pop.popularity() == 0. && !pop.is_fixed() { let n = Nearest::new(palette)?; let mut worst = None; let mut worst_diff = 0.; let colors = palette.as_slice(); // the search is just for diff, ignoring adjusted_weight, // because the palette already optimizes for the max weight, so it'd likely find another redundant entry. for item in hist.items.iter() { // the early reject avoids running full palette search for every entry let may_be_worst = colors.get(item.likely_palette_index() as usize) .map_or(true, |pal| pal.diff(&item.color) > worst_diff); if may_be_worst { let diff = n.search(&item.color, item.likely_palette_index()).1; if diff > worst_diff { worst_diff = diff; worst = Some(item); } } } if let Some(worst) = worst { palette.set(pal_idx, worst.color, PalPop::new(worst.adjusted_weight)); } } } Ok(()) } libimagequant-4.4.0/src/lib.rs000066400000000000000000000234521503274717000162600ustar00rootroot00000000000000//! //! //! Converts RGBA images to 8-bit with alpha channel. //! //! See `examples/` directory for example code. #![doc(html_logo_url = "https://pngquant.org/pngquant-logo.png")] #![deny(missing_docs)] #![allow(clippy::bool_to_int_with_if)] #![allow(clippy::cast_possible_truncation)] #![allow(clippy::doc_markdown)] #![allow(clippy::if_not_else)] #![allow(clippy::inline_always)] #![allow(clippy::items_after_statements)] #![allow(clippy::map_unwrap_or)] #![allow(clippy::missing_errors_doc)] #![allow(clippy::module_name_repetitions)] #![allow(clippy::redundant_closure_for_method_calls)] #![allow(clippy::unreadable_literal)] #![allow(clippy::wildcard_imports)] #![deny(clippy::semicolon_if_nothing_returned)] mod attr; mod blur; mod error; mod hist; mod image; mod kmeans; mod mediancut; mod nearest; mod pal; mod quant; mod remap; mod rows; mod seacow; #[cfg(not(feature = "threads"))] mod rayoff; #[cfg(feature = "threads")] mod rayoff { pub(crate) fn num_cpus() -> usize { std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1) } pub(crate) use rayon::prelude::{ParallelBridge, ParallelIterator, ParallelSliceMut}; pub(crate) use rayon::in_place_scope as scope; pub(crate) use thread_local::ThreadLocal; } #[cfg_attr(feature = "threads", repr(align(128)))] pub(crate) struct CacheLineAlign(pub T); /// Use imagequant-sys crate instead #[cfg(feature = "_internal_c_ffi")] pub mod capi; pub use attr::{Attributes, ControlFlow}; pub use error::Error; pub use hist::{Histogram, HistogramEntry}; pub use image::Image; #[doc(hidden)] pub use pal::Palette; pub use pal::RGBA; pub use quant::QuantizationResult; #[doc(hidden)] #[deprecated(note = "Please use the imagequant::Error type. This will be removed")] pub use error::Error as liq_error; const LIQ_HIGH_MEMORY_LIMIT: usize = 1 << 26; /// [Start here][Attributes]: creates new handle for library configuration /// /// See [`Attributes`] #[inline(always)] #[must_use] pub fn new() -> Attributes { Attributes::new() } #[test] fn copy_img() { let tmp = vec![RGBA::new(1, 2, 3, 4); 10 * 100]; let liq = Attributes::new(); let _ = liq.new_image_stride(tmp, 10, 100, 10, 0.).unwrap(); } #[test] fn takes_rgba() { let liq = Attributes::new(); let img = vec![RGBA { r: 0, g: 0, b: 0, a: 0 }; 8]; liq.new_image_borrowed(&img, 1, 1, 0.0).unwrap(); liq.new_image_borrowed(&img, 4, 2, 0.0).unwrap(); liq.new_image_borrowed(&img, 8, 1, 0.0).unwrap(); assert!(liq.new_image_borrowed(&img, 9, 1, 0.0).is_err()); assert!(liq.new_image_borrowed(&img, 4, 3, 0.0).is_err()); } #[test] fn histogram() { let attr = Attributes::new(); let mut hist = Histogram::new(&attr); let bitmap1 = [RGBA { r: 0, g: 0, b: 0, a: 0 }; 1]; let mut image1 = attr.new_image(&bitmap1[..], 1, 1, 0.0).unwrap(); hist.add_image(&attr, &mut image1).unwrap(); let bitmap2 = [RGBA { r: 255, g: 255, b: 255, a: 255 }; 1]; let mut image2 = attr.new_image(&bitmap2[..], 1, 1, 0.0).unwrap(); hist.add_image(&attr, &mut image2).unwrap(); hist.add_colors(&[HistogramEntry { color: RGBA::new(255, 128, 255, 128), count: 10, }], 0.0).unwrap(); let mut res = hist.quantize(&attr).unwrap(); let pal = res.palette(); assert_eq!(3, pal.len()); } #[test] fn poke_it() { let width = 10usize; let height = 10usize; let mut fakebitmap = vec![RGBA::new(255, 255, 255, 255); width * height]; fakebitmap[0].r = 0x55; fakebitmap[0].g = 0x66; fakebitmap[0].b = 0x77; // Configure the library let mut liq = Attributes::new(); liq.set_speed(5).unwrap(); liq.set_quality(70, 99).unwrap(); liq.set_min_posterization(1).unwrap(); assert_eq!(1, liq.min_posterization()); liq.set_min_posterization(0).unwrap(); use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst; use std::sync::Arc; let log_called = Arc::new(AtomicBool::new(false)); let log_called2 = log_called.clone(); liq.set_log_callback(move |_attr, _msg| { log_called2.store(true, SeqCst); }); let prog_called = Arc::new(AtomicBool::new(false)); let prog_called2 = prog_called.clone(); liq.set_progress_callback(move |_perc| { prog_called2.store(true, SeqCst); ControlFlow::Continue }); // Describe the bitmap let img = &mut liq.new_image(&fakebitmap[..], width, height, 0.0).unwrap(); // The magic happens in quantize() let mut res = match liq.quantize(img) { Ok(res) => res, Err(err) => panic!("Quantization failed, because: {err:?}"), }; // Enable dithering for subsequent remappings res.set_dithering_level(1.0).unwrap(); // You can reuse the result to generate several images with the same palette let (palette, pixels) = res.remapped(img).unwrap(); assert_eq!(width * height, pixels.len()); assert_eq!(100, res.quantization_quality().unwrap()); assert_eq!(RGBA { r: 255, g: 255, b: 255, a: 255 }, palette[0]); assert_eq!(RGBA { r: 0x55, g: 0x66, b: 0x77, a: 255 }, palette[1]); assert!(log_called.load(SeqCst)); assert!(prog_called.load(SeqCst)); } #[test] fn set_importance_map() { let liq = new(); let bitmap = &[RGBA::new(255, 0, 0, 255), RGBA::new(0u8, 0, 255, 255)]; let mut img = liq.new_image(&bitmap[..], 2, 1, 0.).unwrap(); let map = &[255, 0]; img.set_importance_map(&map[..]).unwrap(); let mut res = liq.quantize(&mut img).unwrap(); let pal = res.palette(); assert_eq!(1, pal.len(), "{pal:?}"); assert_eq!(bitmap[0], pal[0]); } #[test] fn thread() { let liq = Attributes::new(); std::thread::spawn(move || { let b = vec![RGBA::new(0, 0, 0, 0); 1]; liq.new_image_borrowed(&b, 1, 1, 0.).unwrap(); }).join().unwrap(); } #[test] fn r_callback_test() { use std::mem::MaybeUninit; use std::sync::atomic::AtomicU16; use std::sync::atomic::Ordering::SeqCst; use std::sync::Arc; let called = Arc::new(AtomicU16::new(0)); let called2 = called.clone(); let mut res = { let a = new(); let get_row = move |output_row: &mut [MaybeUninit], y: usize| { assert!((0..5).contains(&y)); assert_eq!(123, output_row.len()); for (n, out) in output_row.iter_mut().enumerate() { let n = n as u8; out.write(RGBA::new(n, n, n, n)); } called2.fetch_add(1, SeqCst); }; let mut img = unsafe { Image::new_fn(&a, get_row, 123, 5, 0.).unwrap() }; a.quantize(&mut img).unwrap() }; let called = called.load(SeqCst); assert!(called > 5 && called < 50); assert_eq!(123, res.palette().len()); } #[test] fn sizes() { use pal::PalF; use pal::Palette; assert!(std::mem::size_of::() < crate::pal::MAX_COLORS*(8*4)+32, "{}", std::mem::size_of::()); assert!(std::mem::size_of::() < std::mem::size_of::() + std::mem::size_of::() + 100, "{}", std::mem::size_of::()); assert!(std::mem::size_of::() < 200); assert!(std::mem::size_of::() < 300); assert!(std::mem::size_of::() < 200); assert!(std::mem::size_of::() <= 32); } #[doc(hidden)] pub fn _unstable_internal_kmeans_bench() -> impl FnMut() { use crate::pal::{PalF, PalPop}; let attr = new(); let mut h = hist::Histogram::new(&attr); let e = (0..10000u32).map(|i| HistogramEntry { count: i.wrapping_mul(17) % 12345, color: RGBA::new(i as u8, (i.wrapping_mul(7) >> 2) as u8, (i.wrapping_mul(11) >> 11) as u8, 255), }).collect::>(); h.add_colors(&e, 0.).unwrap(); let mut hist = h.finalize_builder(0.45455).unwrap(); let lut = pal::gamma_lut(0.45455); let mut p = PalF::new(); for i in 0..=255 { p.push(pal::f_pixel::from_rgba(&lut, RGBA::new(i|7, i, i, 255)), PalPop::new(1.)); } move || { kmeans::Kmeans::iteration(&mut hist, &mut p, false).unwrap(); } } trait PushInCapacity { fn push_in_cap(&mut self, val: T); } impl PushInCapacity for Vec { #[track_caller] #[inline(always)] fn push_in_cap(&mut self, val: T) { debug_assert!(self.capacity() != self.len()); if self.capacity() != self.len() { self.push(val); } } } /// Rust is too conservative about sorting floats. /// This library uses only finite values, so they're sortable. #[derive(Debug, PartialEq, PartialOrd, Copy, Clone)] #[repr(transparent)] struct OrdFloat(pub(crate) T); impl Eq for OrdFloat { } impl Ord for OrdFloat { #[inline] fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.partial_cmp(&other.0).unwrap_or(std::cmp::Ordering::Equal) } } impl Eq for OrdFloat { } impl Ord for OrdFloat { #[inline] fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.partial_cmp(&other.0).unwrap_or(std::cmp::Ordering::Equal) } } impl OrdFloat { pub fn new(v: f32) -> Self { debug_assert!(v.is_finite()); Self(v) } } impl OrdFloat { pub fn new64(v: f64) -> Self { debug_assert!(v.is_finite()); Self(v) } } #[test] fn test_fixed_colors() { let attr = Attributes::new(); let mut h = Histogram::new(&attr); let tmp = (0..128).map(|c| HistogramEntry { color: RGBA::new(c,c,c,255), count: 1, }).collect::>(); h.add_colors(&tmp, 0.).unwrap(); for f in 200..255 { h.add_fixed_color(RGBA::new(f, f, f, 255), 0.).unwrap(); } let mut r = h.quantize(&attr).unwrap(); let pal = r.palette(); for (i, c) in (200..255).enumerate() { assert_eq!(pal[i], RGBA::new(c, c, c, 255)); } for c in 0..128 { assert!(pal[55..].iter().any(|&p| p == RGBA::new(c, c, c, 255))); } } libimagequant-4.4.0/src/mediancut.rs000066400000000000000000000301641503274717000174610ustar00rootroot00000000000000use crate::hist::{HistItem, HistogramInternal}; use crate::pal::{f_pixel, PalF, PalLen, PalPop, ARGBF}; use crate::quant::quality_to_mse; use crate::PushInCapacity; use crate::{Error, OrdFloat}; use rgb::prelude::*; use std::cmp::Reverse; struct MedianCutter<'hist> { boxes: Vec>, hist_total_perceptual_weight: f64, target_colors: PalLen, } struct MBox<'hist> { /// Histogram entries that fell into this bucket pub colors: &'hist mut [HistItem], /// Center color selected to represent the colors pub avg_color: f_pixel, /// Difference from the average color, per channel, weighed using `adjusted_weight` pub variance: ARGBF, pub adjusted_weight_sum: f64, pub total_error: Option, /// max color difference between avg_color and any histogram entry pub max_error: f32, } impl<'hist> MBox<'hist> { pub fn new(hist: &'hist mut [HistItem]) -> Self { let weight_sum = hist.iter().map(|a| { debug_assert!(a.adjusted_weight.is_finite()); debug_assert!(a.adjusted_weight > 0.); f64::from(a.adjusted_weight) }).sum(); Self::new_c(hist, weight_sum, weighed_average_color(hist)) } fn new_s(hist: &'hist mut [HistItem], adjusted_weight_sum: f64, other_boxes: &[MBox<'_>]) -> Self { debug_assert!(!hist.is_empty()); let mut avg_color = weighed_average_color(hist); // It's possible that an average color will end up being bad for every entry, // so prefer picking actual colors so that at least one histogram entry will be satisfied. if (hist.len() < 500 && hist.len() > 2) || Self::is_useless_color(avg_color, hist, other_boxes) { avg_color = hist.iter().min_by_key(|a| OrdFloat::new(avg_color.diff(&a.color))).map(|a| a.color).unwrap_or_default(); } Self::new_c(hist, adjusted_weight_sum, avg_color) } fn new_c(hist: &'hist mut [HistItem], adjusted_weight_sum: f64, avg_color: f_pixel) -> Self { let (variance, max_error) = Self::box_stats(hist, avg_color); Self { variance, max_error, avg_color, colors: hist, adjusted_weight_sum, total_error: None, } } /// It's possible that the average color is useless fn is_useless_color(new_avg_color: f_pixel, colors: &[HistItem], other_boxes: &[MBox<'_>]) -> bool { colors.iter().all(move |c| { let own_box_diff = new_avg_color.diff(&c.color); let other_box_is_better = other_boxes.iter() .any(move |other| other.avg_color.diff(&c.color) < own_box_diff); other_box_is_better }) } fn box_stats(hist: &[HistItem], avg_color: f_pixel) -> (ARGBF, f32) { let mut variance = ARGBF::default(); let mut max_error = 0.; for a in hist { variance += (avg_color.0 - a.color.0).map(|c| c * c) * a.adjusted_weight; let diff = avg_color.diff(&a.color); if diff > max_error { max_error = diff; } } (variance, max_error) } pub fn compute_total_error(&mut self) -> f64 { let avg = self.avg_color; let e = self.colors.iter().map(move |a| f64::from(avg.diff(&a.color)) * f64::from(a.perceptual_weight)).sum::(); self.total_error = Some(e); e } pub fn prepare_sort(&mut self) { struct ChanVariance { pub chan: usize, pub variance: f32, } // Sort dimensions by their variance, and then sort colors first by dimension with the highest variance let vars: [f32; 4] = rgb::bytemuck::cast(self.variance); let mut channels = [ ChanVariance { chan: 0, variance: vars[0] }, ChanVariance { chan: 1, variance: vars[1] }, ChanVariance { chan: 2, variance: vars[2] }, ChanVariance { chan: 3, variance: vars[3] }, ]; channels.sort_unstable_by_key(|a| Reverse(OrdFloat::new(a.variance))); for a in self.colors.iter_mut() { let chans: [f32; 4] = rgb::bytemuck::cast(a.color.0); // Only the first channel really matters. But other channels are included, because when trying median cut // many times with different histogram weights, I don't want sort randomness to influence the outcome. a.tmp.mc_sort_value = (u32::from((chans[channels[0].chan] * 65535.) as u16) << 16) | u32::from(((chans[channels[2].chan] + chans[channels[1].chan] / 2. + chans[channels[3].chan] / 4.) * 65535.) as u16); // box will be split to make color_weight of each side even } } fn median_color(&mut self) -> f_pixel { let len = self.colors.len(); let (_, mid_item, _) = self.colors.select_nth_unstable_by_key(len / 2, |a| a.mc_sort_value()); mid_item.color } pub fn prepare_color_weight_total(&mut self) -> f64 { let median = self.median_color(); self.colors.iter_mut().map(move |a| { let w = median.diff(&a.color).sqrt() * (1. + a.adjusted_weight).sqrt(); debug_assert!(w.is_finite()); a.mc_color_weight = w; f64::from(w) }) .sum() } #[inline] pub fn split(mut self, other_boxes: &[MBox<'_>]) -> [Self; 2] { self.prepare_sort(); let half_weight = self.prepare_color_weight_total() / 2.; // yeah, there's some off-by-one error in there let break_at = hist_item_sort_half(self.colors, half_weight).max(1); let (left, right) = self.colors.split_at_mut(break_at); let left_sum = left.iter().map(|a| f64::from(a.adjusted_weight)).sum(); let right_sum = self.adjusted_weight_sum - left_sum; [MBox::new_s(left, left_sum, other_boxes), MBox::new_s(right, right_sum, other_boxes)] } } #[inline] fn qsort_pivot(base: &[HistItem]) -> usize { let len = base.len(); if len < 32 { return len / 2; } let mut pivots = [8, len / 2, len - 1]; // LLVM can't see it's in bounds :( pivots.sort_unstable_by_key(move |&idx| unsafe { debug_assert!(base.get(idx).is_some()); base.get_unchecked(idx) }.mc_sort_value()); pivots[1] } fn qsort_partition(base: &mut [HistItem]) -> usize { let mut r = base.len(); base.swap(qsort_pivot(base), 0); let pivot_value = base[0].mc_sort_value(); let mut l = 1; while l < r { if base[l].mc_sort_value() >= pivot_value { l += 1; } else { r -= 1; while l < r && base[r].mc_sort_value() <= pivot_value { r -= 1; } base.swap(l, r); } } l -= 1; base.swap(l, 0); l } /// sorts the slice to make the sum of weights lower than `weight_half_sum` one side, /// returns index of the edge between halfvar parts of the set #[inline(never)] fn hist_item_sort_half(mut base: &mut [HistItem], mut weight_half_sum: f64) -> usize { let mut base_index = 0; if base.is_empty() { return 0; } loop { let partition = qsort_partition(base); let (left, right) = base.split_at_mut(partition + 1); // +1, because pivot stays on the left side let left_sum = left.iter().map(|c| f64::from(c.mc_color_weight)).sum::(); if left_sum >= weight_half_sum { match left.get_mut(..partition) { // trim pivot point, avoid panick branch in [] Some(left) if !left.is_empty() => { base = left; continue; }, _ => return base_index, } } weight_half_sum -= left_sum; base_index += left.len(); if !right.is_empty() { base = right; } else { return base_index; } } } impl<'hist> MedianCutter<'hist> { fn total_box_error_below_target(&mut self, mut target_mse: f64) -> bool { target_mse *= self.hist_total_perceptual_weight; let mut total_error = self.boxes.iter().filter_map(|mb| mb.total_error).sum::(); if total_error > target_mse { return false; } for mb in self.boxes.iter_mut().filter(|mb| mb.total_error.is_none()) { total_error += mb.compute_total_error(); if total_error > target_mse { return false; } } true } pub fn new(hist: &'hist mut HistogramInternal, target_colors: PalLen) -> Result { let hist_total_perceptual_weight = hist.total_perceptual_weight; debug_assert!(hist.clusters[0].begin == 0); debug_assert!(hist.clusters.last().unwrap().end as usize == hist.items.len()); let mut hist_items = &mut hist.items[..]; let mut boxes = Vec::new(); boxes.try_reserve(target_colors as usize)?; let used_boxes = hist.clusters.iter().filter(|b| b.begin != b.end).count(); if used_boxes <= target_colors as usize / 3 { // boxes are guaranteed to be sorted let mut prev_end = 0; for b in hist.clusters.iter().filter(|b| b.begin != b.end) { let begin = b.begin as usize; debug_assert_eq!(begin, prev_end); let end = b.end as usize; prev_end = end; let (this_box, rest) = hist_items.split_at_mut(end - begin); hist_items = rest; boxes.push_in_cap(MBox::new(this_box)); } } else { boxes.push_in_cap(MBox::new(hist_items)); } Ok(Self { boxes, hist_total_perceptual_weight, target_colors, }) } fn into_palette(mut self) -> PalF { let mut palette = PalF::new(); for (i, b) in self.boxes.iter_mut().enumerate() { b.colors.iter_mut().for_each(move |a| a.tmp.likely_palette_index = i as _); // store total color popularity (perceptual_weight is approximation of it) let pop = b.colors.iter().map(|a| f64::from(a.perceptual_weight)).sum::(); palette.push(b.avg_color, PalPop::new(pop as f32)); } palette } fn cut(mut self, target_mse: f64, max_mse: f64) -> PalF { let max_mse = max_mse.max(quality_to_mse(20)); while self.boxes.len() < self.target_colors as usize { // first splits boxes that exceed quality limit (to have colors for things like odd green pixel), // later raises the limit to allow large smooth areas/gradients get colors. let fraction_done = self.boxes.len() as f64 / f64::from(self.target_colors); let current_max_mse = (fraction_done * 16.).mul_add(max_mse, max_mse); let Some(bi) = self.take_best_splittable_box(current_max_mse) else { break }; self.boxes.extend(bi.split(&self.boxes)); if self.total_box_error_below_target(target_mse) { break; } } self.into_palette() } fn take_best_splittable_box(&mut self, max_mse: f64) -> Option> { self.boxes.iter().enumerate() .filter(|(_, b)| b.colors.len() > 1) .map(move |(i, b)| { let cv = b.variance.r.max(b.variance.g).max(b.variance.b); let mut thissum = b.adjusted_weight_sum * f64::from(cv.max(b.variance.a)); if f64::from(b.max_error) > max_mse { thissum = thissum * f64::from(b.max_error) / max_mse; } (i, thissum) }) .max_by_key(|&(_, thissum)| OrdFloat::new64(thissum)) .map(|(i, _)| self.boxes.swap_remove(i)) } } #[inline(never)] pub(crate) fn mediancut(hist: &mut HistogramInternal, target_colors: PalLen, target_mse: f64, max_mse_per_color: f64) -> Result { Ok(MedianCutter::new(hist, target_colors)?.cut(target_mse, max_mse_per_color)) } fn weighed_average_color(hist: &[HistItem]) -> f_pixel { debug_assert!(!hist.is_empty()); let mut t = f_pixel::default(); let mut sum = 0.; for c in hist { sum += c.adjusted_weight; t.0 += c.color.0 * c.adjusted_weight; } if sum != 0. { t.0 /= sum; } t } libimagequant-4.4.0/src/nearest.rs000066400000000000000000000163671503274717000171620ustar00rootroot00000000000000use crate::pal::{f_pixel, PalF, PalIndex, MAX_COLORS}; use crate::{Error, OrdFloat}; impl<'pal> Nearest<'pal> { #[inline(never)] pub fn new(palette: &'pal PalF) -> Result { if palette.len() > PalIndex::MAX as usize + 1 { return Err(Error::Unsupported); } let mut indexes: Vec<_> = (0..palette.len()) .map(|idx| MapIndex { idx: idx as _ }) .collect(); if indexes.is_empty() { return Err(Error::Unsupported); } let mut handle = Nearest { root: vp_create_node(&mut indexes, palette), palette, nearest_other_color_dist: [0.; MAX_COLORS], }; for (i, color) in palette.as_slice().iter().enumerate() { let mut best = Visitor { idx: 0, distance: f32::MAX, distance_squared: f32::MAX, exclude: Some(i as PalIndex), }; vp_search_node(&handle.root, color, &mut best); handle.nearest_other_color_dist[i] = best.distance_squared / 4.; } Ok(handle) } } impl Nearest<'_> { #[inline] pub fn search(&self, px: &f_pixel, likely_colormap_index: PalIndex) -> (PalIndex, f32) { // The index may be invalid, so it needs to be checked let mut best_candidate = if let Some(pal_px) = self.palette.as_slice().get(likely_colormap_index as usize) { let guess_diff = px.diff(pal_px); if guess_diff < self.nearest_other_color_dist[likely_colormap_index as usize] { return (likely_colormap_index, guess_diff); } Visitor { distance: guess_diff.sqrt(), distance_squared: guess_diff, idx: likely_colormap_index, exclude: None, } } else { Visitor { distance: f32::INFINITY, distance_squared: f32::INFINITY, idx: 0, exclude: None, } }; vp_search_node(&self.root, px, &mut best_candidate); (best_candidate.idx, best_candidate.distance_squared) } } pub(crate) struct Nearest<'pal> { root: Node, palette: &'pal PalF, nearest_other_color_dist: [f32; MAX_COLORS], } pub struct MapIndex { pub idx: PalIndex, } pub struct Visitor { pub distance: f32, pub distance_squared: f32, pub idx: PalIndex, pub exclude: Option, } impl Visitor { #[inline] fn visit(&mut self, distance: f32, distance_squared: f32, idx: PalIndex) { if distance_squared < self.distance_squared && self.exclude != Some(idx) { self.distance = distance; self.distance_squared = distance_squared; self.idx = idx; } } } pub(crate) struct Node { vantage_point: f_pixel, inner: NodeInner, idx: PalIndex, } const LEAF_MAX_SIZE: usize = 6; enum NodeInner { Nodes { radius: f32, radius_squared: f32, near: Box, far: Box, }, Leaf { len: u8, idxs: [PalIndex; LEAF_MAX_SIZE], colors: Box<[f_pixel; LEAF_MAX_SIZE]>, }, } #[inline(never)] fn vp_create_node(indexes: &mut [MapIndex], items: &PalF) -> Node { debug_assert!(!indexes.is_empty()); let palette = items.as_slice(); if indexes.len() <= 1 { let idx = indexes.first().map(|i| i.idx).unwrap_or_default(); return Node { vantage_point: palette.get(usize::from(idx)).copied().unwrap_or_default(), idx, inner: NodeInner::Leaf { len: 0, idxs: [0; LEAF_MAX_SIZE], colors: Box::new([f_pixel::default(); LEAF_MAX_SIZE]) }, }; } let most_popular_item = indexes.iter().enumerate().max_by_key(move |(_, idx)| { OrdFloat::new(items.pop_as_slice().get(usize::from(idx.idx)) .map(|p| p.popularity()).unwrap_or_default()) }).map(|(n, _)| n).unwrap_or_default(); indexes.swap(most_popular_item, 0); let (ref_, indexes) = indexes.split_first_mut().unwrap(); let vantage_point = palette.get(usize::from(ref_.idx)).copied().unwrap_or_default(); indexes.sort_by_cached_key(move |i| { OrdFloat::new(palette.get(usize::from(i.idx)) .map(|px| vantage_point.diff(px)).unwrap_or_default()) }); let num_indexes = indexes.len(); let inner = if num_indexes <= LEAF_MAX_SIZE { let mut colors = [f_pixel::default(); LEAF_MAX_SIZE]; let mut idxs = [Default::default(); LEAF_MAX_SIZE]; indexes.iter().zip(colors.iter_mut().zip(idxs.iter_mut())).for_each(|(i, (color, idx))| { if let Some(c) = palette.get(usize::from(i.idx)) { *idx = i.idx; *color = *c; } }); NodeInner::Leaf { len: num_indexes as _, idxs, colors: Box::new(colors), } } else { let half_index = num_indexes / 2; let (near, far) = indexes.split_at_mut(half_index); debug_assert!(!near.is_empty()); debug_assert!(!far.is_empty()); let radius_squared = palette.get(usize::from(far[0].idx)) .map(|px| vantage_point.diff(px)).unwrap_or_default(); let radius = radius_squared.sqrt(); NodeInner::Nodes { radius, radius_squared, near: Box::new(vp_create_node(near, items)), far: Box::new(vp_create_node(far, items)), } }; Node { inner, vantage_point, idx: ref_.idx, } } #[inline(never)] fn vp_search_node(mut node: &Node, needle: &f_pixel, best_candidate: &mut Visitor) { loop { let distance_squared = node.vantage_point.diff(needle); let distance = distance_squared.sqrt(); best_candidate.visit(distance, distance_squared, node.idx); match node.inner { NodeInner::Nodes { radius, radius_squared, ref near, ref far } => { // Recurse towards most likely candidate first to narrow best candidate's distance as soon as possible if distance_squared < radius_squared { vp_search_node(near, needle, best_candidate); // The best node (final answer) may be just ouside the radius, but not farther than // the best distance we know so far. The vp_search_node above should have narrowed // best_candidate->distance, so this path is rarely taken. if distance >= radius - best_candidate.distance { node = far; continue; } } else { vp_search_node(far, needle, best_candidate); if distance <= radius + best_candidate.distance { node = near; continue; } } break; }, NodeInner::Leaf { len: num, ref idxs, ref colors } => { colors.iter().zip(idxs.iter().copied()).take(num as usize).for_each(|(color, idx)| { let distance_squared = color.diff(needle); best_candidate.visit(distance_squared.sqrt(), distance_squared, idx); }); break; }, } } } libimagequant-4.4.0/src/pal.rs000066400000000000000000000334331503274717000162660ustar00rootroot00000000000000use crate::OrdFloat; use arrayvec::ArrayVec; use rgb::prelude::*; use std::ops::{Deref, DerefMut}; /// 8-bit RGBA in sRGB. This is the only color format *publicly* used by the library. pub type RGBA = rgb::Rgba; #[allow(clippy::upper_case_acronyms)] pub type ARGBF = rgb::Argb; pub const INTERNAL_GAMMA: f64 = 0.57; pub const LIQ_WEIGHT_A: f32 = 0.625; pub const LIQ_WEIGHT_R: f32 = 0.5; pub const LIQ_WEIGHT_G: f32 = 1.; pub const LIQ_WEIGHT_B: f32 = 0.45; /// This is a fudge factor - reminder that colors are not in 0..1 range any more pub const LIQ_WEIGHT_MSE: f64 = 0.45; pub const MIN_OPAQUE_A: f32 = 1. / 256. * LIQ_WEIGHT_A; pub const MAX_TRANSP_A: f32 = 255. / 256. * LIQ_WEIGHT_A; /// 4xf32 color using internal gamma. /// /// ARGB layout is important for x86 SIMD. /// I've created the newtype wrapper to try a 16-byte alignment, but it didn't improve perf :( #[cfg_attr( any(target_arch = "x86_64", all(target_feature = "neon", target_arch = "aarch64")), repr(C, align(16)) )] #[derive(Debug, Copy, Clone, Default, PartialEq)] #[allow(non_camel_case_types)] pub struct f_pixel(pub ARGBF); impl f_pixel { #[cfg(not(any(target_arch = "x86_64", all(target_feature = "neon", target_arch = "aarch64"))))] #[inline(always)] pub fn diff(&self, other: &f_pixel) -> f32 { let alphas = other.0.a - self.0.a; let black = self.0 - other.0; let white = ARGBF { a: 0., r: black.r + alphas, g: black.g + alphas, b: black.b + alphas, }; (black.r * black.r).max(white.r * white.r) + (black.g * black.g).max(white.g * white.g) + (black.b * black.b).max(white.b * white.b) } #[cfg(all(target_feature = "neon", target_arch = "aarch64"))] #[inline(always)] pub fn diff(&self, other: &Self) -> f32 { unsafe { use std::arch::aarch64::*; let px = vld1q_f32((self as *const Self).cast::()); let py = vld1q_f32((other as *const Self).cast::()); // y.a - x.a let mut alphas = vsubq_f32(py, px); alphas = vdupq_laneq_f32(alphas, 0); // copy first to all four let mut onblack = vsubq_f32(px, py); // x - y let mut onwhite = vaddq_f32(onblack, alphas); // x - y + (y.a - x.a) onblack = vmulq_f32(onblack, onblack); onwhite = vmulq_f32(onwhite, onwhite); let max = vmaxq_f32(onwhite, onblack); let mut max_r = [0.; 4]; vst1q_f32(max_r.as_mut_ptr(), max); let mut max_gb = [0.; 4]; vst1q_f32(max_gb.as_mut_ptr(), vpaddq_f32(max, max)); // add rgb, not a max_r[1] + max_gb[1] } } #[cfg(target_arch = "x86_64")] #[inline(always)] pub fn diff(&self, other: &f_pixel) -> f32 { unsafe { use std::arch::x86_64::*; let px = _mm_loadu_ps(self as *const f_pixel as *const f32); let py = _mm_loadu_ps(other as *const f_pixel as *const f32); // y.a - x.a let mut alphas = _mm_sub_ss(py, px); alphas = _mm_shuffle_ps(alphas, alphas, 0); // copy first to all four let mut onblack = _mm_sub_ps(px, py); // x - y let mut onwhite = _mm_add_ps(onblack, alphas); // x - y + (y.a - x.a) onblack = _mm_mul_ps(onblack, onblack); onwhite = _mm_mul_ps(onwhite, onwhite); let max = _mm_max_ps(onwhite, onblack); // the compiler is better at horizontal add than I am let mut tmp = [0.; 4]; _mm_storeu_ps(tmp.as_mut_ptr(), max); // add rgb, not a let res = tmp[1] + tmp[2] + tmp[3]; res } } #[inline] pub(crate) fn to_rgb(self, gamma: f64) -> RGBA { if self.a < MIN_OPAQUE_A { return RGBA::new(0, 0, 0, 0); } let r = (LIQ_WEIGHT_A / LIQ_WEIGHT_R) * self.r / self.a; let g = (LIQ_WEIGHT_A / LIQ_WEIGHT_G) * self.g / self.a; let b = (LIQ_WEIGHT_A / LIQ_WEIGHT_B) * self.b / self.a; let a = (256. / LIQ_WEIGHT_A) * self.a; let gamma = (gamma / INTERNAL_GAMMA) as f32; debug_assert!(gamma.is_finite()); // 256, because numbers are in range 1..255.9999… rounded down RGBA { r: (r.powf(gamma) * 256.) as u8, g: (g.powf(gamma) * 256.) as u8, b: (b.powf(gamma) * 256.) as u8, a: a as u8, } } pub fn from_rgba(gamma_lut: &[f32; 256], px: RGBA) -> Self { let a = f32::from(px.a) / 255.; Self(ARGBF { a: a * LIQ_WEIGHT_A, r: gamma_lut[px.r as usize] * LIQ_WEIGHT_R * a, g: gamma_lut[px.g as usize] * LIQ_WEIGHT_G * a, b: gamma_lut[px.b as usize] * LIQ_WEIGHT_B * a, }) } } impl Deref for f_pixel { type Target = ARGBF; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for f_pixel { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From for f_pixel { #[inline(always)] fn from(x: ARGBF) -> Self { Self(x) } } /// To keep the data dense, `is_fixed` is stuffed into the sign bit #[derive(Copy, Clone, Debug)] pub(crate) struct PalPop(f32); impl PalPop { #[inline(always)] pub fn is_fixed(self) -> bool { self.0 < 0. } #[must_use] pub fn to_fixed(self) -> Self { if self.0 < 0. { return self; } Self(if self.0 > 0. { -self.0 } else { -1. }) } #[inline] #[cfg_attr(debug_assertions, track_caller)] pub fn new(popularity: f32) -> Self { debug_assert!(popularity >= 0.); Self(popularity) } #[inline(always)] #[must_use] pub fn popularity(self) -> f32 { self.0.abs() } } #[cfg(feature = "large_palettes")] pub type PalIndex = u16; #[cfg(not(feature = "large_palettes"))] pub type PalIndex = u8; /// This could be increased to support > 256 colors in remapping too pub type PalIndexRemap = u8; pub type PalLen = u16; /// Palettes are stored on the stack, and really large ones will cause stack overflows pub(crate) const MAX_COLORS: usize = if PalIndex::MAX == 255 { 256 } else { 2048 }; /// A palette of premultiplied ARGB 4xf32 colors in internal gamma #[derive(Clone)] pub(crate) struct PalF { colors: ArrayVec, pops: ArrayVec, } impl PalF { #[inline] pub fn new() -> Self { debug_assert!(PalIndex::MAX as usize + 1 >= MAX_COLORS); debug_assert!(PalLen::MAX as usize >= MAX_COLORS); Self { colors: ArrayVec::default(), pops: ArrayVec::default(), } } #[inline(always)] pub fn push(&mut self, color: f_pixel, popularity: PalPop) { self.pops.push(popularity); self.colors.push(color); } pub fn set(&mut self, idx: usize, color: f_pixel, popularity: PalPop) { debug_assert!(idx < self.colors.len() && idx < self.pops.len()); if let Some(pops_idx) = self.pops.get_mut(idx) { *pops_idx = popularity; } if let Some(colors_idx) = self.colors.get_mut(idx) { *colors_idx = color; } } #[inline(always)] pub fn as_slice(&self) -> &[f_pixel] { &self.colors } #[inline(always)] pub fn pop_as_slice(&self) -> &[PalPop] { &self.pops } // this is max colors allowed by the user, not just max in the current (candidate/low-quality) palette pub(crate) fn with_fixed_colors(mut self, max_colors: PalLen, fixed_colors: &[f_pixel]) -> Self { if fixed_colors.is_empty() { return self; } // if using low quality, there's a chance mediancut won't create enough colors in the palette let max_fixed_colors = fixed_colors.len().min(max_colors as usize); if self.len() < max_fixed_colors { let needs_extra = max_fixed_colors - self.len(); self.colors.extend(fixed_colors.iter().copied().take(needs_extra)); self.pops.extend(std::iter::repeat(PalPop::new(0.)).take(needs_extra)); debug_assert_eq!(self.len(), max_fixed_colors); } // since the fixed colors were in the histogram, expect them to be in the palette, // and change closest existing one to be exact fixed for (i, fixed_color) in fixed_colors.iter().enumerate().take(self.len()) { let (best_idx, _) = self.colors.iter().enumerate().skip(i).min_by_key(|(_, pal_color)| { // not using Nearest, because creation of the index may take longer than naive search once OrdFloat::new(pal_color.diff(fixed_color)) }).expect("logic bug in fixed colors, please report a bug"); debug_assert!(best_idx >= i); self.swap(i, best_idx); self.set(i, *fixed_color, self.pops[i].to_fixed()); } debug_assert!(self.colors.iter().zip(fixed_colors).all(|(p, f)| p == f)); debug_assert!(self.pops.iter().take(fixed_colors.len()).all(|pop| pop.is_fixed())); self } #[inline(always)] pub(crate) fn len(&self) -> usize { debug_assert_eq!(self.colors.len(), self.pops.len()); self.colors.len() } #[inline(always)] pub fn iter_mut(&mut self) -> impl Iterator { let c = &mut self.colors[..]; let pop = &mut self.pops[..c.len()]; c.iter_mut().zip(pop) } #[cfg_attr(debug_assertions, track_caller)] pub(crate) fn swap(&mut self, a: usize, b: usize) { self.colors.swap(a, b); self.pops.swap(a, b); } /// Also rounds the input pal pub(crate) fn init_int_palette(&mut self, int_palette: &mut Palette, gamma: f64, posterize: u8) { let lut = gamma_lut(gamma); for ((f_color, f_pop), int_pal) in self.iter_mut().zip(&mut int_palette.entries) { let mut px = f_color.to_rgb(gamma) .map(move |c| posterize_channel(c, posterize)); *f_color = f_pixel::from_rgba(&lut, px); if px.a == 0 && !f_pop.is_fixed() { px.r = 71u8; px.g = 112u8; px.b = 76u8; } *int_pal = px; } int_palette.count = self.len() as _; } } #[inline] const fn posterize_channel(color: u8, bits: u8) -> u8 { if bits == 0 { color } else { (color & !((1 << bits) - 1)) | (color >> (8 - bits)) } } #[inline(always)] pub fn gamma_lut(gamma: f64) -> [f32; 256] { debug_assert!(gamma > 0.); let mut tmp = [0.; 256]; for (i, t) in tmp.iter_mut().enumerate() { *t = ((i as f32) / 255.).powf((INTERNAL_GAMMA / gamma) as f32); } tmp } /// Not used in the Rust API. /// RGBA colors obtained from [`QuantizationResult`](crate::QuantizationResult) #[repr(C)] #[derive(Clone)] pub struct Palette { /// Number of used colors in the `entries` pub count: std::os::raw::c_uint, /// The colors, up to `count` pub entries: [RGBA; MAX_COLORS], } impl std::ops::Deref for Palette { type Target = [RGBA]; #[inline(always)] fn deref(&self) -> &Self::Target { self.as_slice() } } impl std::ops::DerefMut for Palette { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { self.as_mut_slice() } } impl Palette { /// Palette colors #[inline(always)] #[must_use] pub fn as_slice(&self) -> &[RGBA] { &self.entries[..self.count as usize] } #[inline(always)] pub(crate) fn as_mut_slice(&mut self) -> &mut [RGBA] { &mut self.entries[..self.count as usize] } } #[test] fn diff_test() { let a = f_pixel(ARGBF {a: 1., r: 0.2, g: 0.3, b: 0.5}); let b = f_pixel(ARGBF {a: 1., r: 0.3, g: 0.3, b: 0.5}); let c = f_pixel(ARGBF {a: 1., r: 1., g: 0.3, b: 0.5}); let d = f_pixel(ARGBF {a: 0., r: 1., g: 0.3, b: 0.5}); assert!(a.diff(&b) < b.diff(&c)); assert!(c.diff(&b) < c.diff(&d)); let a = f_pixel(ARGBF {a: 1., b: 0.2, r: 0.3, g: 0.5}); let b = f_pixel(ARGBF {a: 1., b: 0.3, r: 0.3, g: 0.5}); let c = f_pixel(ARGBF {a: 1., b: 1., r: 0.3, g: 0.5}); let d = f_pixel(ARGBF {a: 0., b: 1., r: 0.3, g: 0.5}); assert!(a.diff(&b) < b.diff(&c)); assert!(c.diff(&b) < c.diff(&d)); let a = f_pixel(ARGBF {a: 1., g: 0.2, b: 0.3, r: 0.5}); let b = f_pixel(ARGBF {a: 1., g: 0.3, b: 0.3, r: 0.5}); let c = f_pixel(ARGBF {a: 1., g: 1., b: 0.3, r: 0.5}); let d = f_pixel(ARGBF {a: 0., g: 1., b: 0.3, r: 0.5}); assert!(a.diff(&b) < b.diff(&c)); assert!(c.diff(&b) < c.diff(&d)); } #[test] fn pal_test() { let mut p = PalF::new(); let gamma = gamma_lut(0.45455); for i in 0..=255u8 { let rgba = RGBA::new(i, i, i, 100 + i / 2); p.push(f_pixel::from_rgba(&gamma, rgba), PalPop::new(1.)); assert_eq!(i as usize + 1, p.len()); assert_eq!(i as usize + 1, p.pop_as_slice().len()); assert_eq!(i as usize + 1, p.as_slice().len()); assert_eq!(i as usize + 1, p.colors.len()); assert_eq!(i as usize + 1, p.pops.len()); assert_eq!(i as usize + 1, p.iter_mut().count()); } let mut int_pal = Palette { count: 0, entries: [RGBA::default(); MAX_COLORS], }; p.init_int_palette(&mut int_pal, 0.45455, 0); for i in 0..=255u8 { let rgba = p.as_slice()[i as usize].to_rgb(0.45455); assert_eq!(rgba, RGBA::new(i, i, i, 100 + i / 2)); assert_eq!(int_pal[i as usize], RGBA::new(i, i, i, 100 + i / 2)); } } #[test] #[cfg(feature = "large_palettes")] fn largepal() { let gamma = gamma_lut(0.5); let mut p = PalF::new(); for i in 0..1000 { let rgba = RGBA::new(i as u8, (i/2) as u8, (i/4) as u8, 255); p.push(f_pixel::from_rgba(&gamma, rgba), PalPop::new(1.)); } } libimagequant-4.4.0/src/quant.rs000066400000000000000000000477671503274717000166610ustar00rootroot00000000000000use crate::attr::{Attributes, ControlFlow}; use crate::error::*; use crate::hist::{HistogramInternal, Histogram}; use crate::image::Image; use crate::kmeans::Kmeans; use crate::mediancut::mediancut; use crate::pal::{PalF, PalIndexRemap, PalLen, PalPop, Palette, LIQ_WEIGHT_MSE, MAX_COLORS, MAX_TRANSP_A, RGBA}; use crate::remap::{mse_to_standard_mse, remap_to_palette, remap_to_palette_floyd, DitherMapMode, Remapped}; use crate::seacow::RowBitmapMut; use crate::OrdFloat; use arrayvec::ArrayVec; use std::cmp::Reverse; use std::fmt; use std::mem::MaybeUninit; /// Remapping step, computed from [`Attributes::quantize()`] pub struct QuantizationResult { remapped: Option>, pub(crate) palette: PalF, progress_callback: Option ControlFlow + Send + Sync>>, pub(crate) int_palette: Palette, pub(crate) dither_level: f32, pub(crate) gamma: f64, pub(crate) palette_error: Option, pub(crate) min_posterization_output: u8, pub(crate) use_dither_map: DitherMapMode, pub(crate) single_threaded_dithering: bool, } impl QuantizationResult { pub(crate) fn new(attr: &Attributes, hist: HistogramInternal, freeze_result_colors: bool, gamma: f64) -> Result { if attr.progress(f32::from(attr.progress_stage1)) { return Err(Aborted); } let (max_mse, target_mse, target_mse_is_zero) = attr.target_mse(hist.items.len()); let (mut palette, palette_error) = find_best_palette(attr, target_mse, target_mse_is_zero, max_mse, hist)?; if freeze_result_colors { palette.iter_mut().for_each(|(_, p)| *p = p.to_fixed()); } if attr.progress(f32::from(attr.progress_stage3).mul_add(0.95, f32::from(attr.progress_stage1) + f32::from(attr.progress_stage2))) { return Err(Aborted); } if let (Some(palette_error), Some(max_mse)) = (palette_error, max_mse) { if palette_error > max_mse { attr.verbose_print(format!( " image degradation MSE={:0.3} (Q={}) exceeded limit of {:0.3} ({})", mse_to_standard_mse(palette_error), mse_to_quality(palette_error), mse_to_standard_mse(max_mse), mse_to_quality(max_mse) )); return Err(QualityTooLow); } } sort_palette(attr, &mut palette); Ok(Self { palette, gamma, palette_error, min_posterization_output: attr.min_posterization(), use_dither_map: attr.use_dither_map, remapped: None, progress_callback: None, int_palette: Palette { count: 0, entries: [RGBA::default(); MAX_COLORS], }, dither_level: 1., single_threaded_dithering: attr.single_threaded_dithering, }) } /// This is 100% redundant and unnecessary. This work is done anyway when remap is called. /// However, this can be called before calling `image.set_background()`, so it may allow better parallelization while the background is generated on another thread. #[doc(hidden)] pub fn optionally_prepare_for_dithering_with_background_set(&mut self, image: &mut Image<'_>, output_buf: &mut [MaybeUninit]) -> Result<(), Error> { let mut output_pixels = RowBitmapMut::new_contiguous(output_buf, image.width()); Self::optionally_generate_dither_map(self.use_dither_map, image, true, &mut output_pixels, &mut self.palette)?; Ok(()) } #[inline(never)] pub(crate) fn write_remapped_image_rows_internal(&mut self, image: &mut Image, mut output_pixels: RowBitmapMut<'_, MaybeUninit>) -> Result<(), Error> { let progress_stage1 = if self.use_dither_map != DitherMapMode::None { 20 } else { 0 }; if self.remap_progress(progress_stage1 as f32 * 0.25) { return Err(Error::Aborted); } image.free_histogram_inputs(); let mut palette = self.palette.clone(); let mut remapped = Box::new(Remapped { int_palette: Palette { count: 0, entries: [RGBA::default(); MAX_COLORS] }, palette_error: None, }); if self.dither_level == 0. { palette.init_int_palette(&mut remapped.int_palette, self.gamma, self.min_posterization_output); remapped.palette_error = Some(remap_to_palette(&mut image.px, image.background.as_deref_mut(), image.importance_map.as_deref(), &mut output_pixels, &mut palette)?.0); } else { let uses_background = image.background.is_some(); let dither_map_error = Self::optionally_generate_dither_map(self.use_dither_map, image, uses_background, &mut output_pixels, &mut palette)?; if self.remap_progress(progress_stage1 as f32 * 0.5) { return Err(Error::Aborted); } let output_image_is_remapped = dither_map_error.is_some(); let palette_error = dither_map_error.or(self.palette_error); // remapping above was the last chance to do K-Means iteration, hence the final palette is set after remapping palette.init_int_palette(&mut remapped.int_palette, self.gamma, self.min_posterization_output); remapped.palette_error = palette_error; let max_dither_error = (palette_error.unwrap_or(quality_to_mse(80)) * 2.4).max(quality_to_mse(35)) as f32; remap_to_palette_floyd(image, output_pixels, &palette, self, max_dither_error, output_image_is_remapped)?; } self.remapped = Some(remapped); Ok(()) } fn optionally_generate_dither_map(use_dither_map: DitherMapMode, image: &mut Image<'_>, uses_background: bool, output_pixels: &mut RowBitmapMut<'_, MaybeUninit>, palette: &mut PalF) -> Result, Error> { let is_image_huge = (image.px.width * image.px.height) > 2000 * 2000; let allow_dither_map = use_dither_map == DitherMapMode::Always || (!is_image_huge && use_dither_map != DitherMapMode::None); let generate_dither_map = allow_dither_map && image.dither_map.is_none(); if !generate_dither_map { return Ok(None); } // If dithering (with dither map) is required, this image is used to find areas that require dithering let (palette_error, row_pointers_remapped) = remap_to_palette(&mut image.px, None, image.importance_map.as_deref(), output_pixels, palette)?; image.update_dither_map(&row_pointers_remapped, &*palette, uses_background)?; Ok(Some(palette_error)) } /// Set to 1.0 to get nice smooth image pub fn set_dithering_level(&mut self, value: f32) -> Result<(), Error> { if !(0. ..=1.).contains(&value) { return Err(ValueOutOfRange); } self.remapped = None; self.dither_level = value; Ok(()) } /// The default is sRGB gamma (~1/2.2) pub fn set_output_gamma(&mut self, value: f64) -> Result<(), Error> { if value <= 0. || value >= 1. { return Err(ValueOutOfRange); } self.remapped = None; self.gamma = value; Ok(()) } /// Approximate gamma correction value used for the output /// /// Colors are converted from input gamma to this gamma #[inline] #[must_use] pub fn output_gamma(&self) -> f64 { self.gamma } /// Number 0-100 guessing how nice the input image will look if remapped to this palette #[must_use] pub fn quantization_quality(&self) -> Option { self.palette_error.map(mse_to_quality) } /// Approximate mean square error of the palette #[must_use] pub fn quantization_error(&self) -> Option { self.palette_error.map(mse_to_standard_mse) } /// Approximate mean square error of the palette used for the most recent remapping #[must_use] pub fn remapping_error(&self) -> Option { self.remapped.as_ref() .and_then(|re| re.palette_error) .or(self.palette_error) .map(mse_to_standard_mse) } /// Palette remapping error mapped back to 0-100 scale, same as the scale in [`Attributes::set_quality()`] #[must_use] pub fn remapping_quality(&self) -> Option { self.remapped.as_ref() .and_then(|re| re.palette_error) .or(self.palette_error) .map(mse_to_quality) } /// The final palette /// /// It's slighly better if you get palette from the [`remapped()`][Self::remapped] call instead #[inline] #[must_use] pub fn palette(&mut self) -> &[RGBA] { self.int_palette().as_slice() } pub(crate) fn int_palette(&mut self) -> &Palette { if let Some(remap) = self.remapped.as_ref() { debug_assert!(remap.int_palette.count > 0); &remap.int_palette } else { if self.int_palette.count == 0 { self.palette.init_int_palette(&mut self.int_palette, self.gamma, self.min_posterization_output); } &self.int_palette } } /// Callback called at various point of processing, which gets percentage of progress done, /// and can return `ControlFlow::Break` to abort further processing #[inline(always)] pub fn set_progress_callback ControlFlow + Sync + Send + 'static>(&mut self, callback: F) { self.progress_callback = Some(Box::new(callback)); } // true == abort pub(crate) fn remap_progress(&self, percent: f32) -> bool { self.progress_callback.as_ref().map_or(false, |cb| cb(percent) == ControlFlow::Break) } /// Remap image into a palette + indices. /// /// Returns the palette and a 1-byte-per-pixel uncompressed bitmap pub fn remapped(&mut self, image: &mut Image<'_>) -> Result<(Vec, Vec), Error> { let mut buf = Vec::new(); let pal = self.remap_into_vec(image, &mut buf)?; Ok((pal, buf)) } /// Remap image into an existing buffer. Use [`remapped()`][Self::remapped] if you don't have a pre-allocated buffer to reuse. /// /// Writes 1-byte-per-pixel uncompressed bitmap into the `Vec`. /// /// Returns the palette. #[inline] pub fn remap_into_vec(&mut self, image: &mut Image<'_>, buf: &mut Vec) -> Result, Error> { let len = image.width() * image.height(); // Capacity is essential here, as it creates uninitialized buffer unsafe { buf.clear(); buf.try_reserve_exact(len)?; self.remap_into(image, &mut buf.spare_capacity_mut()[..len])?; buf.set_len(len); } Ok(self.palette_vec()) } /// Remap image into an existing buffer. /// /// This is a low-level call for use when existing memory has to be reused. Use [`remapped()`][Self::remapped] or [`remap_into_vec()`][Self::remap_into_vec] if possible. /// /// Writes 1-byte-per-pixel uncompressed bitmap into the pre-allocated buffer. /// /// You should call [`palette()`][Self::palette] _after_ this call, but not before it, /// because remapping refines the palette. #[inline] pub fn remap_into(&mut self, image: &mut Image<'_>, output_buf: &mut [MaybeUninit]) -> Result<(), Error> { let required_size = (image.width()) * (image.height()); let output_buf = output_buf.get_mut(0..required_size).ok_or(BufferTooSmall)?; let rows = RowBitmapMut::new_contiguous(output_buf, image.width()); self.write_remapped_image_rows_internal(image, rows) } /// The final palette, copied. /// /// It's slighly better if you get palette from the [`remapped()`][Self::remapped] call instead #[must_use] pub fn palette_vec(&mut self) -> Vec { let pal = self.palette(); let mut out: Vec = Vec::new(); if out.try_reserve_exact(pal.len()).is_ok() { out.extend_from_slice(pal); } out } /// Expected length of the palette /// /// Reads the length without finalizing the colors pub fn palette_len(&mut self) -> usize { self.palette.len() } /// Shortcut for making [`Histogram`] with `add_fixed_color` /// /// Set `gamma` to `0.` for sRGB colors. pub fn from_palette(attr: &Attributes, palette: &[RGBA], gamma: f64) -> Result { if palette.len() > MAX_COLORS { return Err(Unsupported); } let mut hist = Histogram::new(attr); for &c in palette { hist.add_fixed_color(c, gamma)?; } hist.quantize(attr) } /// Getter for the value set in [`set_dithering_level`] pub fn dithering_level(&self) -> f32 { self.dither_level } } impl Clone for QuantizationResult { /// It will be without a progress callback fn clone(&self) -> Self { Self { remapped: self.remapped.clone(), palette: self.palette.clone(), progress_callback: None, int_palette: self.int_palette.clone(), dither_level: self.dither_level, gamma: self.gamma, palette_error: self.palette_error, min_posterization_output: self.min_posterization_output, use_dither_map: self.use_dither_map, single_threaded_dithering: self.single_threaded_dithering, } } } fn sort_palette(attr: &Attributes, palette: &mut PalF) { let last_index_transparent = attr.last_index_transparent; let mut tmp: ArrayVec<_, { MAX_COLORS }> = palette.iter_mut().map(|(c, p)| (*c, *p)).collect(); tmp.sort_by_key(|(color, pop)| { let is_transparent = color.a <= MAX_TRANSP_A; (is_transparent == last_index_transparent, Reverse(OrdFloat::new(pop.popularity()))) }); palette.iter_mut().zip(tmp).for_each(|((dcol, dpop), (scol, spop))| { *dcol = scol; *dpop = spop; }); if last_index_transparent { let alpha_index = palette.as_slice().iter().enumerate() .filter(|(_, c)| c.a <= MAX_TRANSP_A) .min_by_key(|(_, c)| OrdFloat::new(c.a)) .map(|(i, _)| i); if let Some(alpha_index) = alpha_index { let last_index = palette.as_slice().len() - 1; palette.swap(last_index, alpha_index); } } else { let num_transparent = palette.as_slice().iter().enumerate() .filter(|(_, c)| c.a <= MAX_TRANSP_A) .map(|(i, _)| i + 1) // num entries, not index .max(); if let Some(num_transparent) = num_transparent { attr.verbose_print(format!(" eliminated opaque tRNS-chunk entries...{} entr{} transparent", num_transparent, if num_transparent == 1 { "y" } else { "ies" })); } } } impl fmt::Debug for QuantizationResult { #[cold] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "QuantizationResult(q={})", self.quantization_quality().unwrap_or(0)) } } /// Repeats mediancut with different histogram weights to find palette with minimum error. /// /// `feedback_loop_trials` controls how long the search will take. < 0 skips the iteration. #[allow(clippy::or_fun_call)] pub(crate) fn find_best_palette(attr: &Attributes, target_mse: f64, target_mse_is_zero: bool, max_mse: Option, mut hist: HistogramInternal) -> Result<(PalF, Option), Error> { // hist.items includes fixed colors already let few_input_colors = hist.items.len() <= attr.max_colors as usize; // actual target_mse passed to this method has extra diff from posterization if few_input_colors && target_mse_is_zero { return Ok(palette_from_histogram(&hist, attr.max_colors)); } let mut max_colors = attr.max_colors; let total_trials = attr.feedback_loop_trials(hist.items.len()) as i16; let mut trials_left = total_trials; let mut best_palette = None; let mut target_mse_overshoot = if total_trials > 0 { 1.05 } else { 1. }; let mut fails_in_a_row = 0; let mut palette_error = None; let mut palette = loop { let max_mse_per_color = target_mse.max(palette_error.unwrap_or(quality_to_mse(1))).max(quality_to_mse(51)) * 1.2; let mut new_palette = mediancut(&mut hist, max_colors, target_mse * target_mse_overshoot, max_mse_per_color)? .with_fixed_colors(attr.max_colors, &hist.fixed_colors); let stage_done = (f32::from(trials_left.max(0)) / f32::from(total_trials + 1)).mul_add(-(f32::from(trials_left.max(0)) / f32::from(total_trials + 1)), 1.); let overall_done = stage_done.mul_add(f32::from(attr.progress_stage2), f32::from(attr.progress_stage1)); attr.verbose_print(format!(" selecting colors...{}%", (100. * stage_done) as u8)); if trials_left <= 0 { break Some(new_palette); } let first_run_of_target_mse = best_palette.is_none() && target_mse > 0.; let total_error = Kmeans::iteration(&mut hist, &mut new_palette, !first_run_of_target_mse)?; if best_palette.is_none() || total_error < palette_error.unwrap_or(f64::MAX) || (total_error <= target_mse && new_palette.len() < max_colors as usize) { if total_error < target_mse && total_error > 0. { target_mse_overshoot = if (target_mse_overshoot * 1.25) < (target_mse / total_error) {target_mse_overshoot * 1.25 } else {target_mse / total_error }; // if number of colors could be reduced, try to keep it that way } palette_error = Some(total_error); max_colors = max_colors.min(new_palette.len() as PalLen + 1); trials_left -= 1; fails_in_a_row = 0; best_palette = Some(new_palette); } else { fails_in_a_row += 1; target_mse_overshoot = 1.; trials_left -= 5 + fails_in_a_row; } if attr.progress(overall_done) || trials_left <= 0 { break best_palette; } }.ok_or(ValueOutOfRange)?; refine_palette(&mut palette, attr, &mut hist, max_mse, &mut palette_error)?; Ok((palette, palette_error)) } fn refine_palette(palette: &mut PalF, attr: &Attributes, hist: &mut HistogramInternal, max_mse: Option, palette_error: &mut Option) -> Result<(), Error> { let (iterations, iteration_limit) = attr.kmeans_iterations(hist.items.len(), palette_error.is_some()); if iterations > 0 { attr.verbose_print(" moving colormap towards local minimum"); let mut i = 0; while i < iterations { let stage_done = f32::from(i) / f32::from(iterations); let overall_done = (stage_done * f32::from(attr.progress_stage3)).mul_add(0.89, f32::from(attr.progress_stage1) + f32::from(attr.progress_stage2)); if attr.progress(overall_done) { break; } let pal_err = Kmeans::iteration(hist, palette, false)?; debug_assert!(pal_err < 1e20); let previous_palette_error = *palette_error; *palette_error = Some(pal_err); if let Some(previous_palette_error) = previous_palette_error { if (previous_palette_error - pal_err).abs() < iteration_limit { break; } } i += if pal_err > max_mse.unwrap_or(1e20) * 1.5 { 2 } else { 1 }; } } Ok(()) } #[cold] fn palette_from_histogram(hist: &HistogramInternal, max_colors: PalLen) -> (PalF, Option) { let mut hist_pal = PalF::new(); for item in hist.items.iter() { hist_pal.push(item.color, PalPop::new(item.perceptual_weight)); } (hist_pal.with_fixed_colors(max_colors, &hist.fixed_colors), Some(0.)) } pub(crate) fn quality_to_mse(quality: u8) -> f64 { if quality == 0 { return 1e20; // + epsilon for floating point errors } if quality >= 100 { return 0.; } let extra_low_quality_fudge = (0.016 / (0.001 + f64::from(quality)) - 0.001).max(0.); LIQ_WEIGHT_MSE * (extra_low_quality_fudge + 2.5 / (210. + f64::from(quality)).powf(1.2) * (100.1 - f64::from(quality)) / 100.) } pub(crate) fn mse_to_quality(mse: f64) -> u8 { for i in (1..101).rev() { if mse <= quality_to_mse(i) + 0.000001 { return i; } } 0 } libimagequant-4.4.0/src/rayoff.rs000066400000000000000000000032501503274717000167720ustar00rootroot00000000000000use once_cell::unsync::OnceCell; use std::slice::ChunksMut; pub(crate) struct ThreadLocal(OnceCell); impl ThreadLocal { #[inline(always)] pub fn new() -> Self { Self(OnceCell::new()) } #[inline(always)] pub fn get_or(&self, f: impl FnOnce() -> T) -> &T { self.0.get_or_init(f) } #[inline(always)] pub fn get_or_try(&self, f: impl FnOnce() -> Result) -> Result<&T, E> { self.0.get_or_try_init(f) } } impl IntoIterator for ThreadLocal { type IntoIter = std::option::IntoIter; type Item = T; #[inline(always)] fn into_iter(mut self) -> Self::IntoIter { self.0.take().into_iter() } } pub(crate) trait FakeRayonIter: Sized { fn par_bridge(self) -> Self; } impl FakeRayonIter for T where Self: Sized { fn par_bridge(self) -> Self { self } } pub(crate) trait FakeRayonIntoIter { fn par_chunks_mut(&mut self, chunk_size: usize) -> ChunksMut; } impl<'a, T> FakeRayonIntoIter for &'a mut [T] { #[inline(always)] fn par_chunks_mut(&mut self, chunk_size: usize) -> ChunksMut { self.chunks_mut(chunk_size) } } impl<'a, T> FakeRayonIntoIter for Box<[T]> { #[inline(always)] fn par_chunks_mut(&mut self, chunk_size: usize) -> ChunksMut { self.chunks_mut(chunk_size) } } pub(crate) struct SpawnMock; impl SpawnMock { #[inline(always)] pub fn spawn(&self, f: F) -> R where F: FnOnce(SpawnMock) -> R { f(SpawnMock) } } #[inline(always)] pub(crate) fn scope(f: F) -> R where F: FnOnce(SpawnMock) -> R { f(SpawnMock) } #[inline(always)] pub(crate) fn num_cpus() -> usize { 1 } libimagequant-4.4.0/src/remap.rs000066400000000000000000000375021503274717000166170ustar00rootroot00000000000000use crate::error::Error; use crate::image::Image; use crate::kmeans::Kmeans; use crate::nearest::Nearest; use crate::pal::{f_pixel, PalF, PalIndexRemap, Palette, ARGBF, LIQ_WEIGHT_MSE, MIN_OPAQUE_A}; use crate::quant::QuantizationResult; use crate::rayoff::*; use crate::rows::{temp_buf, DynamicRows}; use crate::seacow::{RowBitmap, RowBitmapMut}; use crate::CacheLineAlign; use std::cell::RefCell; use std::mem::MaybeUninit; #[repr(u8)] #[derive(Eq, PartialEq, Clone, Copy)] pub enum DitherMapMode { None = 0, Enabled = 1, Always = 2, } #[derive(Clone)] pub(crate) struct Remapped { pub(crate) int_palette: Palette, pub(crate) palette_error: Option, } #[inline(never)] pub(crate) fn remap_to_palette<'x, 'b: 'x>(px: &mut DynamicRows, background: Option<&mut Image<'_>>, importance_map: Option<&[u8]>, output_pixels: &'x mut RowBitmapMut<'b, MaybeUninit>, palette: &mut PalF) -> Result<(f64, RowBitmap<'x, PalIndexRemap>), Error> { let n = Nearest::new(palette)?; let colors = palette.as_slice(); let palette_len = colors.len(); if palette_len > PalIndexRemap::MAX as usize + 1 { return Err(Error::Unsupported); } let tls = ThreadLocal::new(); let width = px.width as usize; let per_thread_buffers = move || -> Result<_, Error> { Ok(CacheLineAlign(RefCell::new((Kmeans::new(palette_len)?, temp_buf(width)?, temp_buf(width)?, temp_buf(width)?)))) }; let tls_tmp1 = tls.get_or_try(per_thread_buffers)?; let mut tls_tmp = tls_tmp1.0.borrow_mut(); let input_rows = px.rows_iter(&mut tls_tmp.1)?; let (background, transparent_index) = background.map(|background| { (Some(background), n.search(&f_pixel::default(), 0).0 as PalIndexRemap) }) .filter(|&(_, transparent_index)| colors[usize::from(transparent_index)].a < MIN_OPAQUE_A) .unwrap_or((None, 0)); let background = background.map(|bg| bg.px.rows_iter(&mut tls_tmp.1)).transpose()?; if background.is_some() { tls_tmp.0.update_color(f_pixel::default(), 1., transparent_index as _); } drop(tls_tmp); let remapping_error = output_pixels.rows_mut().enumerate().par_bridge().map(|(row, output_pixels_row)| { let mut remapping_error = 0.; let Ok(tls_res) = tls.get_or_try(per_thread_buffers) else { return f64::NAN }; let (kmeans, temp_row, temp_row_f, temp_row_f_bg) = &mut *tls_res.0.borrow_mut(); let output_pixels_row = &mut output_pixels_row[..width]; let importance_map = importance_map.and_then(|m| m.get(row * width..)).unwrap_or(&[]); let row_pixels = &input_rows.row_f_shared(temp_row, temp_row_f, row)[..width]; let bg_pixels = if let Some(background) = &background { &background.row_f_shared(temp_row, temp_row_f_bg, row)[..width] } else { &[] }; let mut last_match = 0; for (col, (inp, out)) in row_pixels.iter().zip(output_pixels_row).enumerate() { let (matched, diff) = n.search(inp, last_match as _); let matched = matched as PalIndexRemap; last_match = matched; if let Some(bg) = bg_pixels.get(col) { let bg_diff = bg.diff(inp); if bg_diff <= diff { remapping_error += f64::from(bg_diff); out.write(transparent_index); continue; } } remapping_error += f64::from(diff); out.write(matched); let importance = f32::from(importance_map.get(col).copied().unwrap_or(1)); kmeans.update_color(*inp, importance, matched as _); } remapping_error }) .sum::(); if remapping_error.is_nan() { return Err(Error::OutOfMemory); } if let Some(kmeans) = tls.into_iter() .map(|t| t.0.into_inner().0) .reduce(Kmeans::merge) { kmeans.finalize(palette); } let remapping_error = remapping_error / f64::from(px.width * px.height); Ok((remapping_error, unsafe { output_pixels.assume_init() })) } fn get_dithered_pixel(dither_level: f32, max_dither_error: f32, thiserr: f_pixel, px: f_pixel) -> f_pixel { let s = thiserr.0 * dither_level; // This prevents gaudy green pixels popping out of the blue (or red or black! ;) let dither_error = s.r.mul_add(s.r, s.g * s.g) + s.b.mul_add(s.b, s.a * s.a); if dither_error < 2. / 256. / 256. { // don't dither areas that don't have noticeable error — makes file smaller return px; } let mut ratio: f32 = 1.; const MAX_OVERFLOW: f32 = 1.1; const MAX_UNDERFLOW: f32 = -0.1; // allowing some overflow prevents undithered bands caused by clamping of all channels if px.r + s.r > MAX_OVERFLOW { ratio = ratio.min((MAX_OVERFLOW - px.r) / s.r); } else if px.r + s.r < MAX_UNDERFLOW { ratio = ratio.min((MAX_UNDERFLOW - px.r) / s.r); } if px.g + s.g > MAX_OVERFLOW { ratio = ratio.min((MAX_OVERFLOW - px.g) / s.g); } else if px.g + s.g < MAX_UNDERFLOW { ratio = ratio.min((MAX_UNDERFLOW - px.g) / s.g); } if px.b + s.b > MAX_OVERFLOW { ratio = ratio.min((MAX_OVERFLOW - px.b) / s.b); } else if px.b + s.b < MAX_UNDERFLOW { ratio = ratio.min((MAX_UNDERFLOW - px.b) / s.b); } if dither_error > max_dither_error { ratio *= 0.8; } f_pixel(ARGBF { a: (px.a + s.a).clamp(0., 1.), r: s.r.mul_add(ratio, px.r), g: s.g.mul_add(ratio, px.g), b: s.b.mul_add(ratio, px.b), }) } /// Uses edge/noise map to apply dithering only to flat areas. Dithering on edges creates jagged lines, and noisy areas are "naturally" dithered. /// /// If `output_image_is_remapped` is true, only pixels noticeably changed by error diffusion will be written to output image. #[inline(never)] pub(crate) fn remap_to_palette_floyd(input_image: &mut Image, mut output_pixels: RowBitmapMut<'_, MaybeUninit>, palette: &PalF, quant: &QuantizationResult, max_dither_error: f32, output_image_is_remapped: bool) -> Result<(), Error> { let progress_stage1 = if quant.use_dither_map != DitherMapMode::None { 20 } else { 0 }; let width = input_image.width(); let height = input_image.height(); let mut temp_row = temp_buf(width)?; let dither_map = if quant.use_dither_map != DitherMapMode::None { input_image.dither_map.as_deref().or(input_image.edges.as_deref()).unwrap_or(&[]) } else { &[] }; let n = Nearest::new(palette)?; let palette = palette.as_slice(); let mut background = input_image.background.as_mut().map(|bg| { bg.px.prepare_iter(&mut temp_row, true)?; Ok::<_, Error>(&bg.px) }).transpose()?; let transparent_index = if background.is_some() { n.search(&f_pixel::default(), 0).0 as PalIndexRemap } else { 0 }; if background.is_some() && palette[transparent_index as usize].a > MIN_OPAQUE_A { background = None; } // response to this value is non-linear and without it any value < 0.8 would give almost no dithering let mut base_dithering_level = (1. - quant.dither_level).mul_add(-(1. - quant.dither_level), 1.) * (15. / 16.); // prevent small errors from accumulating if !dither_map.is_empty() { base_dithering_level *= 1. / 255.; // dither_map is in 0-255 scale } // when using remapping on top of a background, lots of pixels may be transparent, making poor guesses // (guesses are only for speed, don't affect visuals) let guess_from_remapped_pixels = output_image_is_remapped && background.is_none(); input_image.px.prepare_iter(&mut temp_row, true)?; let input_image_px = &input_image.px; let n = &n; // Chunks have overhead, so should be big (more than 2 bring diminishing results). Chunks risk causing seams, so should be tall. let num_chunks = if quant.single_threaded_dithering { 1 } else { (width * height / 524_288).min(height / 128).max(if height > 128 {2} else {1}).min(num_cpus()) }; let chunks = output_pixels.chunks((height + num_chunks - 1) / num_chunks).map(CacheLineAlign); scope(move |s| { let mut chunk_start_row = 0; for mut chunk in chunks { let chunk_len = chunk.0.len(); let mut temp_row = temp_buf(width)?; let mut input_image_iter = input_image_px.rows_iter_prepared()?; let mut background = background.map(|bg| bg.rows_iter_prepared()).transpose()?; let mut diffusion = Vec::new(); let errwidth = width + 2; // +2 saves from checking out of bounds access diffusion.try_reserve_exact(errwidth * 2)?; diffusion.resize(errwidth * 2, f_pixel::default()); // restart of dithering creates a seam. this does redundant work to init diffusion state, // so that later chunks don't start from scratch if chunk_start_row > 2 { let mut discard_row = temp_buf(width)?; for row in (chunk_start_row - 2) .. chunk_start_row { let row_pixels = input_image_iter.row_f(&mut temp_row, row as _); let bg_pixels = background.as_mut().map(|b| b.row_f(&mut temp_row, row as _)).unwrap_or(&[]); let dither_map = dither_map.get(row * width .. row * width + width).unwrap_or(&[]); let scan_forward = row & 1 == 0; dither_row(row_pixels, &mut discard_row, width as u32, dither_map, base_dithering_level, max_dither_error, n, palette, transparent_index, bg_pixels, guess_from_remapped_pixels, &mut diffusion, scan_forward); } } // parallel remap makes progress not very useful if quant.remap_progress(progress_stage1 as f32 + chunk_start_row as f32 * (100. - progress_stage1 as f32) / height as f32) { return Err(Error::Aborted); } s.spawn(move |_| { for (chunk_row, output_pixels_row) in chunk.0.rows_mut().enumerate() { let row = chunk_start_row + chunk_row; let row_pixels = input_image_iter.row_f(&mut temp_row, row as _); let bg_pixels = background.as_mut().map(|b| b.row_f(&mut temp_row, row as _)).unwrap_or(&[]); let dither_map = dither_map.get(row * width .. row * width + width).unwrap_or(&[]); let scan_forward = row & 1 == 0; dither_row(row_pixels, output_pixels_row, width as u32, dither_map, base_dithering_level, max_dither_error, n, palette, transparent_index, bg_pixels, guess_from_remapped_pixels, &mut diffusion, scan_forward); } }); chunk_start_row += chunk_len; } Ok(()) }) } #[inline(never)] fn dither_row(row_pixels: &[f_pixel], output_pixels_row: &mut [MaybeUninit], width: u32, dither_map: &[u8], base_dithering_level: f32, max_dither_error: f32, n: &Nearest, palette: &[f_pixel], transparent_index: PalIndexRemap, bg_pixels: &[f_pixel], guess_from_remapped_pixels: bool, diffusion: &mut [f_pixel], even_row: bool) { let width = width as usize; assert_eq!(row_pixels.len(), width); assert_eq!(output_pixels_row.len(), width); let (thiserr, nexterr) = { // +2 saves from checking out of bounds access let (d1, d2) = diffusion.split_at_mut(width + 2); if even_row { (d1, d2) } else { (d2, d1) } }; nexterr.fill_with(f_pixel::default); let mut undithered_bg_used = 0u8; let mut last_match = 0; for x in 0..width { let col = if even_row { x } else { width - 1 - x }; let thiserr = &mut thiserr[col .. col + 3]; let nexterr = &mut nexterr[col .. col + 3]; let input_px = row_pixels[col]; let mut dither_level = base_dithering_level; if let Some(&l) = dither_map.get(col) { dither_level *= f32::from(l); } let spx = get_dithered_pixel(dither_level, max_dither_error, thiserr[1], input_px); let guessed_match = if guess_from_remapped_pixels { unsafe { output_pixels_row[col].assume_init() } } else { last_match }; let (matched, dither_diff) = n.search(&spx, guessed_match as _); let mut matched = matched as PalIndexRemap; last_match = matched as PalIndexRemap; let mut output_px = palette[last_match as usize]; if let Some(bg_pixel) = bg_pixels.get(col) { // if the background makes better match *with* dithering, it's a definitive win let bg_for_dither_diff = spx.diff(bg_pixel); if bg_for_dither_diff <= dither_diff { output_px = *bg_pixel; matched = transparent_index; } else if undithered_bg_used > 1 { // the undithered fallback can cause artifacts when too many undithered pixels accumulate a big dithering error // so periodically ignore undithered fallback to prevent that undithered_bg_used = 0; } else { // if dithering is not applied, there's a high risk of creating artifacts (flat areas, error accumulating badly), // OTOH poor dithering disturbs static backgrounds and creates oscilalting frames that break backgrounds // back and forth in two differently bad ways let max_diff = input_px.diff(bg_pixel); let dithered_diff = input_px.diff(&output_px); // if dithering is worse than natural difference between frames // (this rule dithers moving areas, but does not dither static areas) if dithered_diff > max_diff { // then see if an undithered color is closer to the ideal let guessed_px = palette[guessed_match as usize]; let undithered_diff = input_px.diff(&guessed_px); // If dithering error is crazy high, don't propagate it that much if undithered_diff < max_diff { undithered_bg_used += 1; output_px = guessed_px; matched = guessed_match; } } } } output_pixels_row[col].write(matched); let mut err = spx.0 - output_px.0; // This prevents weird green pixels popping out of the blue (or red or black! ;) if err.r.mul_add(err.r, err.g * err.g) + err.b.mul_add(err.b, err.a * err.a) > max_dither_error { err *= 0.75; } if even_row { thiserr[2].0 += err * (7. / 16.); nexterr[0].0 += err * (3. / 16.); nexterr[1].0 += err * (5. / 16.); nexterr[2].0 = err * (1. / 16.); } else { thiserr[0].0 += err * (7. / 16.); nexterr[0].0 = err * (1. / 16.); nexterr[1].0 += err * (5. / 16.); nexterr[2].0 += err * (3. / 16.); } } } pub(crate) fn mse_to_standard_mse(mse: f64) -> f64 { (mse * 65536. / 6.) / LIQ_WEIGHT_MSE // parallelized dither map might speed up floyd remapping } #[test] fn send() { fn is_send() {} is_send::>>(); } #[test] fn background_to_nop() { use crate::RGBA; let pixels: Vec<_> = (0..200*200).map(|n| RGBA::new(n as u8, (n/17) as u8, (n/78) as u8, 255)).collect(); let mut attr = crate::new(); let mut img = attr.new_image_borrowed(&pixels, 200, 200, 0.).unwrap(); let img2 = attr.new_image_borrowed(&pixels, 200, 200, 0.).unwrap(); img.set_background(img2).unwrap(); img.add_fixed_color(RGBA::new(0,0,0,0)).unwrap(); attr.set_max_colors(3).unwrap(); let mut res = attr.quantize(&mut img).unwrap(); res.set_dithering_level(0.).unwrap(); let (_, idx) = res.remapped(&mut img).unwrap(); let first = idx[0]; assert!(idx.iter().all(|&x| x == first)); res.set_dithering_level(1.).unwrap(); let (_, idx) = res.remapped(&mut img).unwrap(); let first = idx[0]; assert!(idx.iter().all(|&x| x == first)); } libimagequant-4.4.0/src/rows.rs000066400000000000000000000242211503274717000164770ustar00rootroot00000000000000use crate::error::Error; use crate::pal::{f_pixel, gamma_lut, RGBA}; use crate::seacow::{Pointer, SeaCow}; use crate::LIQ_HIGH_MEMORY_LIMIT; use std::mem::MaybeUninit; pub(crate) type RowCallback<'a> = dyn Fn(&mut [MaybeUninit], usize) + Send + Sync + 'a; pub(crate) enum PixelsSource<'pixels, 'rows> { /// The `pixels` field is never read, but it is used to store the rows. #[allow(dead_code)] Pixels { rows: SeaCow<'rows, Pointer>, pixels: Option>, }, Callback(Box>), } impl<'pixels> PixelsSource<'pixels, '_> { pub(crate) fn for_pixels(pixels: SeaCow<'pixels, RGBA>, width: u32, height: u32, stride: u32) -> Result { if stride < width || height == 0 || width == 0 { return Err(Error::ValueOutOfRange); } let stride = stride as usize; let width = width as usize; let height = height as usize; let slice = pixels.as_slice(); let min_area = stride.checked_mul(height).and_then(|a| a.checked_add(width)).ok_or(Error::ValueOutOfRange)? - stride; if slice.len() < min_area { return Err(Error::BufferTooSmall); } let rows = SeaCow::boxed(slice.chunks(stride).map(|row| Pointer(row.as_ptr())).take(height).collect()); Ok(Self::Pixels { rows, pixels: Some(pixels) }) } } pub(crate) struct DynamicRows<'pixels, 'rows> { pub(crate) width: u32, pub(crate) height: u32, f_pixels: Option>, pixels: PixelsSource<'pixels, 'rows>, pub(crate) gamma: f64, } impl Clone for DynamicRows<'_, '_> { fn clone(&self) -> Self { Self { width: self.width, height: self.height, f_pixels: self.f_pixels.clone(), pixels: match &self.pixels { PixelsSource::Pixels { rows, pixels } => PixelsSource::Pixels { rows: rows.clone(), pixels: pixels.clone(), }, PixelsSource::Callback(_) => { let area = self.width as usize * self.height as usize; let mut out = Vec::with_capacity(area); let out_rows = out.spare_capacity_mut()[..area].chunks_exact_mut(self.width as usize); for (i, row) in out_rows.enumerate() { self.row_rgba(row, i); } unsafe { out.set_len(area); } let pixels = SeaCow::boxed(out.into_boxed_slice()); PixelsSource::for_pixels(pixels, self.width, self.height, self.width).unwrap() }, }, gamma: self.gamma, } } } pub(crate) struct DynamicRowsIter<'parent, 'pixels, 'rows> { px: &'parent DynamicRows<'pixels, 'rows>, temp_f_row: Option]>>, } impl DynamicRowsIter<'_, '_, '_> { #[must_use] pub fn row_f<'px>(&'px mut self, temp_row: &mut [MaybeUninit], row: usize) -> &'px [f_pixel] { debug_assert_eq!(temp_row.len(), self.px.width as usize); if let Some(pixels) = self.px.f_pixels.as_ref() { let start = self.px.width as usize * row; &pixels[start..start + self.px.width as usize] } else { let lut = gamma_lut(self.px.gamma); let row_pixels = self.px.row_rgba(temp_row, row); match self.temp_f_row.as_mut() { Some(t) => DynamicRows::convert_row_to_f(t, row_pixels, &lut), None => &mut [], // this can't happen } } } #[must_use] pub fn row_f_shared<'px>(&'px self, temp_row: &mut [MaybeUninit], temp_row_f: &'px mut [MaybeUninit], row: usize) -> &'px [f_pixel] { if let Some(pixels) = self.px.f_pixels.as_ref() { &pixels[self.px.width as usize * row..] } else { let lut = gamma_lut(self.px.gamma); let row_pixels = self.px.row_rgba(temp_row, row); DynamicRows::convert_row_to_f(temp_row_f, row_pixels, &lut) } } #[must_use] pub fn row_rgba<'px>(&'px self, temp_row: &'px mut [MaybeUninit], row: usize) -> &'px [RGBA] { self.px.row_rgba(temp_row, row) } } impl<'pixels, 'rows> DynamicRows<'pixels, 'rows> { #[inline] pub(crate) fn new(width: u32, height: u32, pixels: PixelsSource<'pixels, 'rows>, gamma: f64) -> Self { debug_assert!(gamma > 0.); Self { width, height, f_pixels: None, pixels, gamma } } fn row_rgba<'px>(&'px self, temp_row: &'px mut [MaybeUninit], row: usize) -> &'px [RGBA] { match &self.pixels { PixelsSource::Pixels { rows, .. } => unsafe { std::slice::from_raw_parts(rows.as_slice()[row].0, self.width()) }, PixelsSource::Callback(cb) => { cb(temp_row, row); // cb needs to be marked as unsafe, since it's responsible for initialization :( unsafe { slice_assume_init_mut(temp_row) } }, } } fn convert_row_to_f<'f>(row_f_pixels: &'f mut [MaybeUninit], row_pixels: &[RGBA], gamma_lut: &[f32; 256]) -> &'f mut [f_pixel] { assert_eq!(row_f_pixels.len(), row_pixels.len()); for (dst, src) in row_f_pixels.iter_mut().zip(row_pixels) { dst.write(f_pixel::from_rgba(gamma_lut, *src)); } // Safe, just initialized unsafe { slice_assume_init_mut(row_f_pixels) } } #[must_use] fn should_use_low_memory(&self) -> bool { self.width() * self.height() > LIQ_HIGH_MEMORY_LIMIT / std::mem::size_of::() } #[inline] fn temp_f_row_for_iter(&self) -> Result]>>, Error> { if self.f_pixels.is_some() { return Ok(None); } Ok(Some(temp_buf(self.width())?)) } pub fn prepare_iter(&mut self, temp_row: &mut [MaybeUninit], allow_steamed: bool) -> Result<(), Error> { debug_assert_eq!(temp_row.len(), self.width as _); if self.f_pixels.is_some() || (allow_steamed && self.should_use_low_memory()) { return Ok(()); } let width = self.width(); let lut = gamma_lut(self.gamma); let mut f_pixels = temp_buf(width * self.height())?; for (row, f_row) in f_pixels.chunks_exact_mut(width).enumerate() { let row_pixels = self.row_rgba(temp_row, row); Self::convert_row_to_f(f_row, row_pixels, &lut); } // just initialized self.f_pixels = Some(unsafe { box_assume_init(f_pixels) }); Ok(()) } #[inline] pub fn rows_iter(&mut self, temp_row: &mut [MaybeUninit]) -> Result, Error> { self.prepare_iter(temp_row, true)?; Ok(DynamicRowsIter { temp_f_row: self.temp_f_row_for_iter()?, px: self, }) } /// Call `prepare_iter()` first #[inline] pub fn rows_iter_prepared(&self) -> Result, Error> { Ok(DynamicRowsIter { temp_f_row: self.temp_f_row_for_iter()?, px: self, }) } #[inline] pub fn rgba_rows_iter(&self) -> Result, Error> { // This happens when histogram image is recycled if let PixelsSource::Pixels { rows, .. } = &self.pixels { if rows.as_slice().is_empty() { return Err(Error::Unsupported); } } Ok(DynamicRowsIter { px: self, temp_f_row: None }) } #[inline] pub fn all_rows_f(&mut self) -> Result<&[f_pixel], Error> { if self.f_pixels.is_some() { return Ok(self.f_pixels.as_ref().unwrap()); // borrow-checker :( } self.prepare_iter(&mut temp_buf(self.width())?, false)?; self.f_pixels.as_deref().ok_or(Error::Unsupported) } /// Not recommended #[cfg(feature = "_internal_c_ffi")] pub(crate) unsafe fn set_memory_ownership(&mut self, own_rows: bool, own_pixels: bool, free_fn: unsafe extern "C" fn(*mut std::os::raw::c_void)) -> Result<(), Error> { if own_rows { match &mut self.pixels { PixelsSource::Pixels { rows, .. } => rows.make_owned(free_fn), PixelsSource::Callback(_) => return Err(Error::ValueOutOfRange), } } if own_pixels { let len = self.width() * self.height(); match &mut self.pixels { PixelsSource::Pixels { pixels: Some(pixels), .. } => pixels.make_owned(free_fn), PixelsSource::Pixels { pixels, rows } => { // the row with the lowest address is assumed to be at the start of the bitmap let ptr = rows.as_slice().iter().map(|p| p.0).min().ok_or(Error::Unsupported)?; *pixels = Some(SeaCow::c_owned(ptr.cast_mut(), len, free_fn)); }, PixelsSource::Callback(_) => return Err(Error::ValueOutOfRange), } } Ok(()) } pub fn free_histogram_inputs(&mut self) { if self.f_pixels.is_some() { self.pixels = PixelsSource::Pixels { rows: SeaCow::borrowed(&[]), pixels: None, }; } } #[inline(always)] #[must_use] pub const fn width(&self) -> usize { self.width as usize } #[inline(always)] #[must_use] pub const fn height(&self) -> usize { self.height as usize } } pub(crate) fn temp_buf(len: usize) -> Result]>, Error> { let mut v = Vec::new(); v.try_reserve_exact(len)?; unsafe { v.set_len(len) }; Ok(v.into_boxed_slice()) } #[test] fn send() { fn is_send() {} fn is_sync() {} is_send::(); is_sync::(); is_send::(); is_sync::(); } #[inline(always)] unsafe fn box_assume_init(s: Box<[MaybeUninit]>) -> Box<[T]> { std::mem::transmute(s) } #[inline(always)] unsafe fn slice_assume_init_mut(s: &mut [MaybeUninit]) -> &mut [T] { &mut *(s as *mut [MaybeUninit] as *mut [T]) } libimagequant-4.4.0/src/seacow.rs000066400000000000000000000132721503274717000167720ustar00rootroot00000000000000use std::mem::MaybeUninit; #[cfg(feature = "_internal_c_ffi")] use std::os::raw::c_void; #[derive(Clone)] pub struct SeaCow<'a, T> { inner: SeaCowInner<'a, T>, } unsafe impl Send for SeaCowInner<'_, T> {} unsafe impl Sync for SeaCowInner<'_, T> {} /// Rust assumes `*const T` is never `Send`/`Sync`, but it can be. /// This is fudge for https://github.com/rust-lang/rust/issues/93367 #[repr(transparent)] #[derive(Copy, Clone)] pub(crate) struct Pointer(pub *const T); #[derive(Copy, Clone)] #[repr(transparent)] pub(crate) struct PointerMut(pub *mut T); unsafe impl Send for Pointer {} unsafe impl Sync for Pointer {} unsafe impl Send for PointerMut {} unsafe impl Sync for PointerMut {} impl SeaCow<'static, T> { #[inline] #[must_use] pub fn boxed(data: Box<[T]>) -> Self { Self { inner: SeaCowInner::Boxed(data) } } } impl<'a, T> SeaCow<'a, T> { #[inline] #[must_use] pub const fn borrowed(data: &'a [T]) -> Self { Self { inner: SeaCowInner::Borrowed(data) } } /// The pointer must be `malloc`-allocated #[inline] #[cfg(feature = "_internal_c_ffi")] #[must_use] pub unsafe fn c_owned(ptr: *mut T, len: usize, free_fn: unsafe extern "C" fn(*mut c_void)) -> Self { debug_assert!(!ptr.is_null()); debug_assert!(len > 0); Self { inner: SeaCowInner::Owned { ptr, len, free_fn }, } } #[inline] #[cfg(feature = "_internal_c_ffi")] pub(crate) fn make_owned(&mut self, free_fn: unsafe extern "C" fn(*mut c_void)) { if let SeaCowInner::Borrowed(slice) = self.inner { self.inner = SeaCowInner::Owned { ptr: slice.as_ptr().cast_mut(), len: slice.len(), free_fn }; } } } impl Clone for SeaCowInner<'_, T> { #[inline(never)] fn clone(&self) -> Self { let slice = match self { Self::Borrowed(data) => return Self::Borrowed(data), #[cfg(feature = "_internal_c_ffi")] Self::Owned { ptr, len, free_fn: _ } => unsafe { std::slice::from_raw_parts(*ptr, *len) }, Self::Boxed(data) => &**data, }; let mut v = Vec::new(); v.try_reserve_exact(slice.len()).unwrap(); v.extend_from_slice(slice); Self::Boxed(v.into_boxed_slice()) } } enum SeaCowInner<'a, T> { #[cfg(feature = "_internal_c_ffi")] Owned { ptr: *mut T, len: usize, free_fn: unsafe extern "C" fn(*mut c_void) }, Borrowed(&'a [T]), Boxed(Box<[T]>), } #[cfg(feature = "_internal_c_ffi")] impl Drop for SeaCowInner<'_, T> { fn drop(&mut self) { if let Self::Owned { ptr, free_fn, .. } = self { unsafe { (free_fn)((*ptr).cast()); } } } } impl SeaCow<'_, T> { #[must_use] pub fn as_slice(&self) -> &[T] { match &self.inner { #[cfg(feature = "_internal_c_ffi")] SeaCowInner::Owned { ptr, len, .. } => unsafe { std::slice::from_raw_parts(*ptr, *len) }, SeaCowInner::Borrowed(a) => a, SeaCowInner::Boxed(x) => x, } } } pub(crate) struct RowBitmap<'a, T> { rows: &'a [Pointer], width: usize, } unsafe impl Send for RowBitmap<'_, T> {} pub(crate) struct RowBitmapMut<'a, T> { rows: MutCow<'a, [PointerMut]>, width: usize, } unsafe impl Send for RowBitmapMut<'_, T> {} impl RowBitmapMut<'_, MaybeUninit> { #[inline] pub(crate) unsafe fn assume_init<'maybeowned>(&'maybeowned mut self) -> RowBitmap<'maybeowned, T> { #[allow(clippy::transmute_ptr_to_ptr)] RowBitmap { width: self.width, rows: std::mem::transmute::<&'maybeowned [PointerMut>], &'maybeowned [Pointer]>(self.rows.borrow_mut()), } } } impl RowBitmap<'_, T> { pub fn rows(&self) -> impl Iterator { let width = self.width; self.rows.iter().map(move |row| { unsafe { std::slice::from_raw_parts(row.0, width) } }) } } enum MutCow<'a, T: ?Sized> { Owned(Box), #[allow(dead_code)] /// This is optional, for FFI only Borrowed(&'a mut T), } impl MutCow<'_, T> { #[must_use] pub fn borrow_mut(&mut self) -> &mut T { match self { Self::Owned(a) => a, Self::Borrowed(a) => a, } } } impl<'a, T: Sync + Send + Copy + 'static> RowBitmapMut<'a, T> { #[inline] #[must_use] pub fn new_contiguous(data: &mut [T], width: usize) -> Self { Self { rows: MutCow::Owned(data.chunks_exact_mut(width).map(|r| PointerMut(r.as_mut_ptr())).collect()), width, } } /// Inner pointers must be valid for `'a` too, and at least `width` large each #[inline] #[cfg(feature = "_internal_c_ffi")] #[must_use] pub unsafe fn new(rows: &'a mut [*mut T], width: usize) -> Self { Self { rows: MutCow::Borrowed(&mut *(rows as *mut [*mut T] as *mut [PointerMut])), width, } } pub fn rows_mut(&mut self) -> impl Iterator + Send { let width = self.width; self.rows.borrow_mut().iter().map(move |row| { unsafe { std::slice::from_raw_parts_mut(row.0, width) } }) } pub(crate) fn chunks(&mut self, chunk_size: usize) -> impl Iterator> { self.rows.borrow_mut().chunks_mut(chunk_size).map(|chunk| RowBitmapMut { width: self.width, rows: MutCow::Borrowed(chunk), }) } #[must_use] pub(crate) fn len(&mut self) -> usize { self.rows.borrow_mut().len() } }