jpegxl-rs-0.11.2+libjxl-0.11.1/.cargo_vcs_info.json0000644000000001470000000000100150260ustar { "git": { "sha1": "c609dcde9a612bbcdd9cea279c1c588c31720373" }, "path_in_vcs": "jpegxl-rs" }jpegxl-rs-0.11.2+libjxl-0.11.1/CHANGELOG.md000064400000000000000000000033601046102023000154270ustar 00000000000000# Changelog ## [Unreleased] ## [0.11.2+libjxl-0.11.1](https://github.com/inflation/jpegxl-rs/compare/jpegxl-rs-v0.11.1+libjxl-0.11.0...jpegxl-rs-v0.11.2+libjxl-0.11.1) ### 📦 Dependencies - Update `libjxl` to v0.11.1 - ([71f188a](https://github.com/inflation/jpegxl-rs/commit/71f188a331fcbc5c1ec9358ffbcc9e34f6f269c7)) ## [0.11.1+libjxl-0.11.0](https://github.com/inflation/jpegxl-rs/compare/jpegxl-rs-v0.11.0+libjxl-0.11.0...jpegxl-rs-v0.11.1+libjxl-0.11.0) - 2024-10-01 ### 🐛 Bug Fixes - Fix doc gen ### 📚 Documentation - Remove docsrs-specific reference to deleted "threads" feature ## [0.11.0+libjxl-0.11.0](https://github.com/inflation/jpegxl-rs/compare/jpegxl-rs-v0.10.4+libjxl-0.10.3...jpegxl-rs-v0.11.0+libjxl-0.11.0) - 2024-09-27 ### ⛰️ Features - Update JPEG quality setting in encoder ([#74](https://github.com/inflation/jpegxl-rs/pull/74)) ### 🐛 Bug Fixes - Update release configuration for jpegxl-rs and jpegxl-sys packages - Change ffi function types to use `c-unwind` ABI - Change `JxlBoxType` to use system char type ### 🚜 Refactor - Move `libjxl` functions into modules - Remove threads feature and update dependencies. - Don't use `-sys` in `-rs` with default features enabled ### 📚 Documentation - Convert `libjxl` doc to rustdoc format with help from @copilot - Remove unnecessary feature attribute in thread pool implementations - Update how docs are generated ([#73](https://github.com/inflation/jpegxl-rs/pull/73)) ### 📦 Dependencies - Bump thiserror from 1.0.61 to 1.0.64 - Bump pretty_assertions from 1.4.0 to 1.4.1 - Bump derive_builder from 0.20.0 to 0.20.1 - Bump testresult from 0.4.0 to 0.4.1 - Bump image from 0.25.1 to 0.25.2 ### ⚙️ Miscellaneous Tasks - Update release-plz workflow and config jpegxl-rs-0.11.2+libjxl-0.11.1/COPYING000064400000000000000000001045141046102023000146540ustar 00000000000000 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. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .jpegxl-rs-0.11.2+libjxl-0.11.1/Cargo.toml0000644000000044230000000000100130250ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.74.0" name = "jpegxl-rs" version = "0.11.2+libjxl-0.11.1" authors = ["Inflation "] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "Safe Rust wrapper for JPEG XL reference implementation" readme = "README.md" keywords = [ "jpeg-xl", "jxl", ] categories = [ "api-bindings", "encoding", "multimedia::images", ] license = "GPL-3.0-or-later" repository = "https://github.com/inflation/jpegxl-rs" [package.metadata.docs.rs] features = ["docs"] rustdoc-args = [ "--cfg", "docsrs", ] [lib] name = "jpegxl_rs" path = "src/lib.rs" bench = false [[bench]] name = "decode" path = "benches/decode.rs" harness = false required-features = ["bench"] [[bench]] name = "encode" path = "benches/encode.rs" harness = false required-features = ["bench"] [dependencies.byteorder] version = "1.5.0" [dependencies.derive_builder] version = "0.20.2" [dependencies.half] version = "2.4.1" [dependencies.image] version = "0.25.5" optional = true default-features = false [dependencies.jpegxl-sys] version = "0.11.2" default-features = false [dependencies.thiserror] version = "2.0.3" [dev-dependencies.image] version = "0.25.5" features = [ "jpeg", "png", ] default-features = false [dev-dependencies.lcms2] version = "6.1.0" [dev-dependencies.pretty_assertions] version = "1.4.1" [dev-dependencies.testresult] version = "0.4.1" [features] bench = [] default = ["image"] docs = ["jpegxl-sys/docs"] image = ["dep:image"] vendored = ["jpegxl-sys/vendored"] [target.'cfg(not(target_family = "wasm"))'.dev-dependencies.criterion] version = "0.5.1" [lints.clippy] pedantic = "warn" [lints.rust] missing_docs = "warn" [lints.rust.unexpected_cfgs] level = "warn" priority = 0 check-cfg = ["cfg(coverage_nightly)"] jpegxl-rs-0.11.2+libjxl-0.11.1/Cargo.toml.orig000064400000000000000000000030701046102023000165030ustar 00000000000000[package] authors = ["Inflation "] categories = ["api-bindings", "encoding", "multimedia::images"] description = "Safe Rust wrapper for JPEG XL reference implementation" edition = "2021" keywords = ["jpeg-xl", "jxl"] license = "GPL-3.0-or-later" name = "jpegxl-rs" readme = "README.md" repository = "https://github.com/inflation/jpegxl-rs" version = "0.11.2+libjxl-0.11.1" rust-version.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lints.rust] missing_docs = "warn" unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage_nightly)'] } [lints.clippy] pedantic = "warn" [features] default = ["image"] image = ["dep:image"] vendored = ["jpegxl-sys/vendored"] docs = ["jpegxl-sys/docs"] bench = [] [dependencies] derive_builder = "0.20.2" image = { version = "0.25.5", optional = true, default-features = false } thiserror = "2.0.3" half = "2.4.1" byteorder = "1.5.0" [dependencies.jpegxl-sys] version = "0.11.2" path = "../jpegxl-sys" default-features = false [dev-dependencies] image = { version = "0.25.5", default-features = false, features = [ "jpeg", "png", ] } lcms2 = "6.1.0" pretty_assertions = "1.4.1" testresult = "0.4.1" [target.'cfg(not(target_family = "wasm"))'.dev-dependencies] criterion = "0.5.1" [package.metadata.docs.rs] rustdoc-args = ["--cfg", "docsrs"] features = ["docs"] [lib] bench = false path = "src/lib.rs" [[bench]] harness = false name = "decode" required-features = ["bench"] [[bench]] harness = false name = "encode" required-features = ["bench"] jpegxl-rs-0.11.2+libjxl-0.11.1/LICENSE000064400000000000000000000012721046102023000146230ustar 00000000000000jpegxl-rs is a safe wrapper around jpeg-xl decoder Copyright (C) 2020-2022 Inflation This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see .jpegxl-rs-0.11.2+libjxl-0.11.1/README.md000064400000000000000000000100161046102023000150710ustar 00000000000000# jpegxl-rs [![Documentation](https://docs.rs/jpegxl-rs/badge.svg)](https://docs.rs/jpegxl-rs/) [![Crates.io](https://img.shields.io/crates/v/jpegxl-rs.svg)](https://crates.io/crates/jpegxl-rs) [![dependency status](https://deps.rs/repo/github/inflation/jpegxl-rs/status.svg)](https://deps.rs/repo/github/inflation/jpegxl-rs) [![CI](https://github.com/inflation/jpegxl-rs/workflows/CI/badge.svg)](https://github.com/inflation/jpegxl-rs/actions?query=workflow%3ACI) [![codecov](https://codecov.io/gh/inflation/jpegxl-rs/branch/master/graph/badge.svg?token=3WMRUQ816H)](https://codecov.io/gh/inflation/jpegxl-rs) [![License: GPL-3.0-or-later](https://img.shields.io/crates/l/jpegxl-rs)](https://github.com/inflation/jpegxl-rs/blob/master/LICENSE) A safe JPEGXL wrapper over `libjxl` library. Check out the original [library](https://github.com/libjxl/libjxl) and the [bindings](https://github.com/inflation/jpegxl-rs/tree/master/jpegxl-sys). ## Building If you wish to specify a custom library path, set the `DEP_JXL_LIB` environment variable. Building `libjxl` and statically linking can be enabled by using the `vendored` feature. If you don't want to depend on C++ standard library, disable the feature `threads`. ## Usage Currently, `u8`, `u16`, `f16` and `f32` are supported as pixel types. ### Decoding ```rust use jpegxl_rs::*; use jpegxl_rs::decode::*; let mut decoder = decoder_builder().build().unwrap(); let sample = include_bytes!("../../samples/sample.jxl"); let (Metadata { width, height, ..}, pixels) = decoder.decode(sample).unwrap(); match pixels { Pixels::Float(data) => { /* do something with Vec data */ }, Pixels::Uint8(data) => { /* do something with Vec data */ }, Pixels::Uint16(data) => { /* do something with Vec data */ }, Pixels::Float16(data) => { /* do something with Vec data */ }, } // Multi-threading use jpegxl_rs::ThreadsRunner; let runner = ThreadsRunner::default(); let mut decoder = decoder_builder() .parallel_runner(&runner) .build() .unwrap(); // Customize pixel format let mut decoder = decoder_builder() .pixel_format(PixelFormat { num_channels: 3, endianness: Endianness::Big, align: 8 }) .build() .unwrap(); decoder.decode_with::(sample); // You can change the settings after initialization decoder.skip_reorientation = Some(true); // Reconstruct JPEG, fallback to pixels if JPEG reconstruction is not possible // This operation is finished in on pass let (metadata, data) = decoder.reconstruct(sample).unwrap(); match data { Data::Jpeg(jpeg) => {/* do something with the JPEG data */} Data::Pixels(pixels) => {/* do something with the pixels data */} } ``` ### Encoding ```rust use image::ImageReader; use jpegxl_rs::encoder_builder; use jpegxl_rs::encode::{EncoderResult, EncoderSpeed}; let sample = ImageReader::open("../samples/sample.png").unwrap().decode().unwrap().to_rgba16(); let mut encoder = encoder_builder().build().unwrap(); let buffer: EncoderResult = encoder.encode(&sample, sample.width(), sample.height()).unwrap(); // Set encoder options let mut encoder = encoder_builder() .lossless(true) .speed(EncoderSpeed::Falcon) .build() .unwrap(); // You can change the settings after initialization encoder.lossless = false; encoder.quality = 3.0; ``` ### [`image`](https://crates.io/crates/image) crate integration The integration is enabled by default. If you don't need it, disable `image` feature. ```rust use jpegxl_rs::image::ToDynamic; use jpegxl_rs::decoder_builder; use image::DynamicImage; let sample = std::fs::read("../samples/sample.jxl").unwrap(); let mut decoder = decoder_builder().build().unwrap(); let img = decoder.decode_to_image(&sample).unwrap(); let img = decoder.decode_to_image_with::(&sample).unwrap(); ``` License: GPL-3.0-or-later jpegxl-rs-0.11.2+libjxl-0.11.1/benches/decode.rs000064400000000000000000000026371046102023000170240ustar 00000000000000#![allow(missing_docs)] #![allow(clippy::missing_panics_doc)] use criterion::{black_box, criterion_group, criterion_main, Criterion}; use jpegxl_rs::{decoder_builder, parallel, ResizableRunner}; use parallel::threads_runner::ThreadsRunner; const SAMPLE: &[u8] = include_bytes!("../../samples/bench.jxl"); pub fn criterion_benchmark(c: &mut Criterion) { let mut group = c.benchmark_group("Decoder"); group.measurement_time(std::time::Duration::from_secs(120)); let decoder = decoder_builder().build().unwrap(); group.bench_function("single thread", |b| { b.iter_with_large_drop(|| decoder.decode_with::(black_box(SAMPLE)).unwrap()); }); let parallel_runner = ThreadsRunner::default(); let decoder = decoder_builder() .parallel_runner(¶llel_runner) .build() .unwrap(); group.bench_function("thread pool using default number of threads", |b| { b.iter_with_large_drop(|| decoder.decode_with::(black_box(SAMPLE)).unwrap()); }); let parallel_runner = ResizableRunner::default(); let decoder = decoder_builder() .parallel_runner(¶llel_runner) .build() .unwrap(); group.bench_function("resizable thread pool", |b| { b.iter_with_large_drop(|| decoder.decode_with::(black_box(SAMPLE)).unwrap()); }); group.finish(); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); jpegxl-rs-0.11.2+libjxl-0.11.1/benches/encode.rs000064400000000000000000000034451046102023000170340ustar 00000000000000#![allow(missing_docs)] #![allow(clippy::missing_panics_doc)] use criterion::{black_box, criterion_group, criterion_main, Criterion}; use jpegxl_rs::{encoder_builder, ResizableRunner, ThreadsRunner}; const SAMPLE: &[u8] = include_bytes!("../../samples/bench.png"); pub fn criterion_benchmark(c: &mut Criterion) { let mut group = c.benchmark_group("Encoder"); group.measurement_time(std::time::Duration::from_secs(120)); let sample = image::load_from_memory_with_format(SAMPLE, image::ImageFormat::Png) .unwrap() .to_rgb8(); let mut encoder = encoder_builder().build().unwrap(); group.bench_function("single thread", |b| { b.iter_with_large_drop(|| { encoder .encode::<_, u8>(black_box(sample.as_raw()), sample.width(), sample.height()) .unwrap() }); }); let parallel_runner = ThreadsRunner::default(); let mut encoder = encoder_builder() .parallel_runner(¶llel_runner) .build() .unwrap(); group.bench_function("thread pool using default number of threads", |b| { b.iter_with_large_drop(|| { encoder .encode::<_, u8>(black_box(sample.as_raw()), sample.width(), sample.height()) .unwrap() }); }); let parallel_runner = ResizableRunner::default(); let mut encoder = encoder_builder() .parallel_runner(¶llel_runner) .build() .unwrap(); group.bench_function("resizable thread pool", |b| { b.iter_with_large_drop(|| { encoder .encode::<_, u8>(black_box(sample.as_raw()), sample.width(), sample.height()) .unwrap() }); }); group.finish(); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches); jpegxl-rs-0.11.2+libjxl-0.11.1/src/common.rs000064400000000000000000000071311046102023000162430ustar 00000000000000/* This file is part of jpegxl-rs. jpegxl-rs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jpegxl-rs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jpegxl-rs. If not, see . */ //! Common types used across the crate use byteorder::{ByteOrder, NativeEndian, BE, LE}; use half::f16; use jpegxl_sys::common::types::{JxlDataType, JxlPixelFormat}; /// Endianness of the pixels pub type Endianness = jpegxl_sys::common::types::JxlEndianness; mod private { pub trait Sealed {} impl Sealed for u8 {} impl Sealed for u16 {} impl Sealed for half::f16 {} impl Sealed for f32 {} } /// Pixel data type. /// `u8`, `u16`, `f16` and `f32` are supported. pub trait PixelType: private::Sealed + Sized { /// Return the C const fn pixel_type() -> JxlDataType; /// Return number of bits per sample and exponential bits fn bits_per_sample() -> (u32, u32); /// Convert the data to the pixel type fn convert(data: &[u8], pixel_format: &JxlPixelFormat) -> Vec; } impl PixelType for u8 { fn pixel_type() -> JxlDataType { JxlDataType::Uint8 } fn bits_per_sample() -> (u32, u32) { (8, 0) } fn convert(data: &[u8], _pixel_format: &JxlPixelFormat) -> Vec { data.to_vec() } } impl PixelType for u16 { fn pixel_type() -> JxlDataType { JxlDataType::Uint16 } fn bits_per_sample() -> (u32, u32) { (16, 0) } fn convert(data: &[u8], pixel_format: &JxlPixelFormat) -> Vec { let mut buf = vec![u16::default(); data.len() / std::mem::size_of::()]; match pixel_format.endianness { Endianness::Native => NativeEndian::read_u16_into(data, buf.as_mut_slice()), Endianness::Little => LE::read_u16_into(data, buf.as_mut_slice()), Endianness::Big => BE::read_u16_into(data, buf.as_mut_slice()), } buf } } impl PixelType for f32 { fn pixel_type() -> JxlDataType { JxlDataType::Float } // Float representation needs exponential bits fn bits_per_sample() -> (u32, u32) { (32, 8) } fn convert(data: &[u8], pixel_format: &JxlPixelFormat) -> Vec { let mut buf = vec![f32::default(); data.len() / std::mem::size_of::()]; match pixel_format.endianness { Endianness::Native => NativeEndian::read_f32_into(data, buf.as_mut_slice()), Endianness::Little => LE::read_f32_into(data, buf.as_mut_slice()), Endianness::Big => BE::read_f32_into(data, buf.as_mut_slice()), } buf } } impl PixelType for f16 { fn pixel_type() -> JxlDataType { JxlDataType::Float16 } fn bits_per_sample() -> (u32, u32) { (16, 5) } fn convert(data: &[u8], pixel_format: &JxlPixelFormat) -> Vec { data.chunks_exact(std::mem::size_of::()) .map(|v| { f16::from_bits(match pixel_format.endianness { Endianness::Native => NativeEndian::read_u16(v), Endianness::Little => LE::read_u16(v), Endianness::Big => BE::read_u16(v), }) }) .collect() } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/decode/result.rs000064400000000000000000000062231046102023000175150ustar 00000000000000/* This file is part of jpegxl-rs. jpegxl-rs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jpegxl-rs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jpegxl-rs. If not, see . */ use half::f16; use jpegxl_sys::common::types::{JxlDataType, JxlPixelFormat}; use super::Orientation; use crate::common::PixelType; /// Result of decoding #[derive(Debug)] pub struct Metadata { /// Width of the image pub width: u32, /// Height of the image pub height: u32, /// Upper bound on the intensity level present in the image in nits pub intensity_target: f32, /// Lower bound on the intensity level present in the image pub min_nits: f32, /// Orientation pub orientation: Orientation, /// Number of color channels per pixel _without_ alpha channel, from metadata pub num_color_channels: u32, /// Whether the image has an alpha channel, from metadata pub has_alpha_channel: bool, /// Intrinsic width of the image. /// Applications are advised to resample the decoded image to the intrinsic dimensions pub intrinsic_width: u32, /// Intrinsic height of the image. /// Applications are advised to resample the decoded image to the intrinsic dimensions pub intrinsic_height: u32, /// ICC profile pub icc_profile: Option>, } /// Pixels returned from the decoder #[derive(Debug)] pub enum Pixels { /// `f32` pixels Float(Vec), /// `u8` pixels Uint8(Vec), /// `u16` pixels Uint16(Vec), /// `f16` pixels Float16(Vec), } impl Pixels { pub(crate) fn new(data: Vec, pixel_format: &JxlPixelFormat) -> Self { match pixel_format.data_type { JxlDataType::Float => Self::Float(f32::convert(&data, pixel_format)), JxlDataType::Uint8 => Self::Uint8(data), JxlDataType::Uint16 => Self::Uint16(u16::convert(&data, pixel_format)), JxlDataType::Float16 => Self::Float16(f16::convert(&data, pixel_format)), } } } /// Reconstruction result pub enum Data { /// JPEG Jpeg(Vec), /// Pixels Pixels(Pixels), } #[cfg(test)] mod tests { use super::*; #[test] #[cfg_attr(coverage_nightly, coverage(off))] fn test_derive() { println!( "{:?}", Metadata { width: 0, height: 0, intensity_target: 0.0, min_nits: 0.0, orientation: Orientation::Identity, num_color_channels: 0, has_alpha_channel: false, intrinsic_width: 0, intrinsic_height: 0, icc_profile: None, } ); println!("{:?}", Pixels::Float(vec![])); } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/decode.rs000064400000000000000000000430271046102023000162020ustar 00000000000000/* * This file is part of jpegxl-rs. * * jpegxl-rs is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jpegxl-rs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jpegxl-rs. If not, see . */ //! Decoder of JPEG XL format use std::{mem::MaybeUninit, ptr::null}; #[allow(clippy::wildcard_imports)] use jpegxl_sys::{ common::types::{JxlDataType, JxlPixelFormat}, decode::*, metadata::codestream_header::{JxlBasicInfo, JxlOrientation}, }; use crate::{ common::{Endianness, PixelType}, errors::{check_dec_status, DecodeError}, memory::MemoryManager, parallel::ParallelRunner, utils::check_valid_signature, }; mod result; pub use result::*; /// Basic information pub type BasicInfo = JxlBasicInfo; /// Progressive decoding steps pub type ProgressiveDetail = JxlProgressiveDetail; /// Orientation pub type Orientation = JxlOrientation; /// Desired Pixel Format #[derive(Clone, Copy, Debug)] pub struct PixelFormat { /// Amount of channels available in a pixel buffer. /// /// 1. single-channel data, e.g. grayscale or a single extra channel /// 2. single-channel + alpha /// 3. trichromatic, e.g. RGB /// 4. trichromatic + alpha /// /// # Default /// 0, which means determined automatically from color channels and alpha bits pub num_channels: u32, /// Whether multibyte data types are represented in big endian or little /// endian format. This applies to `u16`, `f16`, and `f32`. /// /// # Default /// [`Endianness::Native`] pub endianness: Endianness, /// Align scanlines to a multiple of align bytes. /// /// # Default /// 0, which means requiring no alignment (which has the same effect as value 1) pub align: usize, } impl Default for PixelFormat { fn default() -> Self { Self { num_channels: 0, endianness: Endianness::Native, align: 0, } } } /// JPEG XL Decoder #[derive(Builder)] #[builder(build_fn(skip, error = "None"))] #[builder(setter(strip_option))] pub struct JxlDecoder<'pr, 'mm> { /// Opaque pointer to the underlying decoder #[builder(setter(skip))] ptr: *mut jpegxl_sys::decode::JxlDecoder, /// Override desired pixel format pub pixel_format: Option, /// Enables or disables preserving of as-in-bitstream pixel data orientation. /// If it is set to `true`, the decoder will skip applying the transformation /// /// # Default /// `false`, and the returned pixel data is re-oriented pub skip_reorientation: Option, /// Enables or disables preserving of associated alpha channels. /// If it is set to `true`, the colors will be unpremultiplied based on the alpha channel /// /// # Default /// `false`, and return the pixel data "as is". pub unpremul_alpha: Option, /// Enables or disables rendering spot colors. /// If it is set to `false`, then spot colors are not rendered, and have to be retrieved /// separately. This is useful for printing applications /// /// # Default /// `true`, and spot colors are rendered, which is OK for viewing the decoded image pub render_spotcolors: Option, /// Enables or disables coalescing of zero-duration frames. /// For loading a multi-layer still image as separate layers (as opposed to the merged image), /// coalescing has to be disabled /// /// # Default /// `true`, and all frames have the image dimensions, and are blended if needed. pub coalescing: Option, /// Perform tone mapping to the peak display luminance. /// /// # Note /// This is provided for convenience and the exact tone mapping that is performed /// is not meant to be considered authoritative in any way. It may change from version /// to version pub desired_intensity_target: Option, /// Configures whether to get boxes in raw mode or in decompressed mode. /// /// # Default /// false, and the boxes are returned in raw mode pub decompress: Option, /// Configures at which progressive steps in frame decoding /// /// # Default /// [`ProgressiveDetail::DC`] pub progressive_detail: Option, /// Set if need ICC profile /// /// # Default /// `false` pub icc_profile: bool, /// Set initial buffer for JPEG reconstruction /// Larger buffer could make reconstruction faster by doing fewer reallocation /// /// Default: 512 KiB pub init_jpeg_buffer: usize, /// Set parallel runner pub parallel_runner: Option<&'pr dyn ParallelRunner>, /// Set memory manager pub memory_manager: Option<&'mm dyn MemoryManager>, } impl<'pr, 'mm> JxlDecoderBuilder<'pr, 'mm> { /// Build a [`JxlDecoder`] /// /// # Errors /// Return [`DecodeError::CannotCreateDecoder`] if it fails to create the decoder. pub fn build(&mut self) -> Result, DecodeError> { let mm = self.memory_manager.flatten(); let dec = unsafe { mm.map_or_else( || JxlDecoderCreate(null()), |mm| JxlDecoderCreate(&mm.manager()), ) }; if dec.is_null() { return Err(DecodeError::CannotCreateDecoder); } Ok(JxlDecoder { ptr: dec, pixel_format: self.pixel_format.flatten(), skip_reorientation: self.skip_reorientation.flatten(), unpremul_alpha: self.unpremul_alpha.flatten(), render_spotcolors: self.render_spotcolors.flatten(), coalescing: self.coalescing.flatten(), desired_intensity_target: self.desired_intensity_target.flatten(), decompress: self.decompress.flatten(), progressive_detail: self.progressive_detail.flatten(), icc_profile: self.icc_profile.unwrap_or_default(), init_jpeg_buffer: self.init_jpeg_buffer.unwrap_or(512 * 1024), parallel_runner: self.parallel_runner.flatten(), memory_manager: mm, }) } } impl<'pr, 'mm> JxlDecoder<'pr, 'mm> { pub(crate) fn decode_internal( &self, data: &[u8], data_type: Option, with_icc_profile: bool, mut reconstruct_jpeg_buffer: Option<&mut Vec>, format: *mut JxlPixelFormat, pixels: &mut Vec, ) -> Result { let Some(sig) = check_valid_signature(data) else { return Err(DecodeError::InvalidInput); }; if !sig { return Err(DecodeError::InvalidInput); } let mut basic_info = MaybeUninit::uninit(); let mut icc = if with_icc_profile { Some(vec![]) } else { None }; self.setup_decoder(with_icc_profile, reconstruct_jpeg_buffer.is_some())?; let next_in = data.as_ptr(); let avail_in = std::mem::size_of_val(data) as _; check_dec_status(unsafe { JxlDecoderSetInput(self.ptr, next_in, avail_in) })?; unsafe { JxlDecoderCloseInput(self.ptr) }; let mut status; loop { use JxlDecoderStatus as s; status = unsafe { JxlDecoderProcessInput(self.ptr) }; match status { s::NeedMoreInput | s::Error => return Err(DecodeError::GenericError), // Get the basic info s::BasicInfo => { check_dec_status(unsafe { JxlDecoderGetBasicInfo(self.ptr, basic_info.as_mut_ptr()) })?; if let Some(pr) = self.parallel_runner { pr.callback_basic_info(unsafe { &*basic_info.as_ptr() }); } } // Get color encoding s::ColorEncoding => { self.get_icc_profile(unsafe { icc.as_mut().unwrap_unchecked() })?; } // Get JPEG reconstruction buffer s::JPEGReconstruction => { // Safety: JpegReconstruction is only called when reconstruct_jpeg_buffer // is not None let buf = unsafe { reconstruct_jpeg_buffer.as_mut().unwrap_unchecked() }; buf.resize(self.init_jpeg_buffer, 0); check_dec_status(unsafe { JxlDecoderSetJPEGBuffer(self.ptr, buf.as_mut_ptr(), buf.len()) })?; } // JPEG buffer need more space s::JPEGNeedMoreOutput => { // Safety: JpegNeedMoreOutput is only called when reconstruct_jpeg_buffer // is not None let buf = unsafe { reconstruct_jpeg_buffer.as_mut().unwrap_unchecked() }; let need_to_write = unsafe { JxlDecoderReleaseJPEGBuffer(self.ptr) }; buf.resize(buf.len() + need_to_write, 0); check_dec_status(unsafe { JxlDecoderSetJPEGBuffer(self.ptr, buf.as_mut_ptr(), buf.len()) })?; } // Get the output buffer s::NeedImageOutBuffer => { self.output(unsafe { &*basic_info.as_ptr() }, data_type, format, pixels)?; } s::FullImage => continue, s::Success => { if let Some(buf) = reconstruct_jpeg_buffer.as_mut() { let remaining = unsafe { JxlDecoderReleaseJPEGBuffer(self.ptr) }; buf.truncate(buf.len() - remaining); buf.shrink_to_fit(); } unsafe { JxlDecoderReset(self.ptr) }; let info = unsafe { basic_info.assume_init() }; return Ok(Metadata { width: info.xsize, height: info.ysize, intensity_target: info.intensity_target, min_nits: info.min_nits, orientation: info.orientation, num_color_channels: info.num_color_channels, has_alpha_channel: info.alpha_bits > 0, intrinsic_width: info.intrinsic_xsize, intrinsic_height: info.intrinsic_ysize, icc_profile: icc, }); } s::NeedPreviewOutBuffer => todo!(), s::BoxNeedMoreOutput => todo!(), s::PreviewImage => todo!(), s::Frame => todo!(), s::Box => todo!(), s::BoxComplete => todo!(), s::FrameProgression => todo!(), } } } fn setup_decoder(&self, icc: bool, reconstruct_jpeg: bool) -> Result<(), DecodeError> { if let Some(runner) = self.parallel_runner { check_dec_status(unsafe { JxlDecoderSetParallelRunner(self.ptr, runner.runner(), runner.as_opaque_ptr()) })?; } let events = { use JxlDecoderStatus::{BasicInfo, ColorEncoding, FullImage, JPEGReconstruction}; let mut events = BasicInfo as i32 | FullImage as i32; if icc { events |= ColorEncoding as i32; } if reconstruct_jpeg { events |= JPEGReconstruction as i32; } events }; check_dec_status(unsafe { JxlDecoderSubscribeEvents(self.ptr, events) })?; if let Some(val) = self.skip_reorientation { check_dec_status(unsafe { JxlDecoderSetKeepOrientation(self.ptr, val.into()) })?; } if let Some(val) = self.unpremul_alpha { check_dec_status(unsafe { JxlDecoderSetUnpremultiplyAlpha(self.ptr, val.into()) })?; } if let Some(val) = self.render_spotcolors { check_dec_status(unsafe { JxlDecoderSetRenderSpotcolors(self.ptr, val.into()) })?; } if let Some(val) = self.coalescing { check_dec_status(unsafe { JxlDecoderSetCoalescing(self.ptr, val.into()) })?; } if let Some(val) = self.desired_intensity_target { check_dec_status(unsafe { JxlDecoderSetDesiredIntensityTarget(self.ptr, val) })?; } Ok(()) } fn get_icc_profile(&self, icc_profile: &mut Vec) -> Result<(), DecodeError> { let mut icc_size = 0; check_dec_status(unsafe { JxlDecoderGetICCProfileSize(self.ptr, JxlColorProfileTarget::Data, &mut icc_size) })?; icc_profile.resize(icc_size, 0); check_dec_status(unsafe { JxlDecoderGetColorAsICCProfile( self.ptr, JxlColorProfileTarget::Data, icc_profile.as_mut_ptr(), icc_size, ) })?; Ok(()) } fn output( &self, info: &BasicInfo, data_type: Option, format: *mut JxlPixelFormat, pixels: &mut Vec, ) -> Result<(), DecodeError> { let data_type = match data_type { Some(v) => v, None => match (info.bits_per_sample, info.exponent_bits_per_sample) { (x, 0) if x <= 8 => JxlDataType::Uint8, (x, 0) if x <= 16 => JxlDataType::Uint16, (16, _) => JxlDataType::Float16, (32, _) => JxlDataType::Float, (x, _) => return Err(DecodeError::UnsupportedBitWidth(x)), }, }; let f = self.pixel_format.unwrap_or_default(); let pixel_format = JxlPixelFormat { num_channels: if f.num_channels == 0 { info.num_color_channels + u32::from(info.alpha_bits > 0) } else { f.num_channels }, data_type, endianness: f.endianness, align: f.align, }; let mut size = 0; check_dec_status(unsafe { JxlDecoderImageOutBufferSize(self.ptr, &pixel_format, &mut size) })?; pixels.resize(size, 0); check_dec_status(unsafe { JxlDecoderSetImageOutBuffer(self.ptr, &pixel_format, pixels.as_mut_ptr().cast(), size) })?; unsafe { *format = pixel_format }; Ok(()) } /// Decode a JPEG XL image /// /// # Errors /// Return a [`DecodeError`] when internal decoder fails pub fn decode(&self, data: &[u8]) -> Result<(Metadata, Pixels), DecodeError> { let mut buffer = vec![]; let mut pixel_format = MaybeUninit::uninit(); let metadata = self.decode_internal( data, None, self.icc_profile, None, pixel_format.as_mut_ptr(), &mut buffer, )?; Ok(( metadata, Pixels::new(buffer, unsafe { &pixel_format.assume_init() }), )) } /// Decode a JPEG XL image to a specific pixel type /// /// # Errors /// Return a [`DecodeError`] when internal decoder fails pub fn decode_with( &self, data: &[u8], ) -> Result<(Metadata, Vec), DecodeError> { let mut buffer = vec![]; let mut pixel_format = MaybeUninit::uninit(); let metadata = self.decode_internal( data, Some(T::pixel_type()), self.icc_profile, None, pixel_format.as_mut_ptr(), &mut buffer, )?; // Safety: type `T` is set by user and provide to the decoder to determine output data type let buf = unsafe { let pixel_format = pixel_format.assume_init(); debug_assert!(T::pixel_type() == pixel_format.data_type); T::convert(&buffer, &pixel_format) }; Ok((metadata, buf)) } /// Reconstruct JPEG data. Fallback to pixels if JPEG reconstruction fails /// /// # Note /// You can reconstruct JPEG data or get pixels in one go /// /// # Errors /// Return a [`DecodeError`] when internal decoder fails pub fn reconstruct(&self, data: &[u8]) -> Result<(Metadata, Data), DecodeError> { let mut buffer = vec![]; let mut pixel_format = MaybeUninit::uninit(); let mut jpeg_buf = vec![]; let metadata = self.decode_internal( data, None, self.icc_profile, Some(&mut jpeg_buf), pixel_format.as_mut_ptr(), &mut buffer, )?; Ok(( metadata, if jpeg_buf.is_empty() { Data::Pixels(Pixels::new(buffer, unsafe { &pixel_format.assume_init() })) } else { Data::Jpeg(jpeg_buf) }, )) } } impl<'prl, 'mm> Drop for JxlDecoder<'prl, 'mm> { fn drop(&mut self) { unsafe { JxlDecoderDestroy(self.ptr) }; } } /// Return a [`JxlDecoderBuilder`] with default settings #[must_use] pub fn decoder_builder<'prl, 'mm>() -> JxlDecoderBuilder<'prl, 'mm> { JxlDecoderBuilder::default() } #[cfg(test)] mod tests { use super::*; #[test] #[allow(clippy::clone_on_copy)] fn test_derive() { let e = PixelFormat::default().clone(); println!("{e:?}"); _ = decoder_builder().clone(); } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/encode/frame.rs000064400000000000000000000055051046102023000173050ustar 00000000000000use std::marker::PhantomData; use jpegxl_sys::common::types::{JxlEndianness, JxlPixelFormat}; use crate::{common::PixelType, EncodeError}; use super::{EncoderResult, JxlEncoder}; /// A frame for the encoder, consisting of the pixels and its options #[allow(clippy::module_name_repetitions)] pub struct EncoderFrame<'data, T: PixelType> { pub(crate) data: &'data [T], num_channels: Option, endianness: Option, align: Option, } impl<'data, T: PixelType> EncoderFrame<'data, T> { /// Create a default frame from the data. /// /// Use RGB(3) channels, native endianness and no alignment. pub fn new(data: &'data [T]) -> Self { Self { data, num_channels: None, endianness: None, align: None, } } /// Set the number of channels of the source. /// /// _Note_: If you want to use alpha channel, add here #[must_use] pub fn num_channels(mut self, value: u32) -> Self { self.num_channels = Some(value); self } /// Set the endianness of the source. #[must_use] pub fn endianness(mut self, value: JxlEndianness) -> Self { self.endianness = Some(value); self } /// Set the align of the source. /// Align scanlines to a multiple of align bytes, or 0 to require no alignment at all #[must_use] pub fn align(mut self, value: usize) -> Self { self.align = Some(value); self } pub(crate) fn pixel_format(&self) -> JxlPixelFormat { JxlPixelFormat { num_channels: self.num_channels.unwrap_or(3), data_type: T::pixel_type(), endianness: self.endianness.unwrap_or(JxlEndianness::Native), align: self.align.unwrap_or(0), } } } /// A wrapper type for encoding multiple frames pub struct MultiFrames<'enc, 'prl, 'mm, U>( pub(crate) &'enc mut JxlEncoder<'prl, 'mm>, pub(crate) PhantomData, ) where 'prl: 'enc, 'mm: 'enc; impl MultiFrames<'_, '_, '_, U> { /// Add a frame to the encoder /// # Errors /// Return [`EncodeError`] if the internal encoder fails to add a frame pub fn add_frame(self, frame: &EncoderFrame) -> Result { self.0.add_frame(frame)?; Ok(self) } /// Add a JPEG raw frame to the encoder /// # Errors /// Return [`EncodeError`] if the internal encoder fails to add a jpeg frame pub fn add_jpeg_frame(self, data: &[u8]) -> Result { self.0.add_jpeg_frame(data)?; Ok(self) } /// Encode a JPEG XL image from the frames /// # Errors /// Return [`EncodeError`] if the internal encoder fails to encode pub fn encode(self) -> Result, EncodeError> { self.0.start_encoding() } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/encode/metadata.rs000064400000000000000000000013611046102023000177670ustar 00000000000000use jpegxl_sys::common::types::JxlBoxType; /// Metadata box pub enum Metadata<'d> { /// EXIF /// The contents of this box must be prepended by a 4-byte tiff header offset, /// which may be 4 zero bytes in case the tiff header follows immediately. Exif(&'d [u8]), /// XMP/IPTC metadata Xmp(&'d [u8]), /// JUMBF superbox Jumb(&'d [u8]), /// Custom Metadata. /// Type should not start with `jxl`, `JXL`, or conflict with other box type, /// and should be registered with MP4RA (mp4ra.org). Custom([u8; 4], &'d [u8]), } impl Metadata<'_> { #[must_use] pub(crate) fn box_type(t: [u8; 4]) -> JxlBoxType { JxlBoxType(unsafe { std::mem::transmute::<[u8; 4], [std::ffi::c_char; 4]>(t) }) } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/encode/options.rs000064400000000000000000000032441046102023000177040ustar 00000000000000use std::mem::MaybeUninit; use jpegxl_sys::{color::color_encoding::JxlColorEncoding, encoder::encode as api}; /// Encoding speed #[derive(Debug, Clone, Copy)] pub enum EncoderSpeed { /// Fastest, 1 Lightning = 1, /// 2 Thunder = 2, /// 3 Falcon = 3, /// 4 Cheetah, /// 5 Hare, /// 6 Wombat, /// 7, default Squirrel, /// 8 Kitten, /// 9 Tortoise, /// Slowest, 10 Glacier, } impl std::default::Default for EncoderSpeed { fn default() -> Self { Self::Squirrel } } /// Encoding color profile #[derive(Debug, Clone, Copy)] pub enum ColorEncoding { /// SRGB, default for uint pixel types Srgb, /// Linear SRGB, default for float pixel types LinearSrgb, /// SRGB, images with only luma channel SrgbLuma, /// Linear SRGB with only luma channel LinearSrgbLuma, } impl From for JxlColorEncoding { fn from(val: ColorEncoding) -> Self { use ColorEncoding::{LinearSrgb, LinearSrgbLuma, Srgb, SrgbLuma}; let mut color_encoding = MaybeUninit::uninit(); unsafe { match val { Srgb => api::JxlColorEncodingSetToSRGB(color_encoding.as_mut_ptr(), false), LinearSrgb => { api::JxlColorEncodingSetToLinearSRGB(color_encoding.as_mut_ptr(), false); } SrgbLuma => api::JxlColorEncodingSetToSRGB(color_encoding.as_mut_ptr(), true), LinearSrgbLuma => { api::JxlColorEncodingSetToLinearSRGB(color_encoding.as_mut_ptr(), true); } } color_encoding.assume_init() } } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/encode.rs000064400000000000000000000405231046102023000162120ustar 00000000000000/* This file is part of jpegxl-rs. jpegxl-rs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jpegxl-rs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jpegxl-rs. If not, see . */ //! Encoder of JPEG XL format use std::{marker::PhantomData, mem::MaybeUninit, ops::Deref, ptr::null}; #[allow(clippy::wildcard_imports)] use jpegxl_sys::encoder::encode::*; use crate::{ common::PixelType, errors::EncodeError, memory::MemoryManager, parallel::ParallelRunner, }; mod options; pub use options::*; mod metadata; pub use metadata::*; mod frame; pub use frame::*; // MARK: Utility types /// Encoder result pub struct EncoderResult { /// Output binary data pub data: Vec, _pixel_type: PhantomData, } impl Deref for EncoderResult { type Target = [u8]; fn deref(&self) -> &Self::Target { self.data.as_ref() } } // MARK: Encoder /// JPEG XL Encoder #[derive(Builder)] #[builder(build_fn(skip, error = "None"))] #[builder(setter(strip_option))] #[allow(clippy::struct_excessive_bools)] pub struct JxlEncoder<'prl, 'mm> { /// Opaque pointer to the underlying encoder #[builder(setter(skip))] enc: *mut jpegxl_sys::encoder::encode::JxlEncoder, /// Opaque pointer to the encoder options #[builder(setter(skip))] options_ptr: *mut JxlEncoderFrameSettings, /// Set alpha channel /// /// Default: false pub has_alpha: bool, /// Set lossless /// /// Default: false pub lossless: bool, /// Set speed /// /// Default: `Squirrel` (7). pub speed: EncoderSpeed, /// Set quality for lossy compression: target max butteraugli distance, lower = higher quality /// /// Range: 0 .. 15.
/// 0.0 = mathematically lossless (however, use `lossless` to use true lossless).
/// 1.0 = visually lossless.
/// Recommended range: 0.5 .. 3.0.
/// Default value: 1.0.
/// If `lossless` is set to `true`, this value is unused and implied to be 0. pub quality: f32, /// Configure the encoder to use the JPEG XL container format /// /// Using the JPEG XL container format allows to store metadata such as JPEG reconstruction; /// but it adds a few bytes to the encoded file for container headers /// even if there is no extra metadata. pub use_container: bool, /// Configure the encoder to use the original color profile /// /// If the input image has a color profile, it will be used for the encoded image. /// Otherwise, an internal fixed color profile is chosen (which should be smaller). /// /// When lossless recompressing JPEG image, you must set this to true. /// /// Default: `false` pub uses_original_profile: bool, /// Set the decoding speed tier /// /// Minimum is 0 (highest quality), and maximum is 4 (lowest quality). Default is 0. pub decoding_speed: i64, /// Set initial output buffer size in bytes. /// Anything less than 32 bytes will be rounded up to 32 bytes. /// /// Default: 512 KiB pub init_buffer_size: usize, /// Set color encoding /// /// Default: SRGB pub color_encoding: ColorEncoding, /// Set parallel runner /// /// Default: `None`, indicating single thread execution pub parallel_runner: Option<&'prl dyn ParallelRunner>, /// Whether box is used in encoder use_box: bool, /// Set memory manager #[allow(dead_code)] memory_manager: Option<&'mm dyn MemoryManager>, } impl<'prl, 'mm> JxlEncoderBuilder<'prl, 'mm> { /// Build a [`JxlEncoder`] /// /// # Errors /// Return [`EncodeError::CannotCreateEncoder`] if it fails to create the encoder pub fn build(&self) -> Result, EncodeError> { let mm = self.memory_manager.flatten(); let enc = unsafe { mm.map_or_else( || JxlEncoderCreate(null()), |mm| JxlEncoderCreate(&mm.manager()), ) }; if enc.is_null() { return Err(EncodeError::CannotCreateEncoder); } let options_ptr = unsafe { JxlEncoderFrameSettingsCreate(enc, null()) }; let init_buffer_size = self.init_buffer_size .map_or(512 * 1024, |v| if v < 32 { 32 } else { v }); Ok(JxlEncoder { enc, options_ptr, has_alpha: self.has_alpha.unwrap_or_default(), lossless: self.lossless.unwrap_or_default(), speed: self.speed.unwrap_or_default(), quality: self.quality.unwrap_or(1.0), use_container: self.use_container.unwrap_or_default(), uses_original_profile: self.uses_original_profile.unwrap_or_default(), decoding_speed: self.decoding_speed.unwrap_or_default(), init_buffer_size, color_encoding: self.color_encoding.unwrap_or(ColorEncoding::Srgb), parallel_runner: self.parallel_runner.flatten(), use_box: self.use_box.unwrap_or_default(), memory_manager: mm, }) } /// Set the `quality` parameter from a JPEG-style quality factor (0-100, higher is better /// quality). pub fn jpeg_quality(&mut self, quality: f32) -> &mut Self { // SAFETY: the C API has no safety requirements. self.quality = Some(unsafe { JxlEncoderDistanceFromQuality(quality) }); self } } // MARK: Private helper functions impl JxlEncoder<'_, '_> { /// Error mapping from underlying C const to [`EncodeError`] enum #[cfg_attr(coverage_nightly, coverage(off))] fn check_enc_status(&self, status: JxlEncoderStatus) -> Result<(), EncodeError> { match status { JxlEncoderStatus::Success => Ok(()), JxlEncoderStatus::Error => match unsafe { JxlEncoderGetError(self.enc) } { JxlEncoderError::OK => unreachable!(), JxlEncoderError::Generic => Err(EncodeError::GenericError), JxlEncoderError::OutOfMemory => Err(EncodeError::OutOfMemory), JxlEncoderError::Jbrd => Err(EncodeError::Jbrd), JxlEncoderError::BadInput => Err(EncodeError::BadInput), JxlEncoderError::NotSupported => Err(EncodeError::NotSupported), JxlEncoderError::ApiUsage => Err(EncodeError::ApiUsage), }, JxlEncoderStatus::NeedMoreOutput => Err(EncodeError::NeedMoreOutput), } } // Set options fn set_options(&self) -> Result<(), EncodeError> { self.check_enc_status(unsafe { JxlEncoderUseContainer(self.enc, self.use_container) })?; self.check_enc_status(unsafe { JxlEncoderSetFrameLossless(self.options_ptr, self.lossless) })?; self.check_enc_status(unsafe { JxlEncoderFrameSettingsSetOption( self.options_ptr, JxlEncoderFrameSettingId::Effort, self.speed as _, ) })?; self.check_enc_status(unsafe { JxlEncoderSetFrameDistance(self.options_ptr, self.quality) })?; self.check_enc_status(unsafe { JxlEncoderFrameSettingsSetOption( self.options_ptr, JxlEncoderFrameSettingId::DecodingSpeed, self.decoding_speed, ) })?; Ok(()) } // Setup the encoder fn setup_encoder( &self, width: u32, height: u32, (bits, exp): (u32, u32), has_alpha: bool, ) -> Result<(), EncodeError> { if let Some(runner) = self.parallel_runner { unsafe { self.check_enc_status(JxlEncoderSetParallelRunner( self.enc, runner.runner(), runner.as_opaque_ptr(), ))?; } } self.set_options()?; let mut basic_info = unsafe { let mut info = MaybeUninit::uninit(); JxlEncoderInitBasicInfo(info.as_mut_ptr()); info.assume_init() }; basic_info.xsize = width; basic_info.ysize = height; basic_info.have_container = self.use_container.into(); basic_info.uses_original_profile = self.uses_original_profile.into(); basic_info.bits_per_sample = bits; basic_info.exponent_bits_per_sample = exp; if has_alpha { basic_info.num_extra_channels = 1; basic_info.alpha_bits = bits; basic_info.alpha_exponent_bits = exp; } else { basic_info.num_extra_channels = 0; basic_info.alpha_bits = 0; basic_info.alpha_exponent_bits = 0; } match self.color_encoding { ColorEncoding::SrgbLuma | ColorEncoding::LinearSrgbLuma => { basic_info.num_color_channels = 1; } _ => (), } if let Some(pr) = self.parallel_runner { pr.callback_basic_info(&basic_info); } self.check_enc_status(unsafe { JxlEncoderSetBasicInfo(self.enc, &basic_info) })?; self.check_enc_status(unsafe { JxlEncoderSetColorEncoding(self.enc, &self.color_encoding.into()) }) } // Add a frame fn add_frame(&self, frame: &EncoderFrame) -> Result<(), EncodeError> { self.check_enc_status(unsafe { JxlEncoderAddImageFrame( self.options_ptr, &frame.pixel_format(), frame.data.as_ptr().cast(), std::mem::size_of_val(frame.data), ) }) } // Add a frame from JPEG raw data fn add_jpeg_frame(&self, data: &[u8]) -> Result<(), EncodeError> { self.check_enc_status(unsafe { JxlEncoderAddJPEGFrame( self.options_ptr, data.as_ptr().cast(), std::mem::size_of_val(data), ) }) } fn _internal(&mut self) -> Result, EncodeError> { unsafe { JxlEncoderCloseInput(self.enc) }; let mut buffer = vec![0; self.init_buffer_size]; let mut next_out = buffer.as_mut_ptr().cast(); let mut avail_out = buffer.len(); let mut status; loop { status = unsafe { JxlEncoderProcessOutput(self.enc, &mut next_out, &mut avail_out) }; if status != JxlEncoderStatus::NeedMoreOutput { break; } unsafe { let offset = next_out.offset_from(buffer.as_ptr()); debug_assert!(offset >= 0); buffer.resize(buffer.len() * 2, 0); next_out = buffer.as_mut_ptr().offset(offset); avail_out = buffer.len().wrapping_add_signed(-offset); } } buffer.truncate(next_out as usize - buffer.as_ptr() as usize); self.check_enc_status(status)?; unsafe { JxlEncoderReset(self.enc) }; self.options_ptr = unsafe { JxlEncoderFrameSettingsCreate(self.enc, null()) }; buffer.shrink_to_fit(); Ok(buffer) } // Start encoding fn start_encoding(&mut self) -> Result, EncodeError> { Ok(EncoderResult { data: self._internal()?, _pixel_type: PhantomData, }) } } // MARK: Public interface impl<'prl, 'mm> JxlEncoder<'prl, 'mm> { /// Set a specific encoder frame setting /// /// # Errors /// Return [`EncodeError`] if it fails to set frame option pub fn set_frame_option( &mut self, option: JxlEncoderFrameSettingId, value: i64, ) -> Result<(), EncodeError> { self.check_enc_status(unsafe { JxlEncoderFrameSettingsSetOption(self.options_ptr, option, value) }) } /// Return a wrapper type for adding multiple frames to the encoder /// /// # Errors /// Return [`EncodeError`] if it fails to set up the encoder pub fn multiple<'enc, U: PixelType>( &'enc mut self, width: u32, height: u32, ) -> Result, EncodeError> { self.setup_encoder(width, height, U::bits_per_sample(), self.has_alpha)?; Ok(MultiFrames::<'enc, 'prl, 'mm, U>(self, PhantomData)) } /// Add a metadata box to the encoder /// /// # Errors /// Return [`EncodeError`] if it fails to add metadata pub fn add_metadata(&mut self, metadata: &Metadata, compress: bool) -> Result<(), EncodeError> { let (&t, &data) = match metadata { Metadata::Exif(data) => (b"Exif", data), Metadata::Xmp(data) => (b"xml ", data), Metadata::Jumb(data) => (b"jumb", data), Metadata::Custom(t, data) => (t, data), }; if !self.use_box { self.check_enc_status(unsafe { JxlEncoderUseBoxes(self.enc) })?; self.use_box = true; } self.check_enc_status(unsafe { JxlEncoderAddBox( self.enc, &Metadata::box_type(t), data.as_ptr().cast(), data.len(), compress.into(), ) }) } /// Encode a JPEG XL image from existing raw JPEG data /// /// Note: Only support output pixel type of `u8`. Ignore alpha channel settings /// /// # Errors /// Return [`EncodeError`] if the internal encoder fails to encode pub fn encode_jpeg(&mut self, data: &[u8]) -> Result, EncodeError> { if let Some(runner) = self.parallel_runner { unsafe { self.check_enc_status(JxlEncoderSetParallelRunner( self.enc, runner.runner(), runner.as_opaque_ptr(), ))?; } } self.set_options()?; // If using container format, store JPEG reconstruction metadata self.check_enc_status(unsafe { JxlEncoderStoreJPEGMetadata(self.enc, true) })?; self.add_jpeg_frame(data)?; self.start_encoding() } /// Encode a JPEG XL image from pixels /// /// Note: Use RGB(3) channels, native endianness and no alignment. /// Ignore alpha channel settings /// /// # Errors /// Return [`EncodeError`] if the internal encoder fails to encode pub fn encode( &mut self, data: &[T], width: u32, height: u32, ) -> Result, EncodeError> { self.setup_encoder(width, height, U::bits_per_sample(), self.has_alpha)?; self.add_frame(&EncoderFrame::new(data))?; self.start_encoding::() } /// Encode a JPEG XL image from a frame. /// See [`EncoderFrame`] for custom options of the original pixels. /// /// # Errors /// Return [`EncodeError`] if the internal encoder fails to encode pub fn encode_frame( &mut self, frame: &EncoderFrame, width: u32, height: u32, ) -> Result, EncodeError> { self.setup_encoder(width, height, U::bits_per_sample(), self.has_alpha)?; self.add_frame(frame)?; self.start_encoding::() } } impl Drop for JxlEncoder<'_, '_> { fn drop(&mut self) { unsafe { JxlEncoderDestroy(self.enc) }; } } /// Return a [`JxlEncoderBuilder`] with default settings #[must_use] pub fn encoder_builder<'prl, 'mm>() -> JxlEncoderBuilder<'prl, 'mm> { JxlEncoderBuilder::default() } // MARK: Tests #[cfg(test)] mod tests { use super::*; use testresult::TestResult; #[test] #[allow(clippy::clone_on_copy)] fn test_derive() { let e = EncoderSpeed::default().clone(); println!("{e:?}"); let e = ColorEncoding::Srgb.clone(); println!("{e:?}"); _ = encoder_builder().clone(); } #[test] fn test_usebox() -> TestResult { let mut encoder = encoder_builder().build()?; let metadata = Metadata::Exif(&[0, 1, 2, 3]); encoder.add_metadata(&metadata, true)?; assert!(encoder.use_box); Ok(()) } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/errors.rs000064400000000000000000000115021046102023000162640ustar 00000000000000/* This file is part of jpegxl-rs. jpegxl-rs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jpegxl-rs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jpegxl-rs. If not, see . */ //! Decoder and encoder errors use thiserror::Error; use jpegxl_sys::{decode::JxlDecoderStatus, encoder::encode::JxlEncoderError}; /// Errors derived from [`JxlDecoderStatus`] #[derive(Error, Debug)] pub enum DecodeError { /// Cannot create a decoder #[error("Cannot create a decoder")] CannotCreateDecoder, /// Unknown Error #[error( "Generic Error. Please build `libjxl` from source (using `vendored` feature) in debug mode to get more information. Check `stderr` for any internal error messages." )] GenericError, /// Invalid input #[error("The input does not contain a valid codestream or container")] InvalidInput, /// Unsupported Pixel bit width #[error("Unsupported Pixel bit width: {0}")] UnsupportedBitWidth(u32), /// Internal error, usually invalid usages of the `libjxl` library #[error("Internal error, please file an issus: {0}")] InternalError(&'static str), /// Unknown status #[error("Unknown status: `{0:?}`")] UnknownStatus(JxlDecoderStatus), } /// Errors derived from [`JxlEncoderStatus`][jpegxl_sys::encoder::encode::JxlEncoderStatus] /// and [`JxlEncoderError`] #[derive(Error, Debug)] pub enum EncodeError { /// Cannot create an encoder #[error("Cannot create an encoder")] CannotCreateEncoder, /// Generic Error #[error( "Generic Error. Please build `libjxl` from source (using `vendored` feature) in debug mode to get more information. Check `stderr` for any internal error messages." )] GenericError, /// Not Supported #[error("Encoder does not support it (yet)")] NotSupported, /// Need more output #[error("Need more output")] NeedMoreOutput, /// Out of memory #[error("Out of memory")] OutOfMemory, /// JPEG bitstream reconstruction data could not be represented (e.g. too much tail data) #[error("JPEG bitstream reconstruction data could not be represented")] Jbrd, /// Input is invalid (e.g. corrupt JPEG file or ICC profile) #[error("Input is invalid")] BadInput, /// The encoder API is used in an incorrect way. In this case, /// a debug build of libjxl should output a specific error message #[error("The encoder API is used in an incorrect way")] ApiUsage, /// Unknown status #[error("Unknown status: `{0:?}`")] UnknownStatus(JxlEncoderError), } /// Error mapping from underlying C const to [`DecodeError`] enum pub(crate) fn check_dec_status(status: JxlDecoderStatus) -> Result<(), DecodeError> { match status { JxlDecoderStatus::Success => Ok(()), JxlDecoderStatus::Error => Err(DecodeError::GenericError), _ => Err(DecodeError::UnknownStatus(status)), } } #[cfg(test)] mod tests { use testresult::TestResult; use super::*; #[test] #[cfg_attr(coverage_nightly, coverage(off))] fn decode_invalid_data() -> TestResult { let decoder = crate::decoder_builder().build()?; assert!(matches!( decoder.decode_with::(&[]), Err(DecodeError::InvalidInput) )); assert!(matches!( decoder.decode_with::(&[0; 64]), Err(DecodeError::InvalidInput) )); assert!(matches!( decoder.decode(&crate::tests::SAMPLE_JXL[..100]), Err(DecodeError::GenericError) )); assert!(matches!( check_dec_status(JxlDecoderStatus::Error), Err(DecodeError::GenericError) )); println!( "{x}, {x:?}", x = check_dec_status(JxlDecoderStatus::BasicInfo).unwrap_err() ); Ok(()) } #[test] #[cfg_attr(coverage_nightly, coverage(off))] fn encode_invalid_data() -> TestResult { let mut encoder = crate::encoder_builder().has_alpha(true).build()?; assert!(matches!( encoder.encode::(&[], 0, 0), Err(EncodeError::ApiUsage) )); assert!(matches!( encoder.encode::(&[1.0, 1.0, 1.0, 0.5], 1, 1), Err(EncodeError::ApiUsage) )); println!( "{x}, {x:?}", x = EncodeError::UnknownStatus(JxlEncoderError::OK) ); Ok(()) } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/image.rs000064400000000000000000000170451046102023000160420ustar 00000000000000/* * This file is part of jpegxl-rs. * * jpegxl-rs is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jpegxl-rs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jpegxl-rs. If not, see . */ //! `image` crate integration use std::mem::MaybeUninit; use image::{DynamicImage, ImageBuffer}; use jpegxl_sys::common::types::{JxlDataType, JxlPixelFormat}; use crate::{ common::PixelType, decode::{JxlDecoder, Metadata}, DecodeError, }; /// Extension trait for [`JxlDecoder`] pub trait ToDynamic { /// Decode the JPEG XL image to a [`DynamicImage`] /// /// # Errors /// Return a [`DecodeError`] when internal decoding fails. /// Return `Ok(None)` when the image is not representable as a [`DynamicImage`] fn decode_to_image(&self, data: &[u8]) -> Result, DecodeError>; /// Decode the JPEG XL image to a [`DynamicImage`] with a specific pixel type /// /// # Errors /// Return a [`DecodeError`] when internal decoding fails. /// Return `Ok(None)` when the image is not representable as a [`DynamicImage`] fn decode_to_image_with( &self, data: &[u8], ) -> Result, DecodeError>; } impl<'pr, 'mm> ToDynamic for JxlDecoder<'pr, 'mm> { fn decode_to_image(&self, data: &[u8]) -> Result, DecodeError> { let mut buffer = vec![]; let mut pixel_format = MaybeUninit::uninit(); let metadata = self.decode_internal( data, None, false, None, pixel_format.as_mut_ptr(), &mut buffer, )?; let pixel_format = unsafe { pixel_format.assume_init() }; Ok(to_image(metadata, &pixel_format, buffer)) } fn decode_to_image_with( &self, data: &[u8], ) -> Result, DecodeError> { let mut buffer = vec![]; let mut pixel_format = MaybeUninit::uninit(); let metadata = self.decode_internal( data, Some(T::pixel_type()), false, None, pixel_format.as_mut_ptr(), &mut buffer, )?; let pixel_format = unsafe { pixel_format.assume_init() }; Ok(to_image(metadata, &pixel_format, buffer)) } } fn to_image( Metadata { width, height, .. }: Metadata, pixel_format: &JxlPixelFormat, buffer: Vec, ) -> Option { match (pixel_format.data_type, pixel_format.num_channels) { (JxlDataType::Float, 3) => { ImageBuffer::from_raw(width, height, f32::convert(&buffer, pixel_format)) .map(DynamicImage::ImageRgb32F) } (JxlDataType::Float, 4) => { ImageBuffer::from_raw(width, height, f32::convert(&buffer, pixel_format)) .map(DynamicImage::ImageRgba32F) } (JxlDataType::Uint8, 1) => { ImageBuffer::from_raw(width, height, buffer).map(DynamicImage::ImageLuma8) } (JxlDataType::Uint8, 2) => { ImageBuffer::from_raw(width, height, buffer).map(DynamicImage::ImageLumaA8) } (JxlDataType::Uint8, 3) => { ImageBuffer::from_raw(width, height, buffer).map(DynamicImage::ImageRgb8) } (JxlDataType::Uint8, 4) => { ImageBuffer::from_raw(width, height, buffer).map(DynamicImage::ImageRgba8) } (JxlDataType::Uint16, 1) => { ImageBuffer::from_raw(width, height, u16::convert(&buffer, pixel_format)) .map(DynamicImage::ImageLuma16) } (JxlDataType::Uint16, 2) => { ImageBuffer::from_raw(width, height, u16::convert(&buffer, pixel_format)) .map(DynamicImage::ImageLumaA16) } (JxlDataType::Uint16, 3) => { ImageBuffer::from_raw(width, height, u16::convert(&buffer, pixel_format)) .map(DynamicImage::ImageRgb16) } (JxlDataType::Uint16, 4) => { ImageBuffer::from_raw(width, height, u16::convert(&buffer, pixel_format)) .map(DynamicImage::ImageRgba16) } _ => None, } } #[cfg(test)] mod tests { use super::*; use crate::{ decode::PixelFormat, decoder_builder, tests::{SAMPLE_JXL, SAMPLE_JXL_GRAY, SAMPLE_PNG}, ThreadsRunner, }; use half::f16; use pretty_assertions::assert_eq; use testresult::TestResult; #[test] #[cfg_attr(coverage_nightly, coverage(off))] fn invalid() -> TestResult { let decoder = decoder_builder().build()?; assert!(decoder.decode_to_image(&[]).is_err()); assert!(decoder.decode_to_image_with::(&[]).is_err()); Ok(()) } #[test] #[cfg_attr(coverage_nightly, coverage(off))] fn simple() -> TestResult { let parallel_runner = ThreadsRunner::default(); let decoder = decoder_builder() .parallel_runner(¶llel_runner) .build()?; let img = decoder .decode_to_image(SAMPLE_JXL)? .expect("Failed to create DynamicImage"); let sample_png = image::load_from_memory_with_format(SAMPLE_PNG, image::ImageFormat::Png)?; assert_eq!(img.to_rgba16(), sample_png.to_rgba16()); Ok(()) } #[test] #[cfg_attr(coverage_nightly, coverage(off))] fn pixel_type() -> TestResult { let parallel_runner = ThreadsRunner::default(); let mut decoder = decoder_builder() .parallel_runner(¶llel_runner) .build()?; assert!(decoder.decode_to_image_with::(SAMPLE_JXL)?.is_none()); decoder.pixel_format = Some(PixelFormat { num_channels: 1, ..PixelFormat::default() }); decoder .decode_to_image_with::(SAMPLE_JXL_GRAY)? .unwrap(); decoder .decode_to_image_with::(SAMPLE_JXL_GRAY)? .unwrap(); assert!(decoder .decode_to_image_with::(SAMPLE_JXL_GRAY)? .is_none()); decoder.pixel_format = Some(PixelFormat { num_channels: 2, ..PixelFormat::default() }); decoder .decode_to_image_with::(SAMPLE_JXL_GRAY)? .unwrap(); decoder .decode_to_image_with::(SAMPLE_JXL_GRAY)? .unwrap(); assert!(decoder .decode_to_image_with::(SAMPLE_JXL_GRAY)? .is_none()); decoder.pixel_format = Some(PixelFormat { num_channels: 3, ..PixelFormat::default() }); decoder.decode_to_image_with::(SAMPLE_JXL)?.unwrap(); decoder.decode_to_image_with::(SAMPLE_JXL)?.unwrap(); decoder.decode_to_image_with::(SAMPLE_JXL)?.unwrap(); decoder.pixel_format = Some(PixelFormat { num_channels: 4, ..PixelFormat::default() }); decoder.decode_to_image_with::(SAMPLE_JXL)?.unwrap(); decoder.decode_to_image_with::(SAMPLE_JXL)?.unwrap(); decoder.decode_to_image_with::(SAMPLE_JXL)?.unwrap(); Ok(()) } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/lib.rs000064400000000000000000000023351046102023000155220ustar 00000000000000/* This file is part of jpegxl-rs. jpegxl-rs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jpegxl-rs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jpegxl-rs. If not, see . */ #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![cfg_attr(coverage_nightly, feature(coverage_attribute))] #![doc = include_str!("../README.md")] #[macro_use] extern crate derive_builder; mod common; pub mod decode; pub mod encode; mod errors; pub mod memory; pub mod parallel; pub mod utils; #[cfg(feature = "image")] pub mod image; #[cfg(test)] mod tests; pub use common::Endianness; pub use decode::decoder_builder; pub use encode::encoder_builder; pub use errors::{DecodeError, EncodeError}; pub use parallel::resizable_runner::ResizableRunner; pub use parallel::threads_runner::ThreadsRunner; jpegxl-rs-0.11.2+libjxl-0.11.1/src/memory.rs000064400000000000000000000107441046102023000162670ustar 00000000000000/* * This file is part of jpegxl-rs. * * jpegxl-rs is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jpegxl-rs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jpegxl-rs. If not, see . */ //! Memory manager interface use jpegxl_sys::common::memory_manager::{JpegxlAllocFunc, JpegxlFreeFunc, JxlMemoryManager}; /// General trait for a memory manager #[allow(clippy::module_name_repetitions)] pub trait MemoryManager { /// Return a custom allocating function fn alloc(&self) -> JpegxlAllocFunc; /// Return a custom deallocating function fn free(&self) -> JpegxlFreeFunc; /// Helper conversion function for C API #[must_use] fn manager(&self) -> JxlMemoryManager { JxlMemoryManager { opaque: (self as *const Self).cast_mut().cast(), alloc: Some(self.alloc()), free: Some(self.free()), } } } #[cfg(test)] pub(crate) mod tests { use std::{ ffi::c_void, ptr::null_mut, sync::atomic::{AtomicUsize, Ordering}, }; use testresult::TestResult; use crate::{decoder_builder, encoder_builder}; use super::*; /// Example implementation of [`MemoryManager`] of a fixed size allocator pub struct BumpManager { arena: Vec, footer: AtomicUsize, } impl BumpManager { pub(crate) fn new(n: usize) -> Self { Self { arena: vec![0; n], footer: AtomicUsize::new(0), } } } impl MemoryManager for BumpManager { fn alloc(&self) -> JpegxlAllocFunc { #[cfg_attr(coverage_nightly, coverage(off))] unsafe extern "C-unwind" fn alloc(opaque: *mut c_void, size: usize) -> *mut c_void { let mm = &mut *opaque.cast::(); let footer = mm.footer.load(Ordering::Acquire); let mut new = footer + size; loop { if new > mm.arena.len() { println!("Out of memory"); break null_mut(); } else if let Err(s) = mm.footer.compare_exchange_weak( footer, new, Ordering::AcqRel, Ordering::Relaxed, ) { new = s + size; } else { let addr = mm.arena.get_unchecked_mut(footer); break (addr as *mut u8).cast(); } } } alloc } fn free(&self) -> JpegxlFreeFunc { #[cfg_attr(coverage_nightly, coverage(off))] unsafe extern "C-unwind" fn free(_opaque: *mut c_void, _address: *mut c_void) {} free } } pub struct PanicManager {} impl MemoryManager for PanicManager { fn alloc(&self) -> JpegxlAllocFunc { #[cfg_attr(coverage_nightly, coverage(off))] unsafe extern "C-unwind" fn alloc(_opaque: *mut c_void, _size: usize) -> *mut c_void { panic!("Stack unwind test") } alloc } fn free(&self) -> JpegxlFreeFunc { #[cfg_attr(coverage_nightly, coverage(off))] unsafe extern "C-unwind" fn free(_opaque: *mut c_void, _address: *mut c_void) { debug_assert!(false, "Should not be called"); } free } } #[test] fn test_mm() -> TestResult { let mm = BumpManager::new(1024 * 1024 * 50); let dec = decoder_builder().memory_manager(&mm).build()?; let (meta, img) = dec.decode_with::(crate::tests::SAMPLE_JXL)?; let mut enc = encoder_builder().memory_manager(&mm).build()?; let _ = enc.encode::(&img, meta.width, meta.height)?; Ok(()) } #[test] #[should_panic = "Stack unwind test"] fn test_unwind() { let mm = PanicManager {}; let _ = decoder_builder().memory_manager(&mm).build().unwrap(); } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/parallel/resizable_runner.rs000064400000000000000000000060241046102023000221200ustar 00000000000000/* This file is part of jpegxl-rs. jpegxl-rs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jpegxl-rs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jpegxl-rs. If not, see . */ //! Wrapper for resizable thread pool implementation with C++ standard library use std::{ffi::c_void, ptr::null_mut}; use jpegxl_sys::threads::resizable_parallel_runner as api; use super::{JxlParallelRunner, ParallelRunner}; use crate::{decode::BasicInfo, memory::MemoryManager}; /// Wrapper for resizable thread pool implementation with C++ standard library pub struct ResizableRunner<'mm> { runner_ptr: *mut c_void, _memory_manager: Option<&'mm dyn MemoryManager>, } impl<'mm> ResizableRunner<'mm> { /// Construct with number of threads #[must_use] pub fn new(memory_manager: Option<&'mm dyn MemoryManager>) -> Option { let mm = memory_manager.map(MemoryManager::manager); let runner_ptr = unsafe { api::JxlResizableParallelRunnerCreate(mm.as_ref().map_or(null_mut(), |mm| mm)) }; if runner_ptr.is_null() { None } else { Some(Self { runner_ptr, _memory_manager: memory_manager, }) } } /// Set number of threads depending on the size of the image pub fn set_num_threads(&self, width: u64, height: u64) { let num = unsafe { api::JxlResizableParallelRunnerSuggestThreads(width, height) }; unsafe { api::JxlResizableParallelRunnerSetThreads(self.runner_ptr, num as usize) }; } } impl Default for ResizableRunner<'_> { fn default() -> Self { Self { runner_ptr: unsafe { api::JxlResizableParallelRunnerCreate(std::ptr::null()) }, _memory_manager: None, } } } impl ParallelRunner for ResizableRunner<'_> { fn runner(&self) -> JxlParallelRunner { api::JxlResizableParallelRunner } fn as_opaque_ptr(&self) -> *mut c_void { self.runner_ptr } fn callback_basic_info(&self, info: &BasicInfo) { self.set_num_threads(info.xsize.into(), info.ysize.into()); } } impl Drop for ResizableRunner<'_> { fn drop(&mut self) { unsafe { api::JxlResizableParallelRunnerDestroy(self.runner_ptr) }; } } #[cfg(test)] mod tests { use crate::memory::tests::BumpManager; use super::*; #[test] #[cfg_attr(coverage_nightly, coverage(off))] fn test_construction() { let memory_manager = BumpManager::new(1024); let parallel_runner = ResizableRunner::new(Some(&memory_manager)); assert!(parallel_runner.is_some()); } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/parallel/threads_runner.rs000064400000000000000000000055011046102023000215710ustar 00000000000000/* This file is part of jpegxl-rs. jpegxl-rs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jpegxl-rs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jpegxl-rs. If not, see . */ //! Wrapper for default thread pool implementation with C++ standard library use std::{ffi::c_void, ptr::null_mut}; #[allow(clippy::wildcard_imports)] use jpegxl_sys::threads::thread_parallel_runner::*; use super::{JxlParallelRunner, ParallelRunner}; use crate::memory::MemoryManager; /// Wrapper for default thread pool implementation with C++ standard library pub struct ThreadsRunner<'mm> { runner_ptr: *mut c_void, _memory_manager: Option<&'mm dyn MemoryManager>, } impl<'mm> ThreadsRunner<'mm> { /// Construct with number of threads #[must_use] pub fn new( memory_manager: Option<&'mm dyn MemoryManager>, num_workers: Option, ) -> Option { let mm = memory_manager.map(MemoryManager::manager); let runner_ptr = unsafe { JxlThreadParallelRunnerCreate( mm.as_ref().map_or(null_mut(), |mm| mm), num_workers.unwrap_or_else(|| JxlThreadParallelRunnerDefaultNumWorkerThreads()), ) }; if runner_ptr.is_null() { None } else { Some(Self { runner_ptr, _memory_manager: memory_manager, }) } } } impl Default for ThreadsRunner<'_> { fn default() -> Self { Self { runner_ptr: unsafe { JxlThreadParallelRunnerCreate( std::ptr::null(), JxlThreadParallelRunnerDefaultNumWorkerThreads(), ) }, _memory_manager: None, } } } impl ParallelRunner for ThreadsRunner<'_> { fn runner(&self) -> JxlParallelRunner { JxlThreadParallelRunner } fn as_opaque_ptr(&self) -> *mut c_void { self.runner_ptr } } impl Drop for ThreadsRunner<'_> { fn drop(&mut self) { unsafe { JxlThreadParallelRunnerDestroy(self.runner_ptr) }; } } #[cfg(test)] mod tests { use crate::memory::tests::BumpManager; use super::*; #[test] fn test_construction() { let memory_manager = BumpManager::new(1024); let parallel_runner = ThreadsRunner::new(Some(&memory_manager), Some(10)); assert!(parallel_runner.is_some()); } } jpegxl-rs-0.11.2+libjxl-0.11.1/src/parallel.rs000064400000000000000000000034151046102023000165500ustar 00000000000000/* This file is part of jpegxl-rs. jpegxl-rs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jpegxl-rs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jpegxl-rs. If not, see . */ //! Parallel runner interface //! # Example //! ``` //! #[cfg(feature = "image")] //! # || -> Result<(), Box> { //! use jpegxl_rs::{decoder_builder, parallel::threads_runner::ThreadsRunner}; //! // Use the default C++ Threads pool runner: //! let mut parallel_runner = ThreadsRunner::default(); //! let mut decoder = decoder_builder().parallel_runner(¶llel_runner).build()?; //! # Ok(()) //! # }; //! ``` //! use std::ffi::c_void; pub mod resizable_runner; pub mod threads_runner; use jpegxl_sys::threads::parallel_runner::JxlParallelRunner; pub use jpegxl_sys::threads::parallel_runner::{ JxlParallelRetCode, JxlParallelRunFunction, JxlParallelRunInit, }; use crate::decode::BasicInfo; /// JPEG XL Parallel Runner #[allow(clippy::module_name_repetitions)] pub trait ParallelRunner { /// Get a [`JxlParallelRunner`] for the parallel runner. fn runner(&self) -> JxlParallelRunner; /// Get an opaque pointer to the runner. fn as_opaque_ptr(&self) -> *mut c_void; /// Callback function after getting basic info #[allow(unused_variables)] fn callback_basic_info(&self, basic_info: &BasicInfo) {} } jpegxl-rs-0.11.2+libjxl-0.11.1/src/tests/decode.rs000064400000000000000000000120151046102023000173350ustar 00000000000000/* * This file is part of jpegxl-rs. * * jpegxl-rs is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jpegxl-rs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jpegxl-rs. If not, see . */ use std::io::Cursor; use half::f16; use image::ImageDecoder; use pretty_assertions::assert_eq; use testresult::TestResult; use crate::{ common::Endianness, decode::{Data, Metadata, PixelFormat, Pixels}, decoder_builder, DecodeError, }; use crate::{ResizableRunner, ThreadsRunner}; #[test] fn invalid() -> TestResult { let decoder = decoder_builder().build()?; assert!(matches!( decoder.decode(&[0x00, 0x00]), Err(DecodeError::InvalidInput) )); Ok(()) } #[test] fn simple() -> TestResult { let decoder = decoder_builder().icc_profile(true).build()?; let ( Metadata { width, height, icc_profile, .. }, data, ) = decoder.decode(super::SAMPLE_JXL)?; let Pixels::Uint16(data) = data else { return Err("Failed to decode".into()); }; assert_eq!(data.len(), (width * height * 4) as usize); // Check if icc profile is valid lcms2::Profile::new_icc(&icc_profile.expect("ICC profile not retrieved"))?; Ok(()) } #[test] fn sample_2bit() -> TestResult { let decoder = decoder_builder().build()?; let (Metadata { width, height, .. }, data) = decoder.decode(super::SAMPLE_JXL_2BIT)?; let Pixels::Uint8(data) = data else { return Err("Failed to decode".into()); }; assert_eq!(data.len(), (width * height * 3) as usize); Ok(()) } #[test] fn sample_gray() -> TestResult { let decoder = decoder_builder().build()?; let (Metadata { width, height, .. }, data) = decoder.decode(super::SAMPLE_JXL_GRAY)?; let Pixels::Uint16(data) = data else { return Err("Failed to decode".into()); }; assert_eq!(data.len(), (width * height) as usize); Ok(()) } #[test] fn pixel_types() -> TestResult { let mut decoder = decoder_builder().build()?; // Check different pixel types decoder.decode_with::(super::SAMPLE_JXL)?; decoder.decode_with::(super::SAMPLE_JXL)?; decoder.decode_with::(super::SAMPLE_JXL)?; decoder.decode_with::(super::SAMPLE_JXL)?; // Check endianness decoder.pixel_format = Some(PixelFormat { endianness: Endianness::Big, ..Default::default() }); decoder.decode_with::(super::SAMPLE_JXL)?; decoder.decode_with::(super::SAMPLE_JXL)?; decoder.pixel_format = Some(PixelFormat { endianness: Endianness::Little, ..Default::default() }); decoder.decode_with::(super::SAMPLE_JXL)?; Ok(()) } #[test] fn jpeg() -> TestResult { let decoder = decoder_builder().init_jpeg_buffer(512).build()?; let (_, data) = decoder.reconstruct(super::SAMPLE_JXL_JPEG)?; let Data::Jpeg(data) = data else { return Err("Failed to reconstruct".into()); }; let jpeg = image::codecs::jpeg::JpegDecoder::new(Cursor::new(data))?; let mut v = vec![0; jpeg.total_bytes().try_into().unwrap()]; jpeg.read_image(&mut v)?; let (_, data) = decoder.reconstruct(super::SAMPLE_JXL)?; assert!(matches!(data, Data::Pixels(Pixels::Uint16(_)))); Ok(()) } #[test] fn builder() -> TestResult { use crate::decode::ProgressiveDetail; let threads_runner = ThreadsRunner::default(); let resizable_runner = ResizableRunner::default(); let mut decoder = decoder_builder() .pixel_format(PixelFormat { num_channels: 3, endianness: Endianness::Big, align: 10, }) .desired_intensity_target(0.5) .coalescing(false) .progressive_detail(ProgressiveDetail::Passes) .render_spotcolors(false) .decompress(true) .unpremul_alpha(true) .skip_reorientation(true) .parallel_runner(&resizable_runner) .build()?; let (Metadata { width, height, .. }, data) = decoder.decode_with::(super::SAMPLE_JXL)?; assert_eq!(data.len(), (width * height * 3) as usize); // Set options after creating decoder decoder.pixel_format = Some(PixelFormat { num_channels: 4, endianness: Endianness::Little, ..PixelFormat::default() }); decoder.skip_reorientation = Some(true); decoder.parallel_runner = Some(&threads_runner); decoder.decode(super::SAMPLE_JXL)?; let (Metadata { width, height, .. }, data) = decoder.decode_with::(super::SAMPLE_JXL)?; assert_eq!(data.len(), (width * height * 4) as usize); Ok(()) } jpegxl-rs-0.11.2+libjxl-0.11.1/src/tests/encode.rs000064400000000000000000000157631046102023000173640ustar 00000000000000/* * This file is part of jpegxl-rs. * * jpegxl-rs is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jpegxl-rs is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jpegxl-rs. If not, see . */ use half::f16; use image::DynamicImage; use pretty_assertions::assert_eq; use testresult::TestResult; use crate::decode::Data; use crate::{ decoder_builder, encode::{ColorEncoding, EncoderFrame, EncoderResult, Metadata}, encoder_builder, Endianness, }; use crate::{encode::EncoderSpeed, ResizableRunner, ThreadsRunner}; fn get_sample() -> DynamicImage { image::load_from_memory_with_format(super::SAMPLE_PNG, image::ImageFormat::Png) .expect("Failed to get sample file") } #[test] fn simple() -> TestResult { let sample = get_sample().to_rgb8(); let mut encoder = encoder_builder().build()?; let result: EncoderResult = encoder.encode(sample.as_raw(), sample.width(), sample.height())?; let decoder = decoder_builder().build().expect("Failed to build decoder"); let _res = decoder.decode(&result)?; Ok(()) } #[test] fn jpeg() -> TestResult { let threads_runner = ThreadsRunner::default(); let mut encoder = encoder_builder() .parallel_runner(&threads_runner) .use_container(true) .uses_original_profile(true) .jpeg_quality(85.0) .build()?; let res = encoder.encode_jpeg(super::SAMPLE_JPEG)?; let (_, Data::Jpeg(reconstructed)) = decoder_builder().build()?.reconstruct(&res)? else { return Err("Failed to reconstruct JPEG".into()); }; assert_eq!(super::SAMPLE_JPEG, reconstructed); Ok(()) } #[test] fn metadata() -> TestResult { let sample = get_sample().to_rgb8(); let mut encoder = encoder_builder().build()?; encoder.add_metadata(&Metadata::Exif(super::SAMPLE_EXIF), true)?; encoder.add_metadata(&Metadata::Xmp(super::SAMPLE_XMP), true)?; let _res: EncoderResult = encoder.encode(sample.as_raw(), sample.width(), sample.height())?; Ok(()) } #[test] fn builder() -> TestResult { use crate::decode::Metadata; let sample = get_sample().to_rgba8(); let threads_runner = ThreadsRunner::default(); let mut encoder = encoder_builder() .has_alpha(true) .lossless(false) .speed(EncoderSpeed::Lightning) .quality(3.0) .color_encoding(ColorEncoding::LinearSrgb) .decoding_speed(4) .init_buffer_size(64) .parallel_runner(&threads_runner) .build()?; let res: EncoderResult = encoder.encode_frame( &EncoderFrame::new(sample.as_raw()).num_channels(4), sample.width(), sample.height(), )?; let decoder = decoder_builder().build().unwrap(); let ( Metadata { num_color_channels, has_alpha_channel, .. }, _, ) = decoder.decode(&res)?; assert_eq!(num_color_channels, 3); assert!(has_alpha_channel); Ok(()) } #[test] fn resizable() -> TestResult { let resizable_runner = ResizableRunner::default(); let sample = get_sample().to_rgb8(); let mut encoder = encoder_builder() .parallel_runner(&resizable_runner) .build()?; let _res: EncoderResult = encoder.encode(sample.as_raw(), sample.width(), sample.height())?; Ok(()) } #[test] fn pixel_type() -> TestResult { let mut encoder = encoder_builder().has_alpha(true).build()?; let decoder = decoder_builder().build()?; let sample = get_sample().to_rgba8(); // Check different pixel format let frame = EncoderFrame::new(sample.as_raw()).num_channels(4); let _res: EncoderResult = encoder.encode_frame(&frame, sample.width(), sample.height())?; let _res: EncoderResult = encoder.encode_frame(&frame, sample.width(), sample.height())?; let _res: EncoderResult = encoder.encode_frame(&frame, sample.width(), sample.height())?; encoder.has_alpha = false; let sample = get_sample().to_rgb8(); let _: EncoderResult = encoder.encode(sample.as_raw(), sample.width(), sample.height())?; let res: EncoderResult = encoder.encode(sample.as_raw(), sample.width(), sample.height())?; decoder.decode(&res)?; let _: EncoderResult = encoder.encode(sample.as_raw(), sample.width(), sample.height())?; let sample = get_sample().to_rgb32f(); let _: EncoderResult = encoder.encode(sample.as_raw(), sample.width(), sample.height())?; Ok(()) } #[test] fn multi_frames() -> TestResult { let sample = get_sample().to_rgb8(); let mut encoder = encoder_builder().use_container(true).build()?; let frame = EncoderFrame::new(sample.as_raw()) .endianness(Endianness::Native) .align(0); let result: EncoderResult = encoder .multiple(sample.width(), sample.height())? .add_frame(&frame)? .add_frame(&frame)? .encode()?; let decoder = decoder_builder().build()?; let _res = decoder.decode(&result)?; encoder.uses_original_profile = true; let result: EncoderResult = encoder .multiple(sample.width(), sample.height())? .add_jpeg_frame(super::SAMPLE_JPEG)? .add_jpeg_frame(super::SAMPLE_JPEG)? .encode()?; let _res = decoder.reconstruct(&result)?; Ok(()) } #[test] fn gray() -> TestResult { let sample = get_sample().to_luma8(); let mut encoder = encoder_builder() .color_encoding(ColorEncoding::SrgbLuma) .build()?; let decoder = decoder_builder().build()?; let result: EncoderResult = encoder.encode_frame( &EncoderFrame::new(sample.as_raw()).num_channels(1), sample.width(), sample.height(), )?; _ = decoder.decode(&result)?; encoder.color_encoding = ColorEncoding::LinearSrgbLuma; let result: EncoderResult = encoder.encode_frame( &EncoderFrame::new(sample.as_raw()).num_channels(1), sample.width(), sample.height(), )?; _ = decoder.decode(&result)?; encoder.set_frame_option( jpegxl_sys::encoder::encode::JxlEncoderFrameSettingId::BrotliEffort, 1, )?; Ok(()) } #[test] fn initial_buffer() -> TestResult { let mut encoder = encoder_builder().init_buffer_size(0).build()?; let sample = get_sample().to_rgb8(); let _: EncoderResult = encoder.encode(sample.as_raw(), sample.width(), sample.height())?; let _: EncoderResult = encoder.encode(sample.as_raw(), sample.width(), sample.height())?; let _: EncoderResult = encoder.encode(sample.as_raw(), sample.width(), sample.height())?; Ok(()) } jpegxl-rs-0.11.2+libjxl-0.11.1/src/tests.rs000064400000000000000000000011561046102023000161160ustar 00000000000000mod decode; mod encode; pub const SAMPLE_PNG: &[u8] = include_bytes!("../../samples/sample.png"); const SAMPLE_JPEG: &[u8] = include_bytes!("../../samples/sample.jpg"); const SAMPLE_EXIF: &[u8] = include_bytes!("../../samples/sample.exif"); const SAMPLE_XMP: &[u8] = include_bytes!("../../samples/sample.xmp"); pub const SAMPLE_JXL: &[u8] = include_bytes!("../../samples/sample.jxl"); const SAMPLE_JXL_JPEG: &[u8] = include_bytes!("../../samples/sample_jpg.jxl"); pub const SAMPLE_JXL_GRAY: &[u8] = include_bytes!("../../samples/sample_grey.jxl"); const SAMPLE_JXL_2BIT: &[u8] = include_bytes!("../../samples/2bit.jxl"); jpegxl-rs-0.11.2+libjxl-0.11.1/src/utils.rs000064400000000000000000000030001046102023000161020ustar 00000000000000/* This file is part of jpegxl-rs. jpegxl-rs is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. jpegxl-rs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with jpegxl-rs. If not, see . */ //! Utils functions when a decoder or encoder is not needed use jpegxl_sys::decode::{JxlSignature, JxlSignatureCheck}; /// Check if the signature of the input is valid. /// Return `None` if it needs more data. #[must_use] pub fn check_valid_signature(buf: &[u8]) -> Option { use JxlSignature::{Codestream, Container, Invalid, NotEnoughBytes}; match unsafe { JxlSignatureCheck(buf.as_ptr(), buf.len()) } { NotEnoughBytes => None, Invalid => Some(false), Codestream | Container => Some(true), } } #[cfg(test)] mod tests { use super::*; use crate::tests::SAMPLE_JXL; use pretty_assertions::assert_eq; #[test] fn test_signature() { assert!(check_valid_signature(&[]).is_none()); assert_eq!(check_valid_signature(&[0; 64]), Some(false)); assert_eq!(check_valid_signature(SAMPLE_JXL), Some(true)); } }