From 793621da9fdf49c56794d60f5dbf0709b8e471c6 Mon Sep 17 00:00:00 2001 From: scaramallion Date: Sun, 8 Mar 2020 13:47:25 +1100 Subject: [PATCH 1/4] Skeletons --- .coveragerc | 5 +- .gitmodules | 3 - .travis.yml | 51 +- LICENCE.txt | 604 +- MANIFEST.in | 3 - README.md | 35 +- build_tools/travis/install.sh | 24 +- codecov.yml | 5 +- pylibjpeg/__init__.py | 34 +- pylibjpeg/_config.py | 4 + pylibjpeg/_libjpeg.cpp | 9221 ----------------- pylibjpeg/_libjpeg.pyx | 160 - pylibjpeg/libjpeg.py | 246 - pylibjpeg/plugins.py | 78 + pylibjpeg/pydicom/__init__.py | 0 .../pixel_data_handler.py} | 35 +- pylibjpeg/src/libjpeg | 1 - pylibjpeg/src/pylibjpeg/decode.cpp | 333 - pylibjpeg/src/pylibjpeg/decode.hpp | 44 - pylibjpeg/src/pylibjpeg/streamhook.cpp | 355 - pylibjpeg/src/pylibjpeg/streamhook.hpp | 48 - pylibjpeg/src/pylibjpeg/utils.hpp | 35 - pylibjpeg/tests/README.md | 11 + pylibjpeg/tests/README.rst | 13 - pylibjpeg/tests/test_decode.py | 538 - pylibjpeg/tests/test_handler.py | 1156 --- pylibjpeg/tests/test_parameters.py | 320 - pylibjpeg/tests/test_plugins.py | 14 + pylibjpeg/tests/test_pydicom.py | 37 + pylibjpeg/tests/test_reconstruct.py | 60 - pylibjpeg/utils.py | 0 requirements.txt | 2 - setup.cfg | 2 + setup.py | 159 +- 34 files changed, 255 insertions(+), 13381 deletions(-) delete mode 100644 .gitmodules delete mode 100644 MANIFEST.in create mode 100644 pylibjpeg/_config.py delete mode 100644 pylibjpeg/_libjpeg.cpp delete mode 100644 pylibjpeg/_libjpeg.pyx delete mode 100755 pylibjpeg/libjpeg.py create mode 100644 pylibjpeg/plugins.py create mode 100644 pylibjpeg/pydicom/__init__.py rename pylibjpeg/{libjpeg_handler.py => pydicom/pixel_data_handler.py} (87%) delete mode 160000 pylibjpeg/src/libjpeg delete mode 100644 pylibjpeg/src/pylibjpeg/decode.cpp delete mode 100644 pylibjpeg/src/pylibjpeg/decode.hpp delete mode 100644 pylibjpeg/src/pylibjpeg/streamhook.cpp delete mode 100644 pylibjpeg/src/pylibjpeg/streamhook.hpp delete mode 100644 pylibjpeg/src/pylibjpeg/utils.hpp create mode 100644 pylibjpeg/tests/README.md delete mode 100644 pylibjpeg/tests/README.rst delete mode 100644 pylibjpeg/tests/test_decode.py delete mode 100644 pylibjpeg/tests/test_handler.py delete mode 100644 pylibjpeg/tests/test_parameters.py create mode 100644 pylibjpeg/tests/test_plugins.py create mode 100644 pylibjpeg/tests/test_pydicom.py delete mode 100644 pylibjpeg/tests/test_reconstruct.py create mode 100644 pylibjpeg/utils.py delete mode 100644 requirements.txt create mode 100644 setup.cfg diff --git a/.coveragerc b/.coveragerc index 2760d0a..70d6069 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,7 +2,6 @@ omit = pylibjpeg/tests/* pylibjpeg/scripts/* - pylibjpeg/data/* - pylibjpeg/src/* + pylibjpeg-data/* + pylibjpeg-libjpeg/* pydicom/* - pydicom-master/* diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 1c043df..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "pylibjpeg/src/libjpeg"] - path = pylibjpeg/src/libjpeg - url = https://github.com/thorfdbg/libjpeg.git diff --git a/.travis.yml b/.travis.yml index 9097d0c..3799051 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,6 @@ branches: language: python -# Build against pydicom master and current release matrix: include: # OSX first because it takes a long time to complete before_install @@ -14,6 +13,7 @@ matrix: env: - TEST_SUITE=osx - TRAVIS_PYTHON_VERSION=3.6.8 + - INSTALL_LIBJPEG=true # Windows - name: "Python 3.6, Windows + pydicom" os: windows @@ -21,59 +21,50 @@ matrix: env: - TEST_SUITE=windows - TRAVIS_PYTHON_VERSION=3.6.8 - # Conda next, also takes a while - - name: "Python 3.6, Ubuntu + conda + pydicom" - os: linux - dist: bionic - env: - - TEST_SUITE=conda - - TRAVIS_PYTHON_VERSION=3.6 - # Ubuntu with pydicom master next to find any issues quickly - - name: "Python 3.6, Ubuntu + pydicom master" - os: linux - dist: bionic - python: "3.6" - env: TEST_SUITE=pydicom_master - - name: "Python 3.7, Ubuntu + pydicom master" - os: linux - dist: bionic - python: "3.7" - env: TEST_SUITE=pydicom_master - - name: "Python 3.8, Ubuntu + pydicom master" - os: linux - dist: bionic - python: "3.8" - env: TEST_SUITE=pydicom_master + - INSTALL_LIBJPEG=true + # Ubuntu - name: "Python 3.6, Ubuntu" os: linux dist: bionic python: "3.6" - env: TEST_SUITE=solo + env: + - TEST_SUITE=solo + - INSTALL_LIBJPEG=true - name: "Python 3.7, Ubuntu" os: linux dist: bionic python: "3.7" - env: TEST_SUITE=solo + env: + - TEST_SUITE=solo + - INSTALL_LIBJPEG=true - name: "Python 3.8, Ubuntu" os: linux dist: bionic python: "3.8" - env: TEST_SUITE=solo + env: + - TEST_SUITE=solo + - INSTALL_LIBJPEG=true - name: "Python 3.6, Ubuntu + pydicom" os: linux dist: bionic python: "3.6" - env: TEST_SUITE=pydicom_release + env: + - TEST_SUITE=pydicom + - INSTALL_LIBJPEG=true - name: "Python 3.7, Ubuntu + pydicom" os: linux dist: bionic python: "3.7" - env: TEST_SUITE=pydicom_release + env: + - TEST_SUITE=pydicom + - INSTALL_LIBJPEG=true - name: "Python 3.8, Ubuntu + pydicom" os: linux dist: bionic python: "3.8" - env: TEST_SUITE=pydicom_release + env: + - TEST_SUITE=pydicom + - INSTALL_LIBJPEG=true # Install dependencies and package install: diff --git a/LICENCE.txt b/LICENCE.txt index b1caebe..f6a83eb 100644 --- a/LICENCE.txt +++ b/LICENCE.txt @@ -1,583 +1,21 @@ -pylibjpeg ---------- - -https://github.com/scaramallion/pylibjpeg - -Copyright (c) 2020 pylibjpeg contributors - -Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3 (see below) - -libjpeg -------- - -https://github.com/thorfdbg/libjpeg - -GNU GENERAL PUBLIC LICENSE - -Version 3, 29 June 2007 - -Copyright © 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 +MIT License + +Copyright (c) 2020 scaramallion and pylibjpeg contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index e9a8803..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,3 +0,0 @@ -recursive-include pylibjpeg/data/dcm *.dcm -recursive-include pylibjpeg/data/jpg *.* -recursive-include pylibjpeg/src * diff --git a/README.md b/README.md index bd71aa1..37e5682 100644 --- a/README.md +++ b/README.md @@ -3,39 +3,29 @@ ## pylibjpeg -A Python 3.6+ wrapper for Thomas Richter's -[libjpeg](https://github.com/thorfdbg/libjpeg), with a focus on providing JPEG +A Python 3.6+ framework for decoding JPEG images, with a focus on providing support for [pydicom](https://github.com/pydicom/pydicom). Linux, OSX and Windows are all supported. + ### Installation #### Installing the development version -Make sure [Python](https://www.python.org/) and [Git](https://git-scm.com/) are installed. For Windows, you also need to install the [Microsoft's C++ Build Tools](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools&rel=16). +Make sure [Python](https://www.python.org/) and [Git](https://git-scm.com/) are installed. ```bash -git clone --recurse-submodules https://github.com/pydicom/pylibjpeg +git clone https://github.com/pydicom/pylibjpeg python -m pip install pylibjpeg ``` -### Supported JPEG Formats - -| ISO/IEC Standard | ITU Equivalent | JPEG Format | -| --- | --- | --- | -| [10918](https://www.iso.org/standard/18902.html) | [T.81](https://www.itu.int/rec/T-REC-T.81/en) | [JPEG](https://jpeg.org/jpeg/index.html) | -| [14495](https://www.iso.org/standard/22397.html) | [T.87](https://www.itu.int/rec/T-REC-T.87/en) | [JPEG-LS](https://jpeg.org/jpegls/index.html) | -| [18477](https://www.iso.org/standard/62552.html) | | [JPEG XT](https://jpeg.org/jpegxt/) | +### Plugins -### Supported Transfer Syntaxes +By itself *pylibjpeg* is unable to decode any JPEG images, which is where the +plugins come in. To support the given JPEG format you'll first have to install +the corresponding package: -| UID | Description | -| --- | --- | -| 1.2.840.10008.1.2.4.50 | JPEG Baseline (Process 1) | -| 1.2.840.10008.1.2.4.51 | JPEG Extended (Process 2 and 4) | -| 1.2.840.10008.1.2.4.57 | JPEG Lossless, Non-Hierarchical (Process 14) | -| 1.2.840.10008.1.2.4.70 | JPEG Lossless, Non-Hierarchical, First-Order Prediction (Process 14 [Selection Value 1]) | -| 1.2.840.10008.1.2.4.80 | JPEG-LS Lossless | -| 1.2.840.10008.1.2.4.81 | JPEG-LS Lossy (Near-Lossless) Image Compression | +* JPEG, JPEG-LS and JPEG XT: [pylibjpeg-libjpeg](https://github.com/pydicom/pylibjpeg-libjpeg) +* JPEG2000: To be implemented ### Usage #### With pydicom @@ -45,15 +35,14 @@ Assuming you already have *pydicom* installed: from pydicom import dcmread from pydicom.data import get_testdata_file -# Importing the package automatically adds the pixel data handler +# With the pylibjpeg-libjpeg plugin import pylibjpeg -# Use pydicom as normal ds = dcmread(get_testdata_file('JPEG-LL.dcm')) arr = ds.pixel_array ``` -#### Without pydicom +#### Standalone ```python from pylibjpeg import decode diff --git a/build_tools/travis/install.sh b/build_tools/travis/install.sh index ee59c8f..a0b2185 100644 --- a/build_tools/travis/install.sh +++ b/build_tools/travis/install.sh @@ -7,11 +7,7 @@ echo "Test suite: " $TEST_SUITE echo "Working directory: " $PWD echo "" -if [[ "$TEST_SUITE" == "pydicom_master" ]]; then - pip install pytest pytest-cov - pip install git+https://github.com/pydicom/pydicom.git - python -c "import pydicom; print('pydicom version', pydicom.__version__)" -elif [[ "$TEST_SUITE" == "pydicom_release" ]]; then +if [[ "$TEST_SUITE" == "pydicom" ]]; then pip install pydicom pytest pytest-cov python -c "import pydicom; print('pydicom version', pydicom.__version__)" elif [[ "$TEST_SUITE" == 'osx' ]]; then @@ -27,7 +23,6 @@ elif [[ "$TEST_SUITE" == 'osx' ]]; then export PATH="/Users/travis/.pyenv/shims:${PATH}" pyenv virtualenv venv pyenv activate venv - python --version pip install --upgrade pip pip install pydicom pytest pytest-cov python -c "import pydicom; print('pydicom version', pydicom.__version__)" @@ -49,13 +44,6 @@ elif [[ "$TEST_SUITE" == 'conda' ]]; then conda install --yes -c conda-forge pydicom elif [[ "$TEST_SUITE" == 'windows' ]]; then choco install python --version $TRAVIS_PYTHON_VERSION - #ls /c - #echo "" - #echo "chocolatey installs:" - #ls /c/ProgramData/chocolatey/bin/ - #ls /c/Python36 # make this generic - #echo $PATH - #echo $CL export PATH="/c/Python36:/c/Python36/Scripts:$PATH" # make this generic python -m pip install --upgrade pip python -m pip install pydicom pytest pytest-cov @@ -63,6 +51,14 @@ else pip install pytest pytest-cov fi -python --version # Install the test data python -m pip install git+git://github.com/pydicom/pylibjpeg-data + +# Install plugins +if [[ "$INSTALL_LIBJPEG" == 'true' ]]; then + python -m pip install git+git://github.com/pydicom/pylibjpeg-libjpeg +fi + + + +python --version diff --git a/codecov.yml b/codecov.yml index 2a492a4..23a28b2 100644 --- a/codecov.yml +++ b/codecov.yml @@ -13,8 +13,7 @@ coverage: ignore: - "pylibjpeg/tests" - - "pylibjpeg/src" - "pylibjpeg/scripts" - - "pylibjpeg/data" - - "pydicom-master" + - "pylibjpeg-libjpeg" + - "pylibjpeg-data" - "pydicom" diff --git a/pylibjpeg/__init__.py b/pylibjpeg/__init__.py index 2a3eda5..0a5c39f 100644 --- a/pylibjpeg/__init__.py +++ b/pylibjpeg/__init__.py @@ -1,23 +1,49 @@ """Set package shortcuts.""" +import importlib +import logging import sys +from ._config import PLUGINS from ._version import __version__ -from .libjpeg import decode, add_handler, remove_handler, get_parameters +from .plugins import PluginManager + + +# Setup default logging +LOGGER = logging.getLogger('pynetdicom') +LOGGER.addHandler(logging.NullHandler()) +LOGGER.debug("pylibjpeg v{}".format(__version__)) + + +def debug_logger(): + """Setup the logging for debugging.""" + logger = logging.getLogger('pylibjpeg') + logger.handlers = [] + handler = logging.StreamHandler() + logger.setLevel(logging.DEBUG) + formatter = logging.Formatter('%(levelname).1s: %(message)s') + handler.setFormatter(formatter) + logger.addHandler(handler) + + +# TODO: remove this later +debug_logger() -# Add the testing data to pylibjpeg (if available) try: import data as _data globals()['data'] = _data # Add to cache - needed for pytest sys.modules['pylibjpeg.data'] = _data + LOGGER.debug('pylibjpeg-data module loaded') except ImportError: pass -# Add the pixel data handler to pydicom (if available) try: import pydicom - add_handler() + LOGGER.debug('pydicom module loaded') except ImportError: pass + + +_plugin_manager = PluginManager(PLUGINS) diff --git a/pylibjpeg/_config.py b/pylibjpeg/_config.py new file mode 100644 index 0000000..156cd6d --- /dev/null +++ b/pylibjpeg/_config.py @@ -0,0 +1,4 @@ +"""pylibjpeg configuration options.""" + +# A list of plugin package import names to try and interface with +PLUGINS = ['libjpeg'] diff --git a/pylibjpeg/_libjpeg.cpp b/pylibjpeg/_libjpeg.cpp deleted file mode 100644 index 0555c23..0000000 --- a/pylibjpeg/_libjpeg.cpp +++ /dev/null @@ -1,9221 +0,0 @@ -/* Generated by Cython 0.29.15 */ - -#define PY_SSIZE_T_CLEAN -#include "Python.h" -#ifndef Py_PYTHON_H - #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) - #error Cython requires Python 2.6+ or Python 3.3+. -#else -#define CYTHON_ABI "0_29_15" -#define CYTHON_HEX_VERSION 0x001D0FF0 -#define CYTHON_FUTURE_DIVISION 1 -#include -#ifndef offsetof - #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif -#define __PYX_COMMA , -#ifndef HAVE_LONG_LONG - #if PY_VERSION_HEX >= 0x02070000 - #define HAVE_LONG_LONG - #endif -#endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif -#ifdef PYPY_VERSION - #define CYTHON_COMPILING_IN_PYPY 1 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #undef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 0 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #if PY_VERSION_HEX < 0x03050000 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #undef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #undef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 1 - #undef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 0 - #undef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 0 - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#elif defined(PYSTON_VERSION) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 1 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#else - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 1 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) - #define CYTHON_USE_PYTYPE_LOOKUP 1 - #endif - #if PY_MAJOR_VERSION < 3 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #elif !defined(CYTHON_USE_PYLONG_INTERNALS) - #define CYTHON_USE_PYLONG_INTERNALS 1 - #endif - #ifndef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 1 - #endif - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #if PY_VERSION_HEX < 0x030300F0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #elif !defined(CYTHON_USE_UNICODE_WRITER) - #define CYTHON_USE_UNICODE_WRITER 1 - #endif - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #ifndef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 1 - #endif - #ifndef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 1 - #endif - #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) - #endif - #ifndef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) - #endif - #ifndef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) - #endif - #ifndef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) - #endif -#endif -#if !defined(CYTHON_FAST_PYCCALL) -#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) -#endif -#if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" - #undef SHIFT - #undef BASE - #undef MASK - #ifdef SIZEOF_VOID_P - enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; - #endif -#endif -#ifndef __has_attribute - #define __has_attribute(x) 0 -#endif -#ifndef __has_cpp_attribute - #define __has_cpp_attribute(x) 0 -#endif -#ifndef CYTHON_RESTRICT - #if defined(__GNUC__) - #define CYTHON_RESTRICT __restrict__ - #elif defined(_MSC_VER) && _MSC_VER >= 1400 - #define CYTHON_RESTRICT __restrict - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_RESTRICT restrict - #else - #define CYTHON_RESTRICT - #endif -#endif -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -#ifndef CYTHON_MAYBE_UNUSED_VAR -# if defined(__cplusplus) - template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } -# else -# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) -# endif -#endif -#ifndef CYTHON_NCP_UNUSED -# if CYTHON_COMPILING_IN_CPYTHON -# define CYTHON_NCP_UNUSED -# else -# define CYTHON_NCP_UNUSED CYTHON_UNUSED -# endif -#endif -#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) -#ifdef _MSC_VER - #ifndef _MSC_STDINT_H_ - #if _MSC_VER < 1300 - typedef unsigned char uint8_t; - typedef unsigned int uint32_t; - #else - typedef unsigned __int8 uint8_t; - typedef unsigned __int32 uint32_t; - #endif - #endif -#else - #include -#endif -#ifndef CYTHON_FALLTHROUGH - #if defined(__cplusplus) && __cplusplus >= 201103L - #if __has_cpp_attribute(fallthrough) - #define CYTHON_FALLTHROUGH [[fallthrough]] - #elif __has_cpp_attribute(clang::fallthrough) - #define CYTHON_FALLTHROUGH [[clang::fallthrough]] - #elif __has_cpp_attribute(gnu::fallthrough) - #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] - #endif - #endif - #ifndef CYTHON_FALLTHROUGH - #if __has_attribute(fallthrough) - #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) - #else - #define CYTHON_FALLTHROUGH - #endif - #endif - #if defined(__clang__ ) && defined(__apple_build_version__) - #if __apple_build_version__ < 7000000 - #undef CYTHON_FALLTHROUGH - #define CYTHON_FALLTHROUGH - #endif - #endif -#endif - -#ifndef __cplusplus - #error "Cython files generated with the C++ option must be compiled with a C++ compiler." -#endif -#ifndef CYTHON_INLINE - #if defined(__clang__) - #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) - #else - #define CYTHON_INLINE inline - #endif -#endif -template -void __Pyx_call_destructor(T& x) { - x.~T(); -} -template -class __Pyx_FakeReference { - public: - __Pyx_FakeReference() : ptr(NULL) { } - __Pyx_FakeReference(const T& ref) : ptr(const_cast(&ref)) { } - T *operator->() { return ptr; } - T *operator&() { return ptr; } - operator T&() { return *ptr; } - template bool operator ==(U other) { return *ptr == other; } - template bool operator !=(U other) { return *ptr != other; } - private: - T *ptr; -}; - -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) - #define Py_OptimizeFlag 0 -#endif -#define __PYX_BUILD_PY_SSIZE_T "n" -#define CYTHON_FORMAT_SSIZE_T "z" -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyClass_Type -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" -#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#else - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif - #define __Pyx_DefaultClassType PyType_Type -#endif -#ifndef Py_TPFLAGS_CHECKTYPES - #define Py_TPFLAGS_CHECKTYPES 0 -#endif -#ifndef Py_TPFLAGS_HAVE_INDEX - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#ifndef Py_TPFLAGS_HAVE_NEWBUFFER - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif -#ifndef Py_TPFLAGS_HAVE_FINALIZE - #define Py_TPFLAGS_HAVE_FINALIZE 0 -#endif -#ifndef METH_STACKLESS - #define METH_STACKLESS 0 -#endif -#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) - #ifndef METH_FASTCALL - #define METH_FASTCALL 0x80 - #endif - typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); - typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames); -#else - #define __Pyx_PyCFunctionFast _PyCFunctionFast - #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords -#endif -#if CYTHON_FAST_PYCCALL -#define __Pyx_PyFastCFunction_Check(func)\ - ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) -#else -#define __Pyx_PyFastCFunction_Check(func) 0 -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) - #define PyObject_Malloc(s) PyMem_Malloc(s) - #define PyObject_Free(p) PyMem_Free(p) - #define PyObject_Realloc(p) PyMem_Realloc(p) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 - #define PyMem_RawMalloc(n) PyMem_Malloc(n) - #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) - #define PyMem_RawFree(p) PyMem_Free(p) -#endif -#if CYTHON_COMPILING_IN_PYSTON - #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) -#else - #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) -#endif -#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#elif PY_VERSION_HEX >= 0x03060000 - #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() -#elif PY_VERSION_HEX >= 0x03000000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#else - #define __Pyx_PyThreadState_Current _PyThreadState_Current -#endif -#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) -#include "pythread.h" -#define Py_tss_NEEDS_INIT 0 -typedef int Py_tss_t; -static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { - *key = PyThread_create_key(); - return 0; -} -static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { - Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); - *key = Py_tss_NEEDS_INIT; - return key; -} -static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { - PyObject_Free(key); -} -static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { - return *key != Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { - PyThread_delete_key(*key); - *key = Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { - return PyThread_set_key_value(*key, value); -} -static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { - return PyThread_get_key_value(*key); -} -#endif -#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) -#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) -#else -#define __Pyx_PyDict_NewPresized(n) PyDict_New() -#endif -#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS -#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) -#else -#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) -#endif -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) - #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) - #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) -#else - #define CYTHON_PEP393_ENABLED 0 - #define PyUnicode_1BYTE_KIND 1 - #define PyUnicode_2BYTE_KIND 2 - #define PyUnicode_4BYTE_KIND 4 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) - #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) - #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) - #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) -#endif -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) -#else - #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ - PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) - #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) - #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) - #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) -#endif -#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) -#else - #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) -#endif -#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) - #define PyObject_ASCII(o) PyObject_Repr(o) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact - #define PyObject_Unicode PyObject_Str -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) -#endif -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif -#if CYTHON_ASSUME_SAFE_MACROS - #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) -#else - #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask - #define PyNumber_Int PyNumber_Long -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif -#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY - #ifndef PyUnicode_InternFromString - #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) - #endif -#endif -#if PY_VERSION_HEX < 0x030200A4 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong - #define __Pyx_PyInt_AsHash_t PyInt_AsLong -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : (Py_INCREF(func), func)) -#else - #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) -#endif -#if CYTHON_USE_ASYNC_SLOTS - #if PY_VERSION_HEX >= 0x030500B1 - #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods - #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) - #else - #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) - #endif -#else - #define __Pyx_PyType_AsAsync(obj) NULL -#endif -#ifndef __Pyx_PyAsyncMethodsStruct - typedef struct { - unaryfunc am_await; - unaryfunc am_aiter; - unaryfunc am_anext; - } __Pyx_PyAsyncMethodsStruct; -#endif - -#if defined(WIN32) || defined(MS_WINDOWS) - #define _USE_MATH_DEFINES -#endif -#include -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif -#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) -#define __Pyx_truncl trunc -#else -#define __Pyx_truncl truncl -#endif - - -#define __PYX_ERR(f_index, lineno, Ln_error) \ -{ \ - __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ -} - -#ifndef __PYX_EXTERN_C - #ifdef __cplusplus - #define __PYX_EXTERN_C extern "C" - #else - #define __PYX_EXTERN_C extern - #endif -#endif - -#define __PYX_HAVE___libjpeg -#define __PYX_HAVE_API___libjpeg -/* Early includes */ -#include -#include "ios" -#include "new" -#include "stdexcept" -#include "typeinfo" -#include -#include -#include "numpy/arrayobject.h" -#include "numpy/ufuncobject.h" -#include "decode.hpp" -#include "cmd/reconstruct.hpp" -#ifdef _OPENMP -#include -#endif /* _OPENMP */ - -#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) -#define CYTHON_WITHOUT_ASSERTIONS -#endif - -typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; - -#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) -#define __PYX_DEFAULT_STRING_ENCODING "" -#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString -#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#define __Pyx_uchar_cast(c) ((unsigned char)c) -#define __Pyx_long_cast(x) ((long)x) -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ - (sizeof(type) < sizeof(Py_ssize_t)) ||\ - (sizeof(type) > sizeof(Py_ssize_t) &&\ - likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX) &&\ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ - v == (type)PY_SSIZE_T_MIN))) ||\ - (sizeof(type) == sizeof(Py_ssize_t) &&\ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX))) ) -static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { - return (size_t) i < (size_t) limit; -} -#if defined (__cplusplus) && __cplusplus >= 201103L - #include - #define __Pyx_sst_abs(value) std::abs(value) -#elif SIZEOF_INT >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) abs(value) -#elif SIZEOF_LONG >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) labs(value) -#elif defined (_MSC_VER) - #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) -#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define __Pyx_sst_abs(value) llabs(value) -#elif defined (__GNUC__) - #define __Pyx_sst_abs(value) __builtin_llabs(value) -#else - #define __Pyx_sst_abs(value) ((value<0) ? -value : value) -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); -#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) -#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif -#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) -#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) -#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) -#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) -#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return (size_t)(u_end - u - 1); -} -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) -#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); -#define __Pyx_PySequence_Tuple(obj)\ - (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -#if CYTHON_ASSUME_SAFE_MACROS -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) -#else -#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) -#endif -#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - const char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - if (strcmp(default_encoding_c, "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (!ascii_chars_u) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - Py_DECREF(ascii_chars_u); - Py_DECREF(ascii_chars_b); - } - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); - if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - - -/* Test for GCC > 2.95 */ -#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) -#else /* !__GNUC__ or GCC < 2.95 */ - #define likely(x) (x) - #define unlikely(x) (x) -#endif /* __GNUC__ */ -static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } - -static PyObject *__pyx_m = NULL; -static PyObject *__pyx_d; -static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime = NULL; -static PyObject *__pyx_empty_tuple; -static PyObject *__pyx_empty_bytes; -static PyObject *__pyx_empty_unicode; -static int __pyx_lineno; -static int __pyx_clineno = 0; -static const char * __pyx_cfilenm= __FILE__; -static const char *__pyx_filename; - -/* Header.proto */ -#if !defined(CYTHON_CCOMPLEX) - #if defined(__cplusplus) - #define CYTHON_CCOMPLEX 1 - #elif defined(_Complex_I) - #define CYTHON_CCOMPLEX 1 - #else - #define CYTHON_CCOMPLEX 0 - #endif -#endif -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - #include - #else - #include - #endif -#endif -#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) - #undef _Complex_I - #define _Complex_I 1.0fj -#endif - - -static const char *__pyx_f[] = { - "pylibjpeg/_libjpeg.pyx", - "__init__.pxd", - "stringsource", - "type.pxd", -}; -/* BufferFormatStructs.proto */ -#define IS_UNSIGNED(type) (((type) -1) > 0) -struct __Pyx_StructField_; -#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) -typedef struct { - const char* name; - struct __Pyx_StructField_* fields; - size_t size; - size_t arraysize[8]; - int ndim; - char typegroup; - char is_unsigned; - int flags; -} __Pyx_TypeInfo; -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - size_t struct_alignment; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; - char is_valid_array; -} __Pyx_BufFmt_Context; - - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":776 - * # in Cython to enable them only on the right systems. - * - * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< - * ctypedef npy_int16 int16_t - * ctypedef npy_int32 int32_t - */ -typedef npy_int8 __pyx_t_5numpy_int8_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":777 - * - * ctypedef npy_int8 int8_t - * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< - * ctypedef npy_int32 int32_t - * ctypedef npy_int64 int64_t - */ -typedef npy_int16 __pyx_t_5numpy_int16_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":778 - * ctypedef npy_int8 int8_t - * ctypedef npy_int16 int16_t - * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< - * ctypedef npy_int64 int64_t - * #ctypedef npy_int96 int96_t - */ -typedef npy_int32 __pyx_t_5numpy_int32_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":779 - * ctypedef npy_int16 int16_t - * ctypedef npy_int32 int32_t - * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< - * #ctypedef npy_int96 int96_t - * #ctypedef npy_int128 int128_t - */ -typedef npy_int64 __pyx_t_5numpy_int64_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":783 - * #ctypedef npy_int128 int128_t - * - * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< - * ctypedef npy_uint16 uint16_t - * ctypedef npy_uint32 uint32_t - */ -typedef npy_uint8 __pyx_t_5numpy_uint8_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":784 - * - * ctypedef npy_uint8 uint8_t - * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< - * ctypedef npy_uint32 uint32_t - * ctypedef npy_uint64 uint64_t - */ -typedef npy_uint16 __pyx_t_5numpy_uint16_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":785 - * ctypedef npy_uint8 uint8_t - * ctypedef npy_uint16 uint16_t - * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< - * ctypedef npy_uint64 uint64_t - * #ctypedef npy_uint96 uint96_t - */ -typedef npy_uint32 __pyx_t_5numpy_uint32_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":786 - * ctypedef npy_uint16 uint16_t - * ctypedef npy_uint32 uint32_t - * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< - * #ctypedef npy_uint96 uint96_t - * #ctypedef npy_uint128 uint128_t - */ -typedef npy_uint64 __pyx_t_5numpy_uint64_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":790 - * #ctypedef npy_uint128 uint128_t - * - * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< - * ctypedef npy_float64 float64_t - * #ctypedef npy_float80 float80_t - */ -typedef npy_float32 __pyx_t_5numpy_float32_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":791 - * - * ctypedef npy_float32 float32_t - * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< - * #ctypedef npy_float80 float80_t - * #ctypedef npy_float128 float128_t - */ -typedef npy_float64 __pyx_t_5numpy_float64_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":800 - * # The int types are mapped a bit surprising -- - * # numpy.int corresponds to 'l' and numpy.long to 'q' - * ctypedef npy_long int_t # <<<<<<<<<<<<<< - * ctypedef npy_longlong long_t - * ctypedef npy_longlong longlong_t - */ -typedef npy_long __pyx_t_5numpy_int_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":801 - * # numpy.int corresponds to 'l' and numpy.long to 'q' - * ctypedef npy_long int_t - * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< - * ctypedef npy_longlong longlong_t - * - */ -typedef npy_longlong __pyx_t_5numpy_long_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":802 - * ctypedef npy_long int_t - * ctypedef npy_longlong long_t - * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< - * - * ctypedef npy_ulong uint_t - */ -typedef npy_longlong __pyx_t_5numpy_longlong_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":804 - * ctypedef npy_longlong longlong_t - * - * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< - * ctypedef npy_ulonglong ulong_t - * ctypedef npy_ulonglong ulonglong_t - */ -typedef npy_ulong __pyx_t_5numpy_uint_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":805 - * - * ctypedef npy_ulong uint_t - * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< - * ctypedef npy_ulonglong ulonglong_t - * - */ -typedef npy_ulonglong __pyx_t_5numpy_ulong_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":806 - * ctypedef npy_ulong uint_t - * ctypedef npy_ulonglong ulong_t - * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< - * - * ctypedef npy_intp intp_t - */ -typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":808 - * ctypedef npy_ulonglong ulonglong_t - * - * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< - * ctypedef npy_uintp uintp_t - * - */ -typedef npy_intp __pyx_t_5numpy_intp_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":809 - * - * ctypedef npy_intp intp_t - * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< - * - * ctypedef npy_double float_t - */ -typedef npy_uintp __pyx_t_5numpy_uintp_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":811 - * ctypedef npy_uintp uintp_t - * - * ctypedef npy_double float_t # <<<<<<<<<<<<<< - * ctypedef npy_double double_t - * ctypedef npy_longdouble longdouble_t - */ -typedef npy_double __pyx_t_5numpy_float_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":812 - * - * ctypedef npy_double float_t - * ctypedef npy_double double_t # <<<<<<<<<<<<<< - * ctypedef npy_longdouble longdouble_t - * - */ -typedef npy_double __pyx_t_5numpy_double_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":813 - * ctypedef npy_double float_t - * ctypedef npy_double double_t - * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< - * - * ctypedef npy_cfloat cfloat_t - */ -typedef npy_longdouble __pyx_t_5numpy_longdouble_t; -/* Declarations.proto */ -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - typedef ::std::complex< float > __pyx_t_float_complex; - #else - typedef float _Complex __pyx_t_float_complex; - #endif -#else - typedef struct { float real, imag; } __pyx_t_float_complex; -#endif -static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); - -/* Declarations.proto */ -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - typedef ::std::complex< double > __pyx_t_double_complex; - #else - typedef double _Complex __pyx_t_double_complex; - #endif -#else - typedef struct { double real, imag; } __pyx_t_double_complex; -#endif -static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); - - -/*--- Type declarations ---*/ - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":815 - * ctypedef npy_longdouble longdouble_t - * - * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< - * ctypedef npy_cdouble cdouble_t - * ctypedef npy_clongdouble clongdouble_t - */ -typedef npy_cfloat __pyx_t_5numpy_cfloat_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":816 - * - * ctypedef npy_cfloat cfloat_t - * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< - * ctypedef npy_clongdouble clongdouble_t - * - */ -typedef npy_cdouble __pyx_t_5numpy_cdouble_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":817 - * ctypedef npy_cfloat cfloat_t - * ctypedef npy_cdouble cdouble_t - * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< - * - * ctypedef npy_cdouble complex_t - */ -typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":819 - * ctypedef npy_clongdouble clongdouble_t - * - * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew1(a): - */ -typedef npy_cdouble __pyx_t_5numpy_complex_t; - -/* --- Runtime support code (head) --- */ -/* Refnanny.proto */ -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - if (acquire_gil) {\ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - PyGILState_Release(__pyx_gilstate_save);\ - } else {\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext()\ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif -#define __Pyx_XDECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_XDECREF(tmp);\ - } while (0) -#define __Pyx_DECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_DECREF(tmp);\ - } while (0) -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -/* RaiseArgTupleInvalid.proto */ -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); - -/* RaiseDoubleKeywords.proto */ -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); - -/* ParseKeywords.proto */ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ - const char* function_name); - -/* ArgTypeTest.proto */ -#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ - ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ - __Pyx__ArgTypeTest(obj, type, name, exact)) -static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); - -/* IsLittleEndian.proto */ -static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); - -/* BufferFormatCheck.proto */ -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type); - -/* BufferGetAndValidate.proto */ -#define __Pyx_GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack)\ - ((obj == Py_None || obj == NULL) ?\ - (__Pyx_ZeroBuffer(buf), 0) :\ - __Pyx__GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack)) -static int __Pyx__GetBufferAndValidate(Py_buffer* buf, PyObject* obj, - __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); -static void __Pyx_ZeroBuffer(Py_buffer* buf); -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); -static Py_ssize_t __Pyx_minusones[] = { -1, -1, -1, -1, -1, -1, -1, -1 }; -static Py_ssize_t __Pyx_zeros[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; - -/* PyObjectGetAttrStr.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) -#endif - -/* GetBuiltinName.proto */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name); - -/* PyDictVersioning.proto */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) -#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ - (version_var) = __PYX_GET_DICT_VERSION(dict);\ - (cache_var) = (value); -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ - (VAR) = __pyx_dict_cached_value;\ - } else {\ - (VAR) = __pyx_dict_cached_value = (LOOKUP);\ - __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ - }\ -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); -#else -#define __PYX_GET_DICT_VERSION(dict) (0) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); -#endif - -/* GetModuleGlobalName.proto */ -#if CYTHON_USE_DICT_VERSIONS -#define __Pyx_GetModuleGlobalName(var, name) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ - (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ - __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -#define __Pyx_GetModuleGlobalNameUncached(var, name) {\ - PY_UINT64_T __pyx_dict_version;\ - PyObject *__pyx_dict_cached_value;\ - (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); -#else -#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) -#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); -#endif - -/* PyCFunctionFastCall.proto */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); -#else -#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) -#endif - -/* PyFunctionFastCall.proto */ -#if CYTHON_FAST_PYCALL -#define __Pyx_PyFunction_FastCall(func, args, nargs)\ - __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); -#else -#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) -#endif -#define __Pyx_BUILD_ASSERT_EXPR(cond)\ - (sizeof(char [1 - 2*!(cond)]) - 1) -#ifndef Py_MEMBER_SIZE -#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) -#endif - static size_t __pyx_pyframe_localsplus_offset = 0; - #include "frameobject.h" - #define __Pxy_PyFrame_Initialize_Offsets()\ - ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ - (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) - #define __Pyx_PyFrame_GetLocalsplus(frame)\ - (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) -#endif - -/* PyObjectCall.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); -#else -#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) -#endif - -/* PyObjectCall2Args.proto */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); - -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -/* RaiseTooManyValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -/* RaiseNeedMoreValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -/* IterFinish.proto */ -static CYTHON_INLINE int __Pyx_IterFinish(void); - -/* UnpackItemEndCheck.proto */ -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); - -/* PyIntBinop.proto */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_TrueDivideObjC(PyObject *op1, PyObject *op2, long intval, int inplace, int zerodivision_check); -#else -#define __Pyx_PyInt_TrueDivideObjC(op1, op2, intval, inplace, zerodivision_check)\ - (inplace ? PyNumber_InPlaceTrueDivide(op1, op2) : PyNumber_TrueDivide(op1, op2)) -#endif - -/* DictGetItem.proto */ -#if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY -static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key); -#define __Pyx_PyObject_Dict_GetItem(obj, name)\ - (likely(PyDict_CheckExact(obj)) ?\ - __Pyx_PyDict_GetItem(obj, name) : PyObject_GetItem(obj, name)) -#else -#define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) -#define __Pyx_PyObject_Dict_GetItem(obj, name) PyObject_GetItem(obj, name) -#endif - -/* ExtTypeTest.proto */ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); - -/* GetItemInt.proto */ -#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ - __Pyx_GetItemInt_Generic(o, to_py_func(i)))) -#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck); - -/* PyThreadStateGet.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; -#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; -#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type -#else -#define __Pyx_PyThreadState_declare -#define __Pyx_PyThreadState_assign -#define __Pyx_PyErr_Occurred() PyErr_Occurred() -#endif - -/* PyErrFetchRestore.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) -#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) -#else -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#endif -#else -#define __Pyx_PyErr_Clear() PyErr_Clear() -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) -#endif - -/* RaiseException.proto */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -/* RaiseNoneIterError.proto */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); - -/* GetTopmostException.proto */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); -#endif - -/* SaveResetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -#else -#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) -#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) -#endif - -/* PyErrExceptionMatches.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) -static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); -#else -#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) -#endif - -/* GetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* TypeImport.proto */ -#ifndef __PYX_HAVE_RT_ImportType_proto -#define __PYX_HAVE_RT_ImportType_proto -enum __Pyx_ImportType_CheckSize { - __Pyx_ImportType_CheckSize_Error = 0, - __Pyx_ImportType_CheckSize_Warn = 1, - __Pyx_ImportType_CheckSize_Ignore = 2 -}; -static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size); -#endif - -/* Import.proto */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -/* ImportFrom.proto */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); - -/* CLineInTraceback.proto */ -#ifdef CYTHON_CLINE_IN_TRACEBACK -#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) -#else -static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); -#endif - -/* CodeObjectCache.proto */ -typedef struct { - PyCodeObject* code_object; - int code_line; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -/* AddTraceback.proto */ -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); - -/* BufferStructDeclare.proto */ -typedef struct { - Py_ssize_t shape, strides, suboffsets; -} __Pyx_Buf_DimInfo; -typedef struct { - size_t refcount; - Py_buffer pybuffer; -} __Pyx_Buffer; -typedef struct { - __Pyx_Buffer *rcbuffer; - char *data; - __Pyx_Buf_DimInfo diminfo[8]; -} __Pyx_LocalBuf_ND; - -#if PY_MAJOR_VERSION < 3 - static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); - static void __Pyx_ReleaseBuffer(Py_buffer *view); -#else - #define __Pyx_GetBuffer PyObject_GetBuffer - #define __Pyx_ReleaseBuffer PyBuffer_Release -#endif - - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_char(char value); - -/* RealImag.proto */ -#if CYTHON_CCOMPLEX - #ifdef __cplusplus - #define __Pyx_CREAL(z) ((z).real()) - #define __Pyx_CIMAG(z) ((z).imag()) - #else - #define __Pyx_CREAL(z) (__real__(z)) - #define __Pyx_CIMAG(z) (__imag__(z)) - #endif -#else - #define __Pyx_CREAL(z) ((z).real) - #define __Pyx_CIMAG(z) ((z).imag) -#endif -#if defined(__cplusplus) && CYTHON_CCOMPLEX\ - && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) - #define __Pyx_SET_CREAL(z,x) ((z).real(x)) - #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) -#else - #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) - #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) -#endif - -/* Arithmetic.proto */ -#if CYTHON_CCOMPLEX - #define __Pyx_c_eq_float(a, b) ((a)==(b)) - #define __Pyx_c_sum_float(a, b) ((a)+(b)) - #define __Pyx_c_diff_float(a, b) ((a)-(b)) - #define __Pyx_c_prod_float(a, b) ((a)*(b)) - #define __Pyx_c_quot_float(a, b) ((a)/(b)) - #define __Pyx_c_neg_float(a) (-(a)) - #ifdef __cplusplus - #define __Pyx_c_is_zero_float(z) ((z)==(float)0) - #define __Pyx_c_conj_float(z) (::std::conj(z)) - #if 1 - #define __Pyx_c_abs_float(z) (::std::abs(z)) - #define __Pyx_c_pow_float(a, b) (::std::pow(a, b)) - #endif - #else - #define __Pyx_c_is_zero_float(z) ((z)==0) - #define __Pyx_c_conj_float(z) (conjf(z)) - #if 1 - #define __Pyx_c_abs_float(z) (cabsf(z)) - #define __Pyx_c_pow_float(a, b) (cpowf(a, b)) - #endif - #endif -#else - static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex); - static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex); - #if 1 - static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex); - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex); - #endif -#endif - -/* Arithmetic.proto */ -#if CYTHON_CCOMPLEX - #define __Pyx_c_eq_double(a, b) ((a)==(b)) - #define __Pyx_c_sum_double(a, b) ((a)+(b)) - #define __Pyx_c_diff_double(a, b) ((a)-(b)) - #define __Pyx_c_prod_double(a, b) ((a)*(b)) - #define __Pyx_c_quot_double(a, b) ((a)/(b)) - #define __Pyx_c_neg_double(a) (-(a)) - #ifdef __cplusplus - #define __Pyx_c_is_zero_double(z) ((z)==(double)0) - #define __Pyx_c_conj_double(z) (::std::conj(z)) - #if 1 - #define __Pyx_c_abs_double(z) (::std::abs(z)) - #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) - #endif - #else - #define __Pyx_c_is_zero_double(z) ((z)==0) - #define __Pyx_c_conj_double(z) (conj(z)) - #if 1 - #define __Pyx_c_abs_double(z) (cabs(z)) - #define __Pyx_c_pow_double(a, b) (cpow(a, b)) - #endif - #endif -#else - static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); - static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); - #if 1 - static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); - #endif -#endif - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value); - -/* CIntFromPy.proto */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); - -/* FastTypeChecks.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); -#else -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) -#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) -#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) -#endif -#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) - -/* CheckBinaryVersion.proto */ -static int __Pyx_check_binary_version(void); - -/* InitStrings.proto */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); - - -/* Module declarations from 'libcpp' */ - -/* Module declarations from 'libc.string' */ - -/* Module declarations from 'libcpp.string' */ - -/* Module declarations from 'cpython.buffer' */ - -/* Module declarations from 'libc.stdio' */ - -/* Module declarations from '__builtin__' */ - -/* Module declarations from 'cpython.type' */ -static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; - -/* Module declarations from 'cpython' */ - -/* Module declarations from 'cpython.object' */ - -/* Module declarations from 'cpython.ref' */ - -/* Module declarations from 'cpython.mem' */ - -/* Module declarations from 'numpy' */ - -/* Module declarations from 'numpy' */ -static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; -static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; -static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; -static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; -static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; -static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ - -/* Module declarations from '_libjpeg' */ -static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &); /*proto*/ -static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t = { "uint8_t", NULL, sizeof(__pyx_t_5numpy_uint8_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_uint8_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_uint8_t), 0 }; -#define __Pyx_MODULE_NAME "_libjpeg" -extern int __pyx_module_is_main__libjpeg; -int __pyx_module_is_main__libjpeg = 0; - -/* Implementation of '_libjpeg' */ -static PyObject *__pyx_builtin_ValueError; -static PyObject *__pyx_builtin_range; -static PyObject *__pyx_builtin_RuntimeError; -static PyObject *__pyx_builtin_ImportError; -static const char __pyx_k_np[] = "np"; -static const char __pyx_k_bpp[] = "bpp"; -static const char __pyx_k_fin[] = "fin"; -static const char __pyx_k_ceil[] = "ceil"; -static const char __pyx_k_fout[] = "fout"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_math[] = "math"; -static const char __pyx_k_name[] = "__name__"; -static const char __pyx_k_rows[] = "rows"; -static const char __pyx_k_test[] = "__test__"; -static const char __pyx_k_dtype[] = "dtype"; -static const char __pyx_k_numpy[] = "numpy"; -static const char __pyx_k_param[] = "param"; -static const char __pyx_k_range[] = "range"; -static const char __pyx_k_shape[] = "shape"; -static const char __pyx_k_uint8[] = "uint8"; -static const char __pyx_k_zeros[] = "zeros"; -static const char __pyx_k_decode[] = "decode"; -static const char __pyx_k_falpha[] = "falpha"; -static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_pInput[] = "pInput"; -static const char __pyx_k_pParam[] = "pParam"; -static const char __pyx_k_status[] = "status"; -static const char __pyx_k_columns[] = "columns"; -static const char __pyx_k_libjpeg[] = "_libjpeg"; -static const char __pyx_k_pOutput[] = "pOutput"; -static const char __pyx_k_nr_bytes[] = "nr_bytes"; -static const char __pyx_k_upsample[] = "upsample"; -static const char __pyx_k_ValueError[] = "ValueError"; -static const char __pyx_k_parameters[] = "parameters"; -static const char __pyx_k_ImportError[] = "ImportError"; -static const char __pyx_k_colourspace[] = "colourspace"; -static const char __pyx_k_reconstruct[] = "reconstruct"; -static const char __pyx_k_RuntimeError[] = "RuntimeError"; -static const char __pyx_k_input_buffer[] = "input_buffer"; -static const char __pyx_k_output_buffer[] = "output_buffer"; -static const char __pyx_k_get_parameters[] = "get_parameters"; -static const char __pyx_k_bits_per_sample[] = "bits_per_sample"; -static const char __pyx_k_samples_per_pixel[] = "samples_per_pixel"; -static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; -static const char __pyx_k_pylibjpeg__libjpeg_pyx[] = "pylibjpeg/_libjpeg.pyx"; -static const char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; -static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import"; -static const char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; -static const char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; -static const char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; -static const char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; -static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import"; -static const char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; -static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; -static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; -static PyObject *__pyx_n_s_ImportError; -static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; -static PyObject *__pyx_n_s_RuntimeError; -static PyObject *__pyx_n_s_ValueError; -static PyObject *__pyx_n_u_bits_per_sample; -static PyObject *__pyx_n_s_bpp; -static PyObject *__pyx_n_s_ceil; -static PyObject *__pyx_n_s_cline_in_traceback; -static PyObject *__pyx_n_s_colourspace; -static PyObject *__pyx_n_u_columns; -static PyObject *__pyx_n_s_decode; -static PyObject *__pyx_n_s_dtype; -static PyObject *__pyx_n_s_falpha; -static PyObject *__pyx_n_s_fin; -static PyObject *__pyx_n_s_fout; -static PyObject *__pyx_n_s_get_parameters; -static PyObject *__pyx_n_s_import; -static PyObject *__pyx_n_s_input_buffer; -static PyObject *__pyx_n_s_libjpeg; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_s_math; -static PyObject *__pyx_n_s_name; -static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; -static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; -static PyObject *__pyx_n_s_np; -static PyObject *__pyx_n_s_nr_bytes; -static PyObject *__pyx_n_s_numpy; -static PyObject *__pyx_kp_u_numpy_core_multiarray_failed_to; -static PyObject *__pyx_kp_u_numpy_core_umath_failed_to_impor; -static PyObject *__pyx_n_s_output_buffer; -static PyObject *__pyx_n_s_pInput; -static PyObject *__pyx_n_s_pOutput; -static PyObject *__pyx_n_s_pParam; -static PyObject *__pyx_n_s_param; -static PyObject *__pyx_n_s_parameters; -static PyObject *__pyx_kp_s_pylibjpeg__libjpeg_pyx; -static PyObject *__pyx_n_s_range; -static PyObject *__pyx_n_s_reconstruct; -static PyObject *__pyx_n_u_rows; -static PyObject *__pyx_n_u_samples_per_pixel; -static PyObject *__pyx_n_s_shape; -static PyObject *__pyx_n_s_status; -static PyObject *__pyx_n_s_test; -static PyObject *__pyx_n_s_uint8; -static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; -static PyObject *__pyx_n_s_upsample; -static PyObject *__pyx_n_s_zeros; -static PyObject *__pyx_pf_8_libjpeg_decode(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_input_buffer, PyObject *__pyx_v_colourspace); /* proto */ -static PyObject *__pyx_pf_8_libjpeg_2get_parameters(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_input_buffer); /* proto */ -static PyObject *__pyx_pf_8_libjpeg_4reconstruct(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_fin, PyObject *__pyx_v_fout, PyObject *__pyx_v_colourspace, PyObject *__pyx_v_falpha, PyObject *__pyx_v_upsample); /* proto */ -static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ -static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ -static PyObject *__pyx_int_8; -static PyObject *__pyx_tuple_; -static PyObject *__pyx_tuple__2; -static PyObject *__pyx_tuple__3; -static PyObject *__pyx_tuple__4; -static PyObject *__pyx_tuple__5; -static PyObject *__pyx_tuple__6; -static PyObject *__pyx_tuple__7; -static PyObject *__pyx_tuple__8; -static PyObject *__pyx_tuple__10; -static PyObject *__pyx_tuple__12; -static PyObject *__pyx_codeobj__9; -static PyObject *__pyx_codeobj__11; -static PyObject *__pyx_codeobj__13; -/* Late includes */ - -/* "_libjpeg.pyx":36 - * - * - * def decode(np.ndarray[np.uint8_t, ndim=1] input_buffer, colourspace): # <<<<<<<<<<<<<< - * """Return the decoded JPEG data from `input_buffer`. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_8_libjpeg_1decode(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_8_libjpeg_decode[] = "Return the decoded JPEG data from `input_buffer`.\n\n Parameters\n ----------\n input_buffer : numpy.ndarray\n A 1D array of ``np.uint8`` containing the raw encoded JPEG image.\n colourspace : int\n | ``0`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_NONE``\n | ``1`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_YCBCR``\n | ``2`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_LSRCT``\n | ``2`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_RCT``\n | ``3`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_FREEFORM``\n\n Returns\n -------\n bytes\n The status and any error message of the decoding operation.\n numpy.ndarray or None\n A 1D array of ``np.uint8`` containing the decoded image data. Returns\n ``None`` if the decode fails.\n dict\n A :class:`dict` containing the image parameters.\n "; -static PyMethodDef __pyx_mdef_8_libjpeg_1decode = {"decode", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_8_libjpeg_1decode, METH_VARARGS|METH_KEYWORDS, __pyx_doc_8_libjpeg_decode}; -static PyObject *__pyx_pw_8_libjpeg_1decode(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyArrayObject *__pyx_v_input_buffer = 0; - PyObject *__pyx_v_colourspace = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("decode (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_input_buffer,&__pyx_n_s_colourspace,0}; - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_input_buffer)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_colourspace)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("decode", 1, 2, 2, 1); __PYX_ERR(0, 36, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "decode") < 0)) __PYX_ERR(0, 36, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_input_buffer = ((PyArrayObject *)values[0]); - __pyx_v_colourspace = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("decode", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 36, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("_libjpeg.decode", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_input_buffer), __pyx_ptype_5numpy_ndarray, 1, "input_buffer", 0))) __PYX_ERR(0, 36, __pyx_L1_error) - __pyx_r = __pyx_pf_8_libjpeg_decode(__pyx_self, __pyx_v_input_buffer, __pyx_v_colourspace); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_8_libjpeg_decode(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_input_buffer, PyObject *__pyx_v_colourspace) { - PyObject *__pyx_v_status = NULL; - PyObject *__pyx_v_param = NULL; - char *__pyx_v_pInput; - PyObject *__pyx_v_bpp = NULL; - PyObject *__pyx_v_nr_bytes = NULL; - PyObject *__pyx_v_output_buffer = NULL; - char *__pyx_v_pOutput; - __Pyx_LocalBuf_ND __pyx_pybuffernd_input_buffer; - __Pyx_Buffer __pyx_pybuffer_input_buffer; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *(*__pyx_t_5)(PyObject *); - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - int __pyx_t_8; - __Pyx_RefNannySetupContext("decode", 0); - __pyx_pybuffer_input_buffer.pybuffer.buf = NULL; - __pyx_pybuffer_input_buffer.refcount = 0; - __pyx_pybuffernd_input_buffer.data = NULL; - __pyx_pybuffernd_input_buffer.rcbuffer = &__pyx_pybuffer_input_buffer; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_input_buffer.rcbuffer->pybuffer, (PyObject*)__pyx_v_input_buffer, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) __PYX_ERR(0, 36, __pyx_L1_error) - } - __pyx_pybuffernd_input_buffer.diminfo[0].strides = __pyx_pybuffernd_input_buffer.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_input_buffer.diminfo[0].shape = __pyx_pybuffernd_input_buffer.rcbuffer->pybuffer.shape[0]; - - /* "_libjpeg.pyx":61 - * """ - * # Get the image parameters - * status, param = get_parameters(input_buffer) # <<<<<<<<<<<<<< - * - * # Pointer to first element in input array - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_get_parameters); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_3, ((PyObject *)__pyx_v_input_buffer)) : __Pyx_PyObject_CallOneArg(__pyx_t_2, ((PyObject *)__pyx_v_input_buffer)); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 61, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_2 = PyList_GET_ITEM(sequence, 0); - __pyx_t_3 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_4 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_5 = Py_TYPE(__pyx_t_4)->tp_iternext; - index = 0; __pyx_t_2 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_2)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_2); - index = 1; __pyx_t_3 = __pyx_t_5(__pyx_t_4); if (unlikely(!__pyx_t_3)) goto __pyx_L3_unpacking_failed; - __Pyx_GOTREF(__pyx_t_3); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_5(__pyx_t_4), 2) < 0) __PYX_ERR(0, 61, __pyx_L1_error) - __pyx_t_5 = NULL; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - goto __pyx_L4_unpacking_done; - __pyx_L3_unpacking_failed:; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 61, __pyx_L1_error) - __pyx_L4_unpacking_done:; - } - __pyx_v_status = __pyx_t_2; - __pyx_t_2 = 0; - __pyx_v_param = __pyx_t_3; - __pyx_t_3 = 0; - - /* "_libjpeg.pyx":64 - * - * # Pointer to first element in input array - * cdef char *pInput = np.PyArray_DATA(input_buffer) # <<<<<<<<<<<<<< - * - * # Create array for output and get pointer to first element - */ - __pyx_v_pInput = ((char *)PyArray_DATA(((PyArrayObject *)__pyx_v_input_buffer))); - - /* "_libjpeg.pyx":67 - * - * # Create array for output and get pointer to first element - * bpp = ceil(param['bits_per_sample'] / 8) # <<<<<<<<<<<<<< - * nr_bytes = ( - * param['rows'] * param['columns'] * param['samples_per_pixel'] * bpp - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_ceil); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 67, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = __Pyx_PyObject_Dict_GetItem(__pyx_v_param, __pyx_n_u_bits_per_sample); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 67, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyInt_TrueDivideObjC(__pyx_t_2, __pyx_int_8, 8, 0, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 67, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_2)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_2); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_1 = (__pyx_t_2) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_2, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 67, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_bpp = __pyx_t_1; - __pyx_t_1 = 0; - - /* "_libjpeg.pyx":69 - * bpp = ceil(param['bits_per_sample'] / 8) - * nr_bytes = ( - * param['rows'] * param['columns'] * param['samples_per_pixel'] * bpp # <<<<<<<<<<<<<< - * ) - * output_buffer = np.zeros(nr_bytes, dtype=np.uint8) - */ - __pyx_t_1 = __Pyx_PyObject_Dict_GetItem(__pyx_v_param, __pyx_n_u_rows); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_Dict_GetItem(__pyx_v_param, __pyx_n_u_columns); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyNumber_Multiply(__pyx_t_1, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Dict_GetItem(__pyx_v_param, __pyx_n_u_samples_per_pixel); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = PyNumber_Multiply(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_v_bpp); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_nr_bytes = __pyx_t_3; - __pyx_t_3 = 0; - - /* "_libjpeg.pyx":71 - * param['rows'] * param['columns'] * param['samples_per_pixel'] * bpp - * ) - * output_buffer = np.zeros(nr_bytes, dtype=np.uint8) # <<<<<<<<<<<<<< - * cdef char *pOutput = np.PyArray_DATA(output_buffer) - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_nr_bytes); - __Pyx_GIVEREF(__pyx_v_nr_bytes); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_nr_bytes); - __pyx_t_4 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_uint8); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_dtype, __pyx_t_6) < 0) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_output_buffer = __pyx_t_6; - __pyx_t_6 = 0; - - /* "_libjpeg.pyx":72 - * ) - * output_buffer = np.zeros(nr_bytes, dtype=np.uint8) - * cdef char *pOutput = np.PyArray_DATA(output_buffer) # <<<<<<<<<<<<<< - * - * # Decode the data - output is written to output_buffer - */ - if (!(likely(((__pyx_v_output_buffer) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_output_buffer, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 72, __pyx_L1_error) - __pyx_v_pOutput = ((char *)PyArray_DATA(((PyArrayObject *)__pyx_v_output_buffer))); - - /* "_libjpeg.pyx":79 - * pOutput, - * input_buffer.shape[0], - * output_buffer.shape[0], # <<<<<<<<<<<<<< - * colourspace - * ) - */ - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_output_buffer, __pyx_n_s_shape); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 79, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_6, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 79, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_7 = __Pyx_PyInt_As_int(__pyx_t_4); if (unlikely((__pyx_t_7 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 79, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - - /* "_libjpeg.pyx":80 - * input_buffer.shape[0], - * output_buffer.shape[0], - * colourspace # <<<<<<<<<<<<<< - * ) - * - */ - __pyx_t_8 = __Pyx_PyInt_As_int(__pyx_v_colourspace); if (unlikely((__pyx_t_8 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 80, __pyx_L1_error) - - /* "_libjpeg.pyx":75 - * - * # Decode the data - output is written to output_buffer - * status = Decode( # <<<<<<<<<<<<<< - * pInput, - * pOutput, - */ - __pyx_t_4 = __pyx_convert_PyBytes_string_to_py_std__in_string(Decode(__pyx_v_pInput, __pyx_v_pOutput, (__pyx_v_input_buffer->dimensions[0]), __pyx_t_7, __pyx_t_8)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 75, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF_SET(__pyx_v_status, __pyx_t_4); - __pyx_t_4 = 0; - - /* "_libjpeg.pyx":83 - * ) - * - * return status, output_buffer, param # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 83, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_INCREF(__pyx_v_status); - __Pyx_GIVEREF(__pyx_v_status); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_v_status); - __Pyx_INCREF(__pyx_v_output_buffer); - __Pyx_GIVEREF(__pyx_v_output_buffer); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_v_output_buffer); - __Pyx_INCREF(__pyx_v_param); - __Pyx_GIVEREF(__pyx_v_param); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_v_param); - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "_libjpeg.pyx":36 - * - * - * def decode(np.ndarray[np.uint8_t, ndim=1] input_buffer, colourspace): # <<<<<<<<<<<<<< - * """Return the decoded JPEG data from `input_buffer`. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_6); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_input_buffer.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("_libjpeg.decode", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_input_buffer.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XDECREF(__pyx_v_status); - __Pyx_XDECREF(__pyx_v_param); - __Pyx_XDECREF(__pyx_v_bpp); - __Pyx_XDECREF(__pyx_v_nr_bytes); - __Pyx_XDECREF(__pyx_v_output_buffer); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "_libjpeg.pyx":86 - * - * - * def get_parameters(np.ndarray[np.uint8_t, ndim=1] input_buffer): # <<<<<<<<<<<<<< - * """Return a :class:`dict` containing the JPEG image parameters. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_8_libjpeg_3get_parameters(PyObject *__pyx_self, PyObject *__pyx_v_input_buffer); /*proto*/ -static char __pyx_doc_8_libjpeg_2get_parameters[] = "Return a :class:`dict` containing the JPEG image parameters.\n\n Parameters\n ----------\n input_buffer : numpy.ndarray\n A 1D array of ``np.uint8`` containing the encoded JPEG image.\n\n Returns\n -------\n dict\n A :class:`dict` containing the JPEG image parameters.\n "; -static PyMethodDef __pyx_mdef_8_libjpeg_3get_parameters = {"get_parameters", (PyCFunction)__pyx_pw_8_libjpeg_3get_parameters, METH_O, __pyx_doc_8_libjpeg_2get_parameters}; -static PyObject *__pyx_pw_8_libjpeg_3get_parameters(PyObject *__pyx_self, PyObject *__pyx_v_input_buffer) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("get_parameters (wrapper)", 0); - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_input_buffer), __pyx_ptype_5numpy_ndarray, 1, "input_buffer", 0))) __PYX_ERR(0, 86, __pyx_L1_error) - __pyx_r = __pyx_pf_8_libjpeg_2get_parameters(__pyx_self, ((PyArrayObject *)__pyx_v_input_buffer)); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_8_libjpeg_2get_parameters(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_input_buffer) { - struct JPEGParameters __pyx_v_param; - struct JPEGParameters *__pyx_v_pParam; - char *__pyx_v_pInput; - std::string __pyx_v_status; - PyObject *__pyx_v_parameters = NULL; - __Pyx_LocalBuf_ND __pyx_pybuffernd_input_buffer; - __Pyx_Buffer __pyx_pybuffer_input_buffer; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - __Pyx_RefNannySetupContext("get_parameters", 0); - __pyx_pybuffer_input_buffer.pybuffer.buf = NULL; - __pyx_pybuffer_input_buffer.refcount = 0; - __pyx_pybuffernd_input_buffer.data = NULL; - __pyx_pybuffernd_input_buffer.rcbuffer = &__pyx_pybuffer_input_buffer; - { - __Pyx_BufFmt_StackElem __pyx_stack[1]; - if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_input_buffer.rcbuffer->pybuffer, (PyObject*)__pyx_v_input_buffer, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) __PYX_ERR(0, 86, __pyx_L1_error) - } - __pyx_pybuffernd_input_buffer.diminfo[0].strides = __pyx_pybuffernd_input_buffer.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_input_buffer.diminfo[0].shape = __pyx_pybuffernd_input_buffer.rcbuffer->pybuffer.shape[0]; - - /* "_libjpeg.pyx":100 - * """ - * cdef JPEGParameters param - * param.columns = 0 # <<<<<<<<<<<<<< - * param.rows = 0 - * param.samples_per_pixel = 0 - */ - __pyx_v_param.columns = 0; - - /* "_libjpeg.pyx":101 - * cdef JPEGParameters param - * param.columns = 0 - * param.rows = 0 # <<<<<<<<<<<<<< - * param.samples_per_pixel = 0 - * param.bits_per_sample = 0 - */ - __pyx_v_param.rows = 0; - - /* "_libjpeg.pyx":102 - * param.columns = 0 - * param.rows = 0 - * param.samples_per_pixel = 0 # <<<<<<<<<<<<<< - * param.bits_per_sample = 0 - * - */ - __pyx_v_param.samples_per_pixel = 0; - - /* "_libjpeg.pyx":103 - * param.rows = 0 - * param.samples_per_pixel = 0 - * param.bits_per_sample = 0 # <<<<<<<<<<<<<< - * - * # Pointer to the JPEGParameters object - */ - __pyx_v_param.bits_per_sample = 0; - - /* "_libjpeg.pyx":106 - * - * # Pointer to the JPEGParameters object - * cdef JPEGParameters *pParam = ¶m # <<<<<<<<<<<<<< - * - * # Pointer to first element in input array - */ - __pyx_v_pParam = (&__pyx_v_param); - - /* "_libjpeg.pyx":109 - * - * # Pointer to first element in input array - * cdef char *pInput = np.PyArray_DATA(input_buffer) # <<<<<<<<<<<<<< - * - * # Decode the data - output is written to output_buffer - */ - __pyx_v_pInput = ((char *)PyArray_DATA(((PyArrayObject *)__pyx_v_input_buffer))); - - /* "_libjpeg.pyx":112 - * - * # Decode the data - output is written to output_buffer - * status = GetJPEGParameters( # <<<<<<<<<<<<<< - * pInput, - * input_buffer.shape[0], - */ - __pyx_v_status = GetJPEGParameters(__pyx_v_pInput, (__pyx_v_input_buffer->dimensions[0]), __pyx_v_pParam); - - /* "_libjpeg.pyx":119 - * - * parameters = { - * 'rows' : param.rows, # <<<<<<<<<<<<<< - * 'columns' : param.columns, - * 'samples_per_pixel' : param.samples_per_pixel, - */ - __pyx_t_1 = __Pyx_PyDict_NewPresized(4); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 119, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v_param.rows); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 119, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_u_rows, __pyx_t_2) < 0) __PYX_ERR(0, 119, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "_libjpeg.pyx":120 - * parameters = { - * 'rows' : param.rows, - * 'columns' : param.columns, # <<<<<<<<<<<<<< - * 'samples_per_pixel' : param.samples_per_pixel, - * 'bits_per_sample' : param.bits_per_sample, - */ - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v_param.columns); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 120, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_u_columns, __pyx_t_2) < 0) __PYX_ERR(0, 119, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "_libjpeg.pyx":121 - * 'rows' : param.rows, - * 'columns' : param.columns, - * 'samples_per_pixel' : param.samples_per_pixel, # <<<<<<<<<<<<<< - * 'bits_per_sample' : param.bits_per_sample, - * } - */ - __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_param.samples_per_pixel); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 121, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_u_samples_per_pixel, __pyx_t_2) < 0) __PYX_ERR(0, 119, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "_libjpeg.pyx":122 - * 'columns' : param.columns, - * 'samples_per_pixel' : param.samples_per_pixel, - * 'bits_per_sample' : param.bits_per_sample, # <<<<<<<<<<<<<< - * } - * - */ - __pyx_t_2 = __Pyx_PyInt_From_char(__pyx_v_param.bits_per_sample); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 122, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_u_bits_per_sample, __pyx_t_2) < 0) __PYX_ERR(0, 119, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_parameters = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "_libjpeg.pyx":125 - * } - * - * return status, parameters # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_convert_PyBytes_string_to_py_std__in_string(__pyx_v_status); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 125, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 125, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); - __Pyx_INCREF(__pyx_v_parameters); - __Pyx_GIVEREF(__pyx_v_parameters); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_parameters); - __pyx_t_1 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L0; - - /* "_libjpeg.pyx":86 - * - * - * def get_parameters(np.ndarray[np.uint8_t, ndim=1] input_buffer): # <<<<<<<<<<<<<< - * """Return a :class:`dict` containing the JPEG image parameters. - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_input_buffer.rcbuffer->pybuffer); - __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} - __Pyx_AddTraceback("_libjpeg.get_parameters", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - goto __pyx_L2; - __pyx_L0:; - __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_input_buffer.rcbuffer->pybuffer); - __pyx_L2:; - __Pyx_XDECREF(__pyx_v_parameters); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "_libjpeg.pyx":138 - * - * - * def reconstruct(fin, fout, colourspace, falpha, upsample): # <<<<<<<<<<<<<< - * """Decode the JPEG file in `fin` and write it to `fout` as PNM. - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_8_libjpeg_5reconstruct(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_8_libjpeg_4reconstruct[] = "Decode the JPEG file in `fin` and write it to `fout` as PNM.\n\n Parameters\n ----------\n fin : bytes\n The path to the JPEG file to be decoded.\n fout : bytes\n The path to the decoded PNM file.\n colourspace : int\n The colourspace transform to apply.\n falpha : bytes or None\n The path where any decoded alpha channel data will be written,\n otherwise ``None`` to not write alpha channel data. Equivalent to the\n ``-al file`` flag.\n upsample : bool\n ``True`` to disable automatic upsampling, equivalent to the ``-U``\n flag.\n "; -static PyMethodDef __pyx_mdef_8_libjpeg_5reconstruct = {"reconstruct", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_8_libjpeg_5reconstruct, METH_VARARGS|METH_KEYWORDS, __pyx_doc_8_libjpeg_4reconstruct}; -static PyObject *__pyx_pw_8_libjpeg_5reconstruct(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_fin = 0; - PyObject *__pyx_v_fout = 0; - PyObject *__pyx_v_colourspace = 0; - PyObject *__pyx_v_falpha = 0; - PyObject *__pyx_v_upsample = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("reconstruct (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_fin,&__pyx_n_s_fout,&__pyx_n_s_colourspace,&__pyx_n_s_falpha,&__pyx_n_s_upsample,0}; - PyObject* values[5] = {0,0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_fin)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_fout)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("reconstruct", 1, 5, 5, 1); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_colourspace)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("reconstruct", 1, 5, 5, 2); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_falpha)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("reconstruct", 1, 5, 5, 3); __PYX_ERR(0, 138, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_upsample)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("reconstruct", 1, 5, 5, 4); __PYX_ERR(0, 138, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "reconstruct") < 0)) __PYX_ERR(0, 138, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - } - __pyx_v_fin = values[0]; - __pyx_v_fout = values[1]; - __pyx_v_colourspace = values[2]; - __pyx_v_falpha = values[3]; - __pyx_v_upsample = values[4]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("reconstruct", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 138, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("_libjpeg.reconstruct", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_8_libjpeg_4reconstruct(__pyx_self, __pyx_v_fin, __pyx_v_fout, __pyx_v_colourspace, __pyx_v_falpha, __pyx_v_upsample); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_8_libjpeg_4reconstruct(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_fin, PyObject *__pyx_v_fout, PyObject *__pyx_v_colourspace, PyObject *__pyx_v_falpha, PyObject *__pyx_v_upsample) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - char const *__pyx_t_3; - char const *__pyx_t_4; - int __pyx_t_5; - bool __pyx_t_6; - char const *__pyx_t_7; - __Pyx_RefNannySetupContext("reconstruct", 0); - - /* "_libjpeg.pyx":157 - * flag. - * """ - * if falpha is None: # <<<<<<<<<<<<<< - * Reconstruct(fin, fout, colourspace, NULL, upsample) - * else: - */ - __pyx_t_1 = (__pyx_v_falpha == Py_None); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "_libjpeg.pyx":158 - * """ - * if falpha is None: - * Reconstruct(fin, fout, colourspace, NULL, upsample) # <<<<<<<<<<<<<< - * else: - * Reconstruct(fin, fout, colourspace, falpha, upsample) - */ - __pyx_t_3 = __Pyx_PyObject_AsString(__pyx_v_fin); if (unlikely((!__pyx_t_3) && PyErr_Occurred())) __PYX_ERR(0, 158, __pyx_L1_error) - __pyx_t_4 = __Pyx_PyObject_AsString(__pyx_v_fout); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) __PYX_ERR(0, 158, __pyx_L1_error) - __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_v_colourspace); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 158, __pyx_L1_error) - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_upsample); if (unlikely((__pyx_t_6 == ((bool)-1)) && PyErr_Occurred())) __PYX_ERR(0, 158, __pyx_L1_error) - Reconstruct(__pyx_t_3, __pyx_t_4, __pyx_t_5, NULL, __pyx_t_6); - - /* "_libjpeg.pyx":157 - * flag. - * """ - * if falpha is None: # <<<<<<<<<<<<<< - * Reconstruct(fin, fout, colourspace, NULL, upsample) - * else: - */ - goto __pyx_L3; - } - - /* "_libjpeg.pyx":160 - * Reconstruct(fin, fout, colourspace, NULL, upsample) - * else: - * Reconstruct(fin, fout, colourspace, falpha, upsample) # <<<<<<<<<<<<<< - */ - /*else*/ { - __pyx_t_3 = __Pyx_PyObject_AsString(__pyx_v_fin); if (unlikely((!__pyx_t_3) && PyErr_Occurred())) __PYX_ERR(0, 160, __pyx_L1_error) - __pyx_t_4 = __Pyx_PyObject_AsString(__pyx_v_fout); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) __PYX_ERR(0, 160, __pyx_L1_error) - __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_v_colourspace); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 160, __pyx_L1_error) - __pyx_t_7 = __Pyx_PyObject_AsString(__pyx_v_falpha); if (unlikely((!__pyx_t_7) && PyErr_Occurred())) __PYX_ERR(0, 160, __pyx_L1_error) - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_upsample); if (unlikely((__pyx_t_6 == ((bool)-1)) && PyErr_Occurred())) __PYX_ERR(0, 160, __pyx_L1_error) - Reconstruct(__pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_7, __pyx_t_6); - } - __pyx_L3:; - - /* "_libjpeg.pyx":138 - * - * - * def reconstruct(fin, fout, colourspace, falpha, upsample): # <<<<<<<<<<<<<< - * """Decode the JPEG file in `fin` and write it to `fout` as PNM. - * - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("_libjpeg.reconstruct", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":258 - * # experimental exception made for __getbuffer__ and __releasebuffer__ - * # -- the details of this may change. - * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< - * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fulfill the PEP. - */ - -/* Python wrapper */ -static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { - int __pyx_v_i; - int __pyx_v_ndim; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - int __pyx_v_t; - char *__pyx_v_f; - PyArray_Descr *__pyx_v_descr = 0; - int __pyx_v_offset; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - PyArray_Descr *__pyx_t_7; - PyObject *__pyx_t_8 = NULL; - char *__pyx_t_9; - if (__pyx_v_info == NULL) { - PyErr_SetString(PyExc_BufferError, "PyObject_GetBuffer: view==NULL argument is obsolete"); - return -1; - } - __Pyx_RefNannySetupContext("__getbuffer__", 0); - __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(__pyx_v_info->obj); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":265 - * - * cdef int i, ndim - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * - */ - __pyx_v_endian_detector = 1; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":266 - * cdef int i, ndim - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< - * - * ndim = PyArray_NDIM(self) - */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":268 - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * - * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - */ - __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":270 - * ndim = PyArray_NDIM(self) - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") - */ - __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L4_bool_binop_done; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":271 - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not C contiguous") - * - */ - __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_ARRAY_C_CONTIGUOUS) != 0)) != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":270 - * ndim = PyArray_NDIM(self) - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") - */ - if (unlikely(__pyx_t_1)) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":272 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< - * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 272, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 272, __pyx_L1_error) - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":270 - * ndim = PyArray_NDIM(self) - * - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":274 - * raise ValueError(u"ndarray is not C contiguous") - * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") - */ - __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L7_bool_binop_done; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":275 - * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< - * raise ValueError(u"ndarray is not Fortran contiguous") - * - */ - __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_ARRAY_F_CONTIGUOUS) != 0)) != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L7_bool_binop_done:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":274 - * raise ValueError(u"ndarray is not C contiguous") - * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") - */ - if (unlikely(__pyx_t_1)) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":276 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< - * - * info.buf = PyArray_DATA(self) - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 276, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 276, __pyx_L1_error) - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":274 - * raise ValueError(u"ndarray is not C contiguous") - * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":278 - * raise ValueError(u"ndarray is not Fortran contiguous") - * - * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< - * info.ndim = ndim - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - */ - __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":279 - * - * info.buf = PyArray_DATA(self) - * info.ndim = ndim # <<<<<<<<<<<<<< - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * # Allocate new buffer for strides and shape info. - */ - __pyx_v_info->ndim = __pyx_v_ndim; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":280 - * info.buf = PyArray_DATA(self) - * info.ndim = ndim - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. - */ - __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); - if (__pyx_t_1) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":283 - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. - * info.strides = PyObject_Malloc(sizeof(Py_ssize_t) * 2 * ndim) # <<<<<<<<<<<<<< - * info.shape = info.strides + ndim - * for i in range(ndim): - */ - __pyx_v_info->strides = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * 2) * ((size_t)__pyx_v_ndim)))); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":284 - * # This is allocated as one block, strides first. - * info.strides = PyObject_Malloc(sizeof(Py_ssize_t) * 2 * ndim) - * info.shape = info.strides + ndim # <<<<<<<<<<<<<< - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] - */ - __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":285 - * info.strides = PyObject_Malloc(sizeof(Py_ssize_t) * 2 * ndim) - * info.shape = info.strides + ndim - * for i in range(ndim): # <<<<<<<<<<<<<< - * info.strides[i] = PyArray_STRIDES(self)[i] - * info.shape[i] = PyArray_DIMS(self)[i] - */ - __pyx_t_4 = __pyx_v_ndim; - __pyx_t_5 = __pyx_t_4; - for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) { - __pyx_v_i = __pyx_t_6; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":286 - * info.shape = info.strides + ndim - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< - * info.shape[i] = PyArray_DIMS(self)[i] - * else: - */ - (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":287 - * for i in range(ndim): - * info.strides[i] = PyArray_STRIDES(self)[i] - * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< - * else: - * info.strides = PyArray_STRIDES(self) - */ - (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":280 - * info.buf = PyArray_DATA(self) - * info.ndim = ndim - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * # Allocate new buffer for strides and shape info. - * # This is allocated as one block, strides first. - */ - goto __pyx_L9; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":289 - * info.shape[i] = PyArray_DIMS(self)[i] - * else: - * info.strides = PyArray_STRIDES(self) # <<<<<<<<<<<<<< - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL - */ - /*else*/ { - __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":290 - * else: - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) # <<<<<<<<<<<<<< - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) - */ - __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); - } - __pyx_L9:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":291 - * info.strides = PyArray_STRIDES(self) - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL # <<<<<<<<<<<<<< - * info.itemsize = PyArray_ITEMSIZE(self) - * info.readonly = not PyArray_ISWRITEABLE(self) - */ - __pyx_v_info->suboffsets = NULL; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":292 - * info.shape = PyArray_DIMS(self) - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< - * info.readonly = not PyArray_ISWRITEABLE(self) - * - */ - __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":293 - * info.suboffsets = NULL - * info.itemsize = PyArray_ITEMSIZE(self) - * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< - * - * cdef int t - */ - __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":296 - * - * cdef int t - * cdef char* f = NULL # <<<<<<<<<<<<<< - * cdef dtype descr = PyArray_DESCR(self) - * cdef int offset - */ - __pyx_v_f = NULL; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":297 - * cdef int t - * cdef char* f = NULL - * cdef dtype descr = PyArray_DESCR(self) # <<<<<<<<<<<<<< - * cdef int offset - * - */ - __pyx_t_7 = PyArray_DESCR(__pyx_v_self); - __pyx_t_3 = ((PyObject *)__pyx_t_7); - __Pyx_INCREF(__pyx_t_3); - __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); - __pyx_t_3 = 0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":300 - * cdef int offset - * - * info.obj = self # <<<<<<<<<<<<<< - * - * if not PyDataType_HASFIELDS(descr): - */ - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); - __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":302 - * info.obj = self - * - * if not PyDataType_HASFIELDS(descr): # <<<<<<<<<<<<<< - * t = descr.type_num - * if ((descr.byteorder == c'>' and little_endian) or - */ - __pyx_t_1 = ((!(PyDataType_HASFIELDS(__pyx_v_descr) != 0)) != 0); - if (__pyx_t_1) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":303 - * - * if not PyDataType_HASFIELDS(descr): - * t = descr.type_num # <<<<<<<<<<<<<< - * if ((descr.byteorder == c'>' and little_endian) or - * (descr.byteorder == c'<' and not little_endian)): - */ - __pyx_t_4 = __pyx_v_descr->type_num; - __pyx_v_t = __pyx_t_4; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":304 - * if not PyDataType_HASFIELDS(descr): - * t = descr.type_num - * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - */ - __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); - if (!__pyx_t_2) { - goto __pyx_L15_next_or; - } else { - } - __pyx_t_2 = (__pyx_v_little_endian != 0); - if (!__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L14_bool_binop_done; - } - __pyx_L15_next_or:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":305 - * t = descr.type_num - * if ((descr.byteorder == c'>' and little_endian) or - * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" - */ - __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); - if (__pyx_t_2) { - } else { - __pyx_t_1 = __pyx_t_2; - goto __pyx_L14_bool_binop_done; - } - __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L14_bool_binop_done:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":304 - * if not PyDataType_HASFIELDS(descr): - * t = descr.type_num - * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - */ - if (unlikely(__pyx_t_1)) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":306 - * if ((descr.byteorder == c'>' and little_endian) or - * (descr.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 306, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 306, __pyx_L1_error) - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":304 - * if not PyDataType_HASFIELDS(descr): - * t = descr.type_num - * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< - * (descr.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":307 - * (descr.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" - */ - switch (__pyx_v_t) { - case NPY_BYTE: - __pyx_v_f = ((char *)"b"); - break; - case NPY_UBYTE: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":308 - * raise ValueError(u"Non-native byte order not supported") - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" - */ - __pyx_v_f = ((char *)"B"); - break; - case NPY_SHORT: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":309 - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" - */ - __pyx_v_f = ((char *)"h"); - break; - case NPY_USHORT: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":310 - * elif t == NPY_UBYTE: f = "B" - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" - */ - __pyx_v_f = ((char *)"H"); - break; - case NPY_INT: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":311 - * elif t == NPY_SHORT: f = "h" - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" - */ - __pyx_v_f = ((char *)"i"); - break; - case NPY_UINT: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":312 - * elif t == NPY_USHORT: f = "H" - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" - */ - __pyx_v_f = ((char *)"I"); - break; - case NPY_LONG: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":313 - * elif t == NPY_INT: f = "i" - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" - */ - __pyx_v_f = ((char *)"l"); - break; - case NPY_ULONG: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":314 - * elif t == NPY_UINT: f = "I" - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" - */ - __pyx_v_f = ((char *)"L"); - break; - case NPY_LONGLONG: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":315 - * elif t == NPY_LONG: f = "l" - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" - */ - __pyx_v_f = ((char *)"q"); - break; - case NPY_ULONGLONG: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":316 - * elif t == NPY_ULONG: f = "L" - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" - */ - __pyx_v_f = ((char *)"Q"); - break; - case NPY_FLOAT: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":317 - * elif t == NPY_LONGLONG: f = "q" - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" - */ - __pyx_v_f = ((char *)"f"); - break; - case NPY_DOUBLE: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":318 - * elif t == NPY_ULONGLONG: f = "Q" - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" - */ - __pyx_v_f = ((char *)"d"); - break; - case NPY_LONGDOUBLE: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":319 - * elif t == NPY_FLOAT: f = "f" - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" - */ - __pyx_v_f = ((char *)"g"); - break; - case NPY_CFLOAT: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":320 - * elif t == NPY_DOUBLE: f = "d" - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" - */ - __pyx_v_f = ((char *)"Zf"); - break; - case NPY_CDOUBLE: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":321 - * elif t == NPY_LONGDOUBLE: f = "g" - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< - * elif t == NPY_CLONGDOUBLE: f = "Zg" - * elif t == NPY_OBJECT: f = "O" - */ - __pyx_v_f = ((char *)"Zd"); - break; - case NPY_CLONGDOUBLE: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":322 - * elif t == NPY_CFLOAT: f = "Zf" - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f = "O" - * else: - */ - __pyx_v_f = ((char *)"Zg"); - break; - case NPY_OBJECT: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":323 - * elif t == NPY_CDOUBLE: f = "Zd" - * elif t == NPY_CLONGDOUBLE: f = "Zg" - * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - */ - __pyx_v_f = ((char *)"O"); - break; - default: - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":325 - * elif t == NPY_OBJECT: f = "O" - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< - * info.format = f - * return - */ - __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 325, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 325, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 325, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 325, __pyx_L1_error) - break; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":326 - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * info.format = f # <<<<<<<<<<<<<< - * return - * else: - */ - __pyx_v_info->format = __pyx_v_f; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":327 - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * info.format = f - * return # <<<<<<<<<<<<<< - * else: - * info.format = PyObject_Malloc(_buffer_format_string_len) - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":302 - * info.obj = self - * - * if not PyDataType_HASFIELDS(descr): # <<<<<<<<<<<<<< - * t = descr.type_num - * if ((descr.byteorder == c'>' and little_endian) or - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":329 - * return - * else: - * info.format = PyObject_Malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< - * info.format[0] = c'^' # Native data types, manual alignment - * offset = 0 - */ - /*else*/ { - __pyx_v_info->format = ((char *)PyObject_Malloc(0xFF)); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":330 - * else: - * info.format = PyObject_Malloc(_buffer_format_string_len) - * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< - * offset = 0 - * f = _util_dtypestring(descr, info.format + 1, - */ - (__pyx_v_info->format[0]) = '^'; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":331 - * info.format = PyObject_Malloc(_buffer_format_string_len) - * info.format[0] = c'^' # Native data types, manual alignment - * offset = 0 # <<<<<<<<<<<<<< - * f = _util_dtypestring(descr, info.format + 1, - * info.format + _buffer_format_string_len, - */ - __pyx_v_offset = 0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":332 - * info.format[0] = c'^' # Native data types, manual alignment - * offset = 0 - * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< - * info.format + _buffer_format_string_len, - * &offset) - */ - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 0xFF), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == ((char *)NULL))) __PYX_ERR(1, 332, __pyx_L1_error) - __pyx_v_f = __pyx_t_9; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":335 - * info.format + _buffer_format_string_len, - * &offset) - * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< - * - * def __releasebuffer__(ndarray self, Py_buffer* info): - */ - (__pyx_v_f[0]) = '\x00'; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":258 - * # experimental exception made for __getbuffer__ and __releasebuffer__ - * # -- the details of this may change. - * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< - * # This implementation of getbuffer is geared towards Cython - * # requirements, and does not yet fulfill the PEP. - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - if (__pyx_v_info->obj != NULL) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - goto __pyx_L2; - __pyx_L0:; - if (__pyx_v_info->obj == Py_None) { - __Pyx_GOTREF(__pyx_v_info->obj); - __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = 0; - } - __pyx_L2:; - __Pyx_XDECREF((PyObject *)__pyx_v_descr); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":337 - * f[0] = c'\0' # Terminate format string - * - * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< - * if PyArray_HASFIELDS(self): - * PyObject_Free(info.format) - */ - -/* Python wrapper */ -static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ -static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); - __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("__releasebuffer__", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":338 - * - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< - * PyObject_Free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - */ - __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); - if (__pyx_t_1) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":339 - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): - * PyObject_Free(info.format) # <<<<<<<<<<<<<< - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * PyObject_Free(info.strides) - */ - PyObject_Free(__pyx_v_info->format); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":338 - * - * def __releasebuffer__(ndarray self, Py_buffer* info): - * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< - * PyObject_Free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":340 - * if PyArray_HASFIELDS(self): - * PyObject_Free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * PyObject_Free(info.strides) - * # info.shape was stored after info.strides in the same block - */ - __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); - if (__pyx_t_1) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":341 - * PyObject_Free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): - * PyObject_Free(info.strides) # <<<<<<<<<<<<<< - * # info.shape was stored after info.strides in the same block - * - */ - PyObject_Free(__pyx_v_info->strides); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":340 - * if PyArray_HASFIELDS(self): - * PyObject_Free(info.format) - * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< - * PyObject_Free(info.strides) - * # info.shape was stored after info.strides in the same block - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":337 - * f[0] = c'\0' # Terminate format string - * - * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< - * if PyArray_HASFIELDS(self): - * PyObject_Free(info.format) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":821 - * ctypedef npy_cdouble complex_t - * - * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(1, a) - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":822 - * - * cdef inline object PyArray_MultiIterNew1(a): - * return PyArray_MultiIterNew(1, a) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew2(a, b): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 822, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":821 - * ctypedef npy_cdouble complex_t - * - * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(1, a) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":824 - * return PyArray_MultiIterNew(1, a) - * - * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(2, a, b) - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":825 - * - * cdef inline object PyArray_MultiIterNew2(a, b): - * return PyArray_MultiIterNew(2, a, b) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 825, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":824 - * return PyArray_MultiIterNew(1, a) - * - * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(2, a, b) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":827 - * return PyArray_MultiIterNew(2, a, b) - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(3, a, b, c) - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":828 - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): - * return PyArray_MultiIterNew(3, a, b, c) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 828, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":827 - * return PyArray_MultiIterNew(2, a, b) - * - * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(3, a, b, c) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":830 - * return PyArray_MultiIterNew(3, a, b, c) - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(4, a, b, c, d) - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":831 - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): - * return PyArray_MultiIterNew(4, a, b, c, d) # <<<<<<<<<<<<<< - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 831, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":830 - * return PyArray_MultiIterNew(3, a, b, c) - * - * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(4, a, b, c, d) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":833 - * return PyArray_MultiIterNew(4, a, b, c, d) - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":834 - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): - * return PyArray_MultiIterNew(5, a, b, c, d, e) # <<<<<<<<<<<<<< - * - * cdef inline tuple PyDataType_SHAPE(dtype d): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 834, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":833 - * return PyArray_MultiIterNew(4, a, b, c, d) - * - * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":836 - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * - * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< - * if PyDataType_HASSUBARRAY(d): - * return d.subarray.shape - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyDataType_SHAPE(PyArray_Descr *__pyx_v_d) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("PyDataType_SHAPE", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":837 - * - * cdef inline tuple PyDataType_SHAPE(dtype d): - * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< - * return d.subarray.shape - * else: - */ - __pyx_t_1 = (PyDataType_HASSUBARRAY(__pyx_v_d) != 0); - if (__pyx_t_1) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":838 - * cdef inline tuple PyDataType_SHAPE(dtype d): - * if PyDataType_HASSUBARRAY(d): - * return d.subarray.shape # <<<<<<<<<<<<<< - * else: - * return () - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject*)__pyx_v_d->subarray->shape)); - __pyx_r = ((PyObject*)__pyx_v_d->subarray->shape); - goto __pyx_L0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":837 - * - * cdef inline tuple PyDataType_SHAPE(dtype d): - * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< - * return d.subarray.shape - * else: - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":840 - * return d.subarray.shape - * else: - * return () # <<<<<<<<<<<<<< - * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_empty_tuple); - __pyx_r = __pyx_empty_tuple; - goto __pyx_L0; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":836 - * return PyArray_MultiIterNew(5, a, b, c, d, e) - * - * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< - * if PyDataType_HASSUBARRAY(d): - * return d.subarray.shape - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":842 - * return () - * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< - * # Recursive utility function used in __getbuffer__ to get format - * # string. The new location in the format string is returned. - */ - -static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { - PyArray_Descr *__pyx_v_child = 0; - int __pyx_v_endian_detector; - int __pyx_v_little_endian; - PyObject *__pyx_v_fields = 0; - PyObject *__pyx_v_childname = NULL; - PyObject *__pyx_v_new_offset = NULL; - PyObject *__pyx_v_t = NULL; - char *__pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - long __pyx_t_8; - char *__pyx_t_9; - __Pyx_RefNannySetupContext("_util_dtypestring", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":847 - * - * cdef dtype child - * cdef int endian_detector = 1 # <<<<<<<<<<<<<< - * cdef bint little_endian = ((&endian_detector)[0] != 0) - * cdef tuple fields - */ - __pyx_v_endian_detector = 1; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":848 - * cdef dtype child - * cdef int endian_detector = 1 - * cdef bint little_endian = ((&endian_detector)[0] != 0) # <<<<<<<<<<<<<< - * cdef tuple fields - * - */ - __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":851 - * cdef tuple fields - * - * for childname in descr.names: # <<<<<<<<<<<<<< - * fields = descr.fields[childname] - * child, new_offset = fields - */ - if (unlikely(__pyx_v_descr->names == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - __PYX_ERR(1, 851, __pyx_L1_error) - } - __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(1, 851, __pyx_L1_error) - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 851, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); - __pyx_t_3 = 0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":852 - * - * for childname in descr.names: - * fields = descr.fields[childname] # <<<<<<<<<<<<<< - * child, new_offset = fields - * - */ - if (unlikely(__pyx_v_descr->fields == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 852, __pyx_L1_error) - } - __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 852, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) __PYX_ERR(1, 852, __pyx_L1_error) - __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); - __pyx_t_3 = 0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":853 - * for childname in descr.names: - * fields = descr.fields[childname] - * child, new_offset = fields # <<<<<<<<<<<<<< - * - * if (end - f) - (new_offset - offset[0]) < 15: - */ - if (likely(__pyx_v_fields != Py_None)) { - PyObject* sequence = __pyx_v_fields; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(1, 853, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - #else - __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 853, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 853, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - #endif - } else { - __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 853, __pyx_L1_error) - } - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) __PYX_ERR(1, 853, __pyx_L1_error) - __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); - __pyx_t_3 = 0; - __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); - __pyx_t_4 = 0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":855 - * child, new_offset = fields - * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") - * - */ - __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 855, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 855, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 855, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); - if (unlikely(__pyx_t_6)) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":856 - * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< - * - * if ((child.byteorder == c'>' and little_endian) or - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 856, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 856, __pyx_L1_error) - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":855 - * child, new_offset = fields - * - * if (end - f) - (new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") - * - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":858 - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") - * - * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - */ - __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); - if (!__pyx_t_7) { - goto __pyx_L8_next_or; - } else { - } - __pyx_t_7 = (__pyx_v_little_endian != 0); - if (!__pyx_t_7) { - } else { - __pyx_t_6 = __pyx_t_7; - goto __pyx_L7_bool_binop_done; - } - __pyx_L8_next_or:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":859 - * - * if ((child.byteorder == c'>' and little_endian) or - * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< - * raise ValueError(u"Non-native byte order not supported") - * # One could encode it in the format string and have Cython - */ - __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); - if (__pyx_t_7) { - } else { - __pyx_t_6 = __pyx_t_7; - goto __pyx_L7_bool_binop_done; - } - __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); - __pyx_t_6 = __pyx_t_7; - __pyx_L7_bool_binop_done:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":858 - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") - * - * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - */ - if (unlikely(__pyx_t_6)) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":860 - * if ((child.byteorder == c'>' and little_endian) or - * (child.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * # One could encode it in the format string and have Cython - * # complain instead, BUT: < and > in format strings also imply - */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 860, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 860, __pyx_L1_error) - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":858 - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") - * - * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< - * (child.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":870 - * - * # Output padding bytes - * while offset[0] < new_offset: # <<<<<<<<<<<<<< - * f[0] = 120 # "x"; pad byte - * f += 1 - */ - while (1) { - __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 870, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 870, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 870, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (!__pyx_t_6) break; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":871 - * # Output padding bytes - * while offset[0] < new_offset: - * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< - * f += 1 - * offset[0] += 1 - */ - (__pyx_v_f[0]) = 0x78; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":872 - * while offset[0] < new_offset: - * f[0] = 120 # "x"; pad byte - * f += 1 # <<<<<<<<<<<<<< - * offset[0] += 1 - * - */ - __pyx_v_f = (__pyx_v_f + 1); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":873 - * f[0] = 120 # "x"; pad byte - * f += 1 - * offset[0] += 1 # <<<<<<<<<<<<<< - * - * offset[0] += child.itemsize - */ - __pyx_t_8 = 0; - (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":875 - * offset[0] += 1 - * - * offset[0] += child.itemsize # <<<<<<<<<<<<<< - * - * if not PyDataType_HASFIELDS(child): - */ - __pyx_t_8 = 0; - (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":877 - * offset[0] += child.itemsize - * - * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< - * t = child.type_num - * if end - f < 5: - */ - __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); - if (__pyx_t_6) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":878 - * - * if not PyDataType_HASFIELDS(child): - * t = child.type_num # <<<<<<<<<<<<<< - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") - */ - __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 878, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); - __pyx_t_4 = 0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":879 - * if not PyDataType_HASFIELDS(child): - * t = child.type_num - * if end - f < 5: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short.") - * - */ - __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); - if (unlikely(__pyx_t_6)) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":880 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< - * - * # Until ticket #99 is fixed, use integers to avoid warnings - */ - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 880, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __PYX_ERR(1, 880, __pyx_L1_error) - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":879 - * if not PyDataType_HASFIELDS(child): - * t = child.type_num - * if end - f < 5: # <<<<<<<<<<<<<< - * raise RuntimeError(u"Format string allocated too short.") - * - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":883 - * - * # Until ticket #99 is fixed, use integers to avoid warnings - * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" - */ - __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_BYTE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 883, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 883, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 883, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 98; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":884 - * # Until ticket #99 is fixed, use integers to avoid warnings - * if t == NPY_BYTE: f[0] = 98 #"b" - * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" - */ - __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UBYTE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 884, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 884, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 884, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 66; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":885 - * if t == NPY_BYTE: f[0] = 98 #"b" - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" - */ - __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_SHORT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 885, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 885, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 885, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 0x68; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":886 - * elif t == NPY_UBYTE: f[0] = 66 #"B" - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" - */ - __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_USHORT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 886, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 886, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 886, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 72; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":887 - * elif t == NPY_SHORT: f[0] = 104 #"h" - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" - */ - __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_INT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 887, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 887, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 887, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 0x69; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":888 - * elif t == NPY_USHORT: f[0] = 72 #"H" - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" - */ - __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UINT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 888, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 888, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 888, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 73; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":889 - * elif t == NPY_INT: f[0] = 105 #"i" - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - */ - __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 889, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 889, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 889, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 0x6C; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":890 - * elif t == NPY_UINT: f[0] = 73 #"I" - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - */ - __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 890, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 890, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 890, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 76; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":891 - * elif t == NPY_LONG: f[0] = 108 #"l" - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" - */ - __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 891, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 891, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 891, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 0x71; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":892 - * elif t == NPY_ULONG: f[0] = 76 #"L" - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - */ - __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 892, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 892, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 892, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 81; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":893 - * elif t == NPY_LONGLONG: f[0] = 113 #"q" - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - */ - __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_FLOAT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 893, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 893, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 893, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 0x66; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":894 - * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - */ - __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 894, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 894, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 894, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 0x64; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":895 - * elif t == NPY_FLOAT: f[0] = 102 #"f" - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - */ - __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 895, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 895, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 895, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 0x67; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":896 - * elif t == NPY_DOUBLE: f[0] = 100 #"d" - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - */ - __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 896, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 896, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 896, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 0x66; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":897 - * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - * elif t == NPY_OBJECT: f[0] = 79 #"O" - */ - __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 897, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 897, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 897, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 0x64; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":898 - * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< - * elif t == NPY_OBJECT: f[0] = 79 #"O" - * else: - */ - __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 898, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 898, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 898, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (__pyx_t_6) { - (__pyx_v_f[0]) = 90; - (__pyx_v_f[1]) = 0x67; - __pyx_v_f = (__pyx_v_f + 1); - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":899 - * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd - * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg - * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - */ - __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_OBJECT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 899, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 899, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 899, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - if (likely(__pyx_t_6)) { - (__pyx_v_f[0]) = 79; - goto __pyx_L15; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":901 - * elif t == NPY_OBJECT: f[0] = 79 #"O" - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< - * f += 1 - * else: - */ - /*else*/ { - __pyx_t_3 = __Pyx_PyUnicode_FormatSafe(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 901, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_ValueError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 901, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __PYX_ERR(1, 901, __pyx_L1_error) - } - __pyx_L15:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":902 - * else: - * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) - * f += 1 # <<<<<<<<<<<<<< - * else: - * # Cython ignores struct boundary information ("T{...}"), - */ - __pyx_v_f = (__pyx_v_f + 1); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":877 - * offset[0] += child.itemsize - * - * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< - * t = child.type_num - * if end - f < 5: - */ - goto __pyx_L13; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":906 - * # Cython ignores struct boundary information ("T{...}"), - * # so don't output it - * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< - * return f - * - */ - /*else*/ { - __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == ((char *)NULL))) __PYX_ERR(1, 906, __pyx_L1_error) - __pyx_v_f = __pyx_t_9; - } - __pyx_L13:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":851 - * cdef tuple fields - * - * for childname in descr.names: # <<<<<<<<<<<<<< - * fields = descr.fields[childname] - * child, new_offset = fields - */ - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":907 - * # so don't output it - * f = _util_dtypestring(child, f, end, offset) - * return f # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_v_f; - goto __pyx_L0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":842 - * return () - * - * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< - * # Recursive utility function used in __getbuffer__ to get format - * # string. The new location in the format string is returned. - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_child); - __Pyx_XDECREF(__pyx_v_fields); - __Pyx_XDECREF(__pyx_v_childname); - __Pyx_XDECREF(__pyx_v_new_offset); - __Pyx_XDECREF(__pyx_v_t); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1022 - * int _import_umath() except -1 - * - * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< - * Py_INCREF(base) # important to do this before stealing the reference below! - * PyArray_SetBaseObject(arr, base) - */ - -static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("set_array_base", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1023 - * - * cdef inline void set_array_base(ndarray arr, object base): - * Py_INCREF(base) # important to do this before stealing the reference below! # <<<<<<<<<<<<<< - * PyArray_SetBaseObject(arr, base) - * - */ - Py_INCREF(__pyx_v_base); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1024 - * cdef inline void set_array_base(ndarray arr, object base): - * Py_INCREF(base) # important to do this before stealing the reference below! - * PyArray_SetBaseObject(arr, base) # <<<<<<<<<<<<<< - * - * cdef inline object get_array_base(ndarray arr): - */ - (void)(PyArray_SetBaseObject(__pyx_v_arr, __pyx_v_base)); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1022 - * int _import_umath() except -1 - * - * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< - * Py_INCREF(base) # important to do this before stealing the reference below! - * PyArray_SetBaseObject(arr, base) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1026 - * PyArray_SetBaseObject(arr, base) - * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * base = PyArray_BASE(arr) - * if base is NULL: - */ - -static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { - PyObject *__pyx_v_base; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("get_array_base", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1027 - * - * cdef inline object get_array_base(ndarray arr): - * base = PyArray_BASE(arr) # <<<<<<<<<<<<<< - * if base is NULL: - * return None - */ - __pyx_v_base = PyArray_BASE(__pyx_v_arr); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1028 - * cdef inline object get_array_base(ndarray arr): - * base = PyArray_BASE(arr) - * if base is NULL: # <<<<<<<<<<<<<< - * return None - * return base - */ - __pyx_t_1 = ((__pyx_v_base == NULL) != 0); - if (__pyx_t_1) { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1029 - * base = PyArray_BASE(arr) - * if base is NULL: - * return None # <<<<<<<<<<<<<< - * return base - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1028 - * cdef inline object get_array_base(ndarray arr): - * base = PyArray_BASE(arr) - * if base is NULL: # <<<<<<<<<<<<<< - * return None - * return base - */ - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1030 - * if base is NULL: - * return None - * return base # <<<<<<<<<<<<<< - * - * # Versions of the import_* functions which are more suitable for - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_base)); - __pyx_r = ((PyObject *)__pyx_v_base); - goto __pyx_L0; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1026 - * PyArray_SetBaseObject(arr, base) - * - * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< - * base = PyArray_BASE(arr) - * if base is NULL: - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1034 - * # Versions of the import_* functions which are more suitable for - * # Cython code. - * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< - * try: - * _import_array() - */ - -static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - __Pyx_RefNannySetupContext("import_array", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1035 - * # Cython code. - * cdef inline int import_array() except -1: - * try: # <<<<<<<<<<<<<< - * _import_array() - * except Exception: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - /*try:*/ { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1036 - * cdef inline int import_array() except -1: - * try: - * _import_array() # <<<<<<<<<<<<<< - * except Exception: - * raise ImportError("numpy.core.multiarray failed to import") - */ - __pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1036, __pyx_L3_error) - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1035 - * # Cython code. - * cdef inline int import_array() except -1: - * try: # <<<<<<<<<<<<<< - * _import_array() - * except Exception: - */ - } - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_try_end; - __pyx_L3_error:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1037 - * try: - * _import_array() - * except Exception: # <<<<<<<<<<<<<< - * raise ImportError("numpy.core.multiarray failed to import") - * - */ - __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); - if (__pyx_t_4) { - __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1037, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_7); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1038 - * _import_array() - * except Exception: - * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< - * - * cdef inline int import_umath() except -1: - */ - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1038, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __PYX_ERR(1, 1038, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1035 - * # Cython code. - * cdef inline int import_array() except -1: - * try: # <<<<<<<<<<<<<< - * _import_array() - * except Exception: - */ - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L1_error; - __pyx_L8_try_end:; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1034 - * # Versions of the import_* functions which are more suitable for - * # Cython code. - * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< - * try: - * _import_array() - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1040 - * raise ImportError("numpy.core.multiarray failed to import") - * - * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< - * try: - * _import_umath() - */ - -static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - __Pyx_RefNannySetupContext("import_umath", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1041 - * - * cdef inline int import_umath() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - /*try:*/ { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1042 - * cdef inline int import_umath() except -1: - * try: - * _import_umath() # <<<<<<<<<<<<<< - * except Exception: - * raise ImportError("numpy.core.umath failed to import") - */ - __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1042, __pyx_L3_error) - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1041 - * - * cdef inline int import_umath() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - } - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_try_end; - __pyx_L3_error:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1043 - * try: - * _import_umath() - * except Exception: # <<<<<<<<<<<<<< - * raise ImportError("numpy.core.umath failed to import") - * - */ - __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); - if (__pyx_t_4) { - __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1043, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_7); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1044 - * _import_umath() - * except Exception: - * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< - * - * cdef inline int import_ufunc() except -1: - */ - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1044, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __PYX_ERR(1, 1044, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1041 - * - * cdef inline int import_umath() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L1_error; - __pyx_L8_try_end:; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1040 - * raise ImportError("numpy.core.multiarray failed to import") - * - * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< - * try: - * _import_umath() - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1046 - * raise ImportError("numpy.core.umath failed to import") - * - * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< - * try: - * _import_umath() - */ - -static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - __Pyx_RefNannySetupContext("import_ufunc", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1047 - * - * cdef inline int import_ufunc() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - /*try:*/ { - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1048 - * cdef inline int import_ufunc() except -1: - * try: - * _import_umath() # <<<<<<<<<<<<<< - * except Exception: - * raise ImportError("numpy.core.umath failed to import") - */ - __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1048, __pyx_L3_error) - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1047 - * - * cdef inline int import_ufunc() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - } - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L8_try_end; - __pyx_L3_error:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1049 - * try: - * _import_umath() - * except Exception: # <<<<<<<<<<<<<< - * raise ImportError("numpy.core.umath failed to import") - */ - __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); - if (__pyx_t_4) { - __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1049, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_7); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1050 - * _import_umath() - * except Exception: - * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< - */ - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1050, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __PYX_ERR(1, 1050, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1047 - * - * cdef inline int import_ufunc() except -1: - * try: # <<<<<<<<<<<<<< - * _import_umath() - * except Exception: - */ - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L1_error; - __pyx_L8_try_end:; - } - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1046 - * raise ImportError("numpy.core.umath failed to import") - * - * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< - * try: - * _import_umath() - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "string.to_py":31 - * - * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) - * cdef extern from *: - */ - -static CYTHON_INLINE PyObject *__pyx_convert_PyObject_string_to_py_std__in_string(std::string const &__pyx_v_s) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("__pyx_convert_PyObject_string_to_py_std__in_string", 0); - - /* "string.to_py":32 - * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): - * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< - * cdef extern from *: - * cdef object __Pyx_PyUnicode_FromStringAndSize(const char*, size_t) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 32, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "string.to_py":31 - * - * @cname("__pyx_convert_PyObject_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyObject_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyObject_FromStringAndSize(s.data(), s.size()) - * cdef extern from *: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("string.to_py.__pyx_convert_PyObject_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "string.to_py":37 - * - * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) - * cdef extern from *: - */ - -static CYTHON_INLINE PyObject *__pyx_convert_PyUnicode_string_to_py_std__in_string(std::string const &__pyx_v_s) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("__pyx_convert_PyUnicode_string_to_py_std__in_string", 0); - - /* "string.to_py":38 - * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): - * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< - * cdef extern from *: - * cdef object __Pyx_PyStr_FromStringAndSize(const char*, size_t) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyUnicode_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "string.to_py":37 - * - * @cname("__pyx_convert_PyUnicode_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyUnicode_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyUnicode_FromStringAndSize(s.data(), s.size()) - * cdef extern from *: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("string.to_py.__pyx_convert_PyUnicode_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "string.to_py":43 - * - * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) - * cdef extern from *: - */ - -static CYTHON_INLINE PyObject *__pyx_convert_PyStr_string_to_py_std__in_string(std::string const &__pyx_v_s) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("__pyx_convert_PyStr_string_to_py_std__in_string", 0); - - /* "string.to_py":44 - * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): - * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< - * cdef extern from *: - * cdef object __Pyx_PyBytes_FromStringAndSize(const char*, size_t) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyStr_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 44, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "string.to_py":43 - * - * @cname("__pyx_convert_PyStr_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyStr_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyStr_FromStringAndSize(s.data(), s.size()) - * cdef extern from *: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("string.to_py.__pyx_convert_PyStr_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "string.to_py":49 - * - * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) - * cdef extern from *: - */ - -static CYTHON_INLINE PyObject *__pyx_convert_PyBytes_string_to_py_std__in_string(std::string const &__pyx_v_s) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("__pyx_convert_PyBytes_string_to_py_std__in_string", 0); - - /* "string.to_py":50 - * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): - * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< - * cdef extern from *: - * cdef object __Pyx_PyByteArray_FromStringAndSize(const char*, size_t) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 50, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "string.to_py":49 - * - * @cname("__pyx_convert_PyBytes_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyBytes_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyBytes_FromStringAndSize(s.data(), s.size()) - * cdef extern from *: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("string.to_py.__pyx_convert_PyBytes_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "string.to_py":55 - * - * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) - * - */ - -static CYTHON_INLINE PyObject *__pyx_convert_PyByteArray_string_to_py_std__in_string(std::string const &__pyx_v_s) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("__pyx_convert_PyByteArray_string_to_py_std__in_string", 0); - - /* "string.to_py":56 - * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): - * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) # <<<<<<<<<<<<<< - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyByteArray_FromStringAndSize(__pyx_v_s.data(), __pyx_v_s.size()); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "string.to_py":55 - * - * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("string.to_py.__pyx_convert_PyByteArray_string_to_py_std__in_string", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -#if CYTHON_PEP489_MULTI_PHASE_INIT -static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ -static int __pyx_pymod_exec__libjpeg(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec__libjpeg}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "_libjpeg", - 0, /* m_doc */ - #if CYTHON_PEP489_MULTI_PHASE_INIT - 0, /* m_size */ - #else - -1, /* m_size */ - #endif - __pyx_methods /* m_methods */, - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_moduledef_slots, /* m_slots */ - #else - NULL, /* m_reload */ - #endif - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) - #define CYTHON_SMALL_CODE __attribute__((cold)) -#else - #define CYTHON_SMALL_CODE -#endif -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, - {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, - {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, - {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, - {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, - {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, - {&__pyx_n_u_bits_per_sample, __pyx_k_bits_per_sample, sizeof(__pyx_k_bits_per_sample), 0, 1, 0, 1}, - {&__pyx_n_s_bpp, __pyx_k_bpp, sizeof(__pyx_k_bpp), 0, 0, 1, 1}, - {&__pyx_n_s_ceil, __pyx_k_ceil, sizeof(__pyx_k_ceil), 0, 0, 1, 1}, - {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, - {&__pyx_n_s_colourspace, __pyx_k_colourspace, sizeof(__pyx_k_colourspace), 0, 0, 1, 1}, - {&__pyx_n_u_columns, __pyx_k_columns, sizeof(__pyx_k_columns), 0, 1, 0, 1}, - {&__pyx_n_s_decode, __pyx_k_decode, sizeof(__pyx_k_decode), 0, 0, 1, 1}, - {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, - {&__pyx_n_s_falpha, __pyx_k_falpha, sizeof(__pyx_k_falpha), 0, 0, 1, 1}, - {&__pyx_n_s_fin, __pyx_k_fin, sizeof(__pyx_k_fin), 0, 0, 1, 1}, - {&__pyx_n_s_fout, __pyx_k_fout, sizeof(__pyx_k_fout), 0, 0, 1, 1}, - {&__pyx_n_s_get_parameters, __pyx_k_get_parameters, sizeof(__pyx_k_get_parameters), 0, 0, 1, 1}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_n_s_input_buffer, __pyx_k_input_buffer, sizeof(__pyx_k_input_buffer), 0, 0, 1, 1}, - {&__pyx_n_s_libjpeg, __pyx_k_libjpeg, sizeof(__pyx_k_libjpeg), 0, 0, 1, 1}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_math, __pyx_k_math, sizeof(__pyx_k_math), 0, 0, 1, 1}, - {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, - {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, - {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, - {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, - {&__pyx_n_s_nr_bytes, __pyx_k_nr_bytes, sizeof(__pyx_k_nr_bytes), 0, 0, 1, 1}, - {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, - {&__pyx_kp_u_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 1, 0, 0}, - {&__pyx_kp_u_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 1, 0, 0}, - {&__pyx_n_s_output_buffer, __pyx_k_output_buffer, sizeof(__pyx_k_output_buffer), 0, 0, 1, 1}, - {&__pyx_n_s_pInput, __pyx_k_pInput, sizeof(__pyx_k_pInput), 0, 0, 1, 1}, - {&__pyx_n_s_pOutput, __pyx_k_pOutput, sizeof(__pyx_k_pOutput), 0, 0, 1, 1}, - {&__pyx_n_s_pParam, __pyx_k_pParam, sizeof(__pyx_k_pParam), 0, 0, 1, 1}, - {&__pyx_n_s_param, __pyx_k_param, sizeof(__pyx_k_param), 0, 0, 1, 1}, - {&__pyx_n_s_parameters, __pyx_k_parameters, sizeof(__pyx_k_parameters), 0, 0, 1, 1}, - {&__pyx_kp_s_pylibjpeg__libjpeg_pyx, __pyx_k_pylibjpeg__libjpeg_pyx, sizeof(__pyx_k_pylibjpeg__libjpeg_pyx), 0, 0, 1, 0}, - {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, - {&__pyx_n_s_reconstruct, __pyx_k_reconstruct, sizeof(__pyx_k_reconstruct), 0, 0, 1, 1}, - {&__pyx_n_u_rows, __pyx_k_rows, sizeof(__pyx_k_rows), 0, 1, 0, 1}, - {&__pyx_n_u_samples_per_pixel, __pyx_k_samples_per_pixel, sizeof(__pyx_k_samples_per_pixel), 0, 1, 0, 1}, - {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, - {&__pyx_n_s_status, __pyx_k_status, sizeof(__pyx_k_status), 0, 0, 1, 1}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_n_s_uint8, __pyx_k_uint8, sizeof(__pyx_k_uint8), 0, 0, 1, 1}, - {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, - {&__pyx_n_s_upsample, __pyx_k_upsample, sizeof(__pyx_k_upsample), 0, 0, 1, 1}, - {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 272, __pyx_L1_error) - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(1, 285, __pyx_L1_error) - __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(1, 856, __pyx_L1_error) - __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(1, 1038, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":272 - * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_C_CONTIGUOUS)): - * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< - * - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - */ - __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 272, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple_); - __Pyx_GIVEREF(__pyx_tuple_); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":276 - * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) - * and not PyArray_CHKFLAGS(self, NPY_ARRAY_F_CONTIGUOUS)): - * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< - * - * info.buf = PyArray_DATA(self) - */ - __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 276, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__2); - __Pyx_GIVEREF(__pyx_tuple__2); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":306 - * if ((descr.byteorder == c'>' and little_endian) or - * (descr.byteorder == c'<' and not little_endian)): - * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< - * if t == NPY_BYTE: f = "b" - * elif t == NPY_UBYTE: f = "B" - */ - __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 306, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__3); - __Pyx_GIVEREF(__pyx_tuple__3); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":856 - * - * if (end - f) - (new_offset - offset[0]) < 15: - * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< - * - * if ((child.byteorder == c'>' and little_endian) or - */ - __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 856, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__4); - __Pyx_GIVEREF(__pyx_tuple__4); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":880 - * t = child.type_num - * if end - f < 5: - * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< - * - * # Until ticket #99 is fixed, use integers to avoid warnings - */ - __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 880, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__5); - __Pyx_GIVEREF(__pyx_tuple__5); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1038 - * _import_array() - * except Exception: - * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< - * - * cdef inline int import_umath() except -1: - */ - __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 1038, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__6); - __Pyx_GIVEREF(__pyx_tuple__6); - - /* "../../env/pyjpg/lib/python3.6/site-packages/Cython/Includes/numpy/__init__.pxd":1044 - * _import_umath() - * except Exception: - * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< - * - * cdef inline int import_ufunc() except -1: - */ - __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_u_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 1044, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__7); - __Pyx_GIVEREF(__pyx_tuple__7); - - /* "_libjpeg.pyx":36 - * - * - * def decode(np.ndarray[np.uint8_t, ndim=1] input_buffer, colourspace): # <<<<<<<<<<<<<< - * """Return the decoded JPEG data from `input_buffer`. - * - */ - __pyx_tuple__8 = PyTuple_Pack(9, __pyx_n_s_input_buffer, __pyx_n_s_colourspace, __pyx_n_s_status, __pyx_n_s_param, __pyx_n_s_pInput, __pyx_n_s_bpp, __pyx_n_s_nr_bytes, __pyx_n_s_output_buffer, __pyx_n_s_pOutput); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(0, 36, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__8); - __Pyx_GIVEREF(__pyx_tuple__8); - __pyx_codeobj__9 = (PyObject*)__Pyx_PyCode_New(2, 0, 9, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__8, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_pylibjpeg__libjpeg_pyx, __pyx_n_s_decode, 36, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__9)) __PYX_ERR(0, 36, __pyx_L1_error) - - /* "_libjpeg.pyx":86 - * - * - * def get_parameters(np.ndarray[np.uint8_t, ndim=1] input_buffer): # <<<<<<<<<<<<<< - * """Return a :class:`dict` containing the JPEG image parameters. - * - */ - __pyx_tuple__10 = PyTuple_Pack(6, __pyx_n_s_input_buffer, __pyx_n_s_param, __pyx_n_s_pParam, __pyx_n_s_pInput, __pyx_n_s_status, __pyx_n_s_parameters); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(0, 86, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__10); - __Pyx_GIVEREF(__pyx_tuple__10); - __pyx_codeobj__11 = (PyObject*)__Pyx_PyCode_New(1, 0, 6, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__10, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_pylibjpeg__libjpeg_pyx, __pyx_n_s_get_parameters, 86, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__11)) __PYX_ERR(0, 86, __pyx_L1_error) - - /* "_libjpeg.pyx":138 - * - * - * def reconstruct(fin, fout, colourspace, falpha, upsample): # <<<<<<<<<<<<<< - * """Decode the JPEG file in `fin` and write it to `fout` as PNM. - * - */ - __pyx_tuple__12 = PyTuple_Pack(5, __pyx_n_s_fin, __pyx_n_s_fout, __pyx_n_s_colourspace, __pyx_n_s_falpha, __pyx_n_s_upsample); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__12); - __Pyx_GIVEREF(__pyx_tuple__12); - __pyx_codeobj__13 = (PyObject*)__Pyx_PyCode_New(5, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__12, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_pylibjpeg__libjpeg_pyx, __pyx_n_s_reconstruct, 138, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__13)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - __pyx_int_8 = PyInt_FromLong(8); if (unlikely(!__pyx_int_8)) __PYX_ERR(0, 1, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ - -static int __Pyx_modinit_global_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); - /*--- Global init code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); - /*--- Variable export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); - /*--- Function export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); - /*--- Type init code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_import_code(void) { - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); - /*--- Type import code ---*/ - __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", - #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 - sizeof(PyTypeObject), - #else - sizeof(PyHeapTypeObject), - #endif - __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(3, 9, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyImport_ImportModule("numpy"); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 206, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_5numpy_dtype = __Pyx_ImportType(__pyx_t_1, "numpy", "dtype", sizeof(PyArray_Descr), __Pyx_ImportType_CheckSize_Ignore); - if (!__pyx_ptype_5numpy_dtype) __PYX_ERR(1, 206, __pyx_L1_error) - __pyx_ptype_5numpy_flatiter = __Pyx_ImportType(__pyx_t_1, "numpy", "flatiter", sizeof(PyArrayIterObject), __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_5numpy_flatiter) __PYX_ERR(1, 229, __pyx_L1_error) - __pyx_ptype_5numpy_broadcast = __Pyx_ImportType(__pyx_t_1, "numpy", "broadcast", sizeof(PyArrayMultiIterObject), __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_5numpy_broadcast) __PYX_ERR(1, 233, __pyx_L1_error) - __pyx_ptype_5numpy_ndarray = __Pyx_ImportType(__pyx_t_1, "numpy", "ndarray", sizeof(PyArrayObject), __Pyx_ImportType_CheckSize_Ignore); - if (!__pyx_ptype_5numpy_ndarray) __PYX_ERR(1, 242, __pyx_L1_error) - __pyx_ptype_5numpy_ufunc = __Pyx_ImportType(__pyx_t_1, "numpy", "ufunc", sizeof(PyUFuncObject), __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_5numpy_ufunc) __PYX_ERR(1, 918, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_modinit_variable_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); - /*--- Variable import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); - /*--- Function import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - - -#if PY_MAJOR_VERSION < 3 -#ifdef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC void -#else -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#endif -#else -#ifdef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC PyObject * -#else -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#endif -#endif - - -#if PY_MAJOR_VERSION < 3 -__Pyx_PyMODINIT_FUNC init_libjpeg(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC init_libjpeg(void) -#else -__Pyx_PyMODINIT_FUNC PyInit__libjpeg(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit__libjpeg(void) -#if CYTHON_PEP489_MULTI_PHASE_INIT -{ - return PyModuleDef_Init(&__pyx_moduledef); -} -static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { - #if PY_VERSION_HEX >= 0x030700A1 - static PY_INT64_T main_interpreter_id = -1; - PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); - if (main_interpreter_id == -1) { - main_interpreter_id = current_id; - return (unlikely(current_id == -1)) ? -1 : 0; - } else if (unlikely(main_interpreter_id != current_id)) - #else - static PyInterpreterState *main_interpreter = NULL; - PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; - if (!main_interpreter) { - main_interpreter = current_interpreter; - } else if (unlikely(main_interpreter != current_interpreter)) - #endif - { - PyErr_SetString( - PyExc_ImportError, - "Interpreter change detected - this module can only be loaded into one interpreter per process."); - return -1; - } - return 0; -} -static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { - PyObject *value = PyObject_GetAttrString(spec, from_name); - int result = 0; - if (likely(value)) { - if (allow_none || value != Py_None) { - result = PyDict_SetItemString(moddict, to_name, value); - } - Py_DECREF(value); - } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - } else { - result = -1; - } - return result; -} -static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { - PyObject *module = NULL, *moddict, *modname; - if (__Pyx_check_single_interpreter()) - return NULL; - if (__pyx_m) - return __Pyx_NewRef(__pyx_m); - modname = PyObject_GetAttrString(spec, "name"); - if (unlikely(!modname)) goto bad; - module = PyModule_NewObject(modname); - Py_DECREF(modname); - if (unlikely(!module)) goto bad; - moddict = PyModule_GetDict(module); - if (unlikely(!moddict)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; - return module; -bad: - Py_XDECREF(module); - return NULL; -} - - -static CYTHON_SMALL_CODE int __pyx_pymod_exec__libjpeg(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - __Pyx_RefNannyDeclarations - #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m) { - if (__pyx_m == __pyx_pyinit_module) return 0; - PyErr_SetString(PyExc_RuntimeError, "Module '_libjpeg' has already been imported. Re-initialisation is not supported."); - return -1; - } - #elif PY_MAJOR_VERSION >= 3 - if (__pyx_m) return __Pyx_NewRef(__pyx_m); - #endif - #if CYTHON_REFNANNY -__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); -if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); -} -#endif - __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit__libjpeg(void)", 0); - if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pxy_PyFrame_Initialize_Offsets - __Pxy_PyFrame_Initialize_Offsets(); - #endif - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pyx_CyFunction_USED - if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Coroutine_USED - if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_StopAsyncIteration_USED - if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #endif - /*--- Module creation code ---*/ - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_m = __pyx_pyinit_module; - Py_INCREF(__pyx_m); - #else - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4("_libjpeg", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_b); - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_cython_runtime); - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - if (__pyx_module_is_main__libjpeg) { - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - } - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) - if (!PyDict_GetItemString(modules, "_libjpeg")) { - if (unlikely(PyDict_SetItemString(modules, "_libjpeg", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - } - } - #endif - /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) goto __pyx_L1_error; - /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) goto __pyx_L1_error; - /*--- Global type/function init code ---*/ - (void)__Pyx_modinit_global_init_code(); - (void)__Pyx_modinit_variable_export_code(); - (void)__Pyx_modinit_function_export_code(); - (void)__Pyx_modinit_type_init_code(); - if (unlikely(__Pyx_modinit_type_import_code() != 0)) goto __pyx_L1_error; - (void)__Pyx_modinit_variable_import_code(); - (void)__Pyx_modinit_function_import_code(); - /*--- Execution code ---*/ - #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - - /* "_libjpeg.pyx":4 - * # distutils: language=c++ - * - * from math import ceil # <<<<<<<<<<<<<< - * - * from libcpp cimport bool - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_ceil); - __Pyx_GIVEREF(__pyx_n_s_ceil); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_ceil); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_math, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_ceil); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_ceil, __pyx_t_1) < 0) __PYX_ERR(0, 4, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "_libjpeg.pyx":9 - * from libcpp.string cimport string - * - * import numpy as np # <<<<<<<<<<<<<< - * cimport numpy as np - * - */ - __pyx_t_2 = __Pyx_Import(__pyx_n_s_numpy, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_2) < 0) __PYX_ERR(0, 9, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "_libjpeg.pyx":36 - * - * - * def decode(np.ndarray[np.uint8_t, ndim=1] input_buffer, colourspace): # <<<<<<<<<<<<<< - * """Return the decoded JPEG data from `input_buffer`. - * - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8_libjpeg_1decode, NULL, __pyx_n_s_libjpeg); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 36, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_decode, __pyx_t_2) < 0) __PYX_ERR(0, 36, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "_libjpeg.pyx":86 - * - * - * def get_parameters(np.ndarray[np.uint8_t, ndim=1] input_buffer): # <<<<<<<<<<<<<< - * """Return a :class:`dict` containing the JPEG image parameters. - * - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8_libjpeg_3get_parameters, NULL, __pyx_n_s_libjpeg); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 86, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_get_parameters, __pyx_t_2) < 0) __PYX_ERR(0, 86, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "_libjpeg.pyx":138 - * - * - * def reconstruct(fin, fout, colourspace, falpha, upsample): # <<<<<<<<<<<<<< - * """Decode the JPEG file in `fin` and write it to `fout` as PNM. - * - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_8_libjpeg_5reconstruct, NULL, __pyx_n_s_libjpeg); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_reconstruct, __pyx_t_2) < 0) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "_libjpeg.pyx":1 - * # cython: language_level=3 # <<<<<<<<<<<<<< - * # distutils: language=c++ - * - */ - __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "string.to_py":55 - * - * @cname("__pyx_convert_PyByteArray_string_to_py_std__in_string") - * cdef inline object __pyx_convert_PyByteArray_string_to_py_std__in_string(const string& s): # <<<<<<<<<<<<<< - * return __Pyx_PyByteArray_FromStringAndSize(s.data(), s.size()) - * - */ - - /*--- Wrapped vars code ---*/ - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init _libjpeg", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init _libjpeg"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if CYTHON_PEP489_MULTI_PHASE_INIT - return (__pyx_m != NULL) ? 0 : -1; - #elif PY_MAJOR_VERSION >= 3 - return __pyx_m; - #else - return; - #endif -} - -/* --- Runtime support code --- */ -/* Refnanny */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule(modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, "RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif - -/* RaiseArgTupleInvalid */ -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -/* RaiseDoubleKeywords */ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - -/* ParseKeywords */ -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -/* ArgTypeTest */ -static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) -{ - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - else if (exact) { - #if PY_MAJOR_VERSION == 2 - if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; - #endif - } - else { - if (likely(__Pyx_TypeCheck(obj, type))) return 1; - } - PyErr_Format(PyExc_TypeError, - "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; -} - -/* IsLittleEndian */ -static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) -{ - union { - uint32_t u32; - uint8_t u8[4]; - } S; - S.u32 = 0x01020304; - return S.u8[0] == 4; -} - -/* BufferFormatCheck */ -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type) { - stack[0].field = &ctx->root; - stack[0].parent_offset = 0; - ctx->root.type = type; - ctx->root.name = "buffer dtype"; - ctx->root.offset = 0; - ctx->head = stack; - ctx->head->field = &ctx->root; - ctx->fmt_offset = 0; - ctx->head->parent_offset = 0; - ctx->new_packmode = '@'; - ctx->enc_packmode = '@'; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->is_complex = 0; - ctx->is_valid_array = 0; - ctx->struct_alignment = 0; - while (type->typegroup == 'S') { - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = 0; - type = type->fields->type; - } -} -static int __Pyx_BufFmt_ParseNumber(const char** ts) { - int count; - const char* t = *ts; - if (*t < '0' || *t > '9') { - return -1; - } else { - count = *t++ - '0'; - while (*t >= '0' && *t <= '9') { - count *= 10; - count += *t++ - '0'; - } - } - *ts = t; - return count; -} -static int __Pyx_BufFmt_ExpectNumber(const char **ts) { - int number = __Pyx_BufFmt_ParseNumber(ts); - if (number == -1) - PyErr_Format(PyExc_ValueError,\ - "Does not understand character buffer dtype format string ('%c')", **ts); - return number; -} -static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { - PyErr_Format(PyExc_ValueError, - "Unexpected format string character: '%c'", ch); -} -static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { - switch (ch) { - case '?': return "'bool'"; - case 'c': return "'char'"; - case 'b': return "'signed char'"; - case 'B': return "'unsigned char'"; - case 'h': return "'short'"; - case 'H': return "'unsigned short'"; - case 'i': return "'int'"; - case 'I': return "'unsigned int'"; - case 'l': return "'long'"; - case 'L': return "'unsigned long'"; - case 'q': return "'long long'"; - case 'Q': return "'unsigned long long'"; - case 'f': return (is_complex ? "'complex float'" : "'float'"); - case 'd': return (is_complex ? "'complex double'" : "'double'"); - case 'g': return (is_complex ? "'complex long double'" : "'long double'"); - case 'T': return "a struct"; - case 'O': return "Python object"; - case 'P': return "a pointer"; - case 's': case 'p': return "a string"; - case 0: return "end"; - default: return "unparseable format string"; - } -} -static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return 2; - case 'i': case 'I': case 'l': case 'L': return 4; - case 'q': case 'Q': return 8; - case 'f': return (is_complex ? 8 : 4); - case 'd': return (is_complex ? 16 : 8); - case 'g': { - PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); - return 0; - } - case 'O': case 'P': return sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(short); - case 'i': case 'I': return sizeof(int); - case 'l': case 'L': return sizeof(long); - #ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(PY_LONG_LONG); - #endif - case 'f': return sizeof(float) * (is_complex ? 2 : 1); - case 'd': return sizeof(double) * (is_complex ? 2 : 1); - case 'g': return sizeof(long double) * (is_complex ? 2 : 1); - case 'O': case 'P': return sizeof(void*); - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } -} -typedef struct { char c; short x; } __Pyx_st_short; -typedef struct { char c; int x; } __Pyx_st_int; -typedef struct { char c; long x; } __Pyx_st_long; -typedef struct { char c; float x; } __Pyx_st_float; -typedef struct { char c; double x; } __Pyx_st_double; -typedef struct { char c; long double x; } __Pyx_st_longdouble; -typedef struct { char c; void *x; } __Pyx_st_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; -#endif -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_st_float) - sizeof(float); - case 'd': return sizeof(__Pyx_st_double) - sizeof(double); - case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -/* These are for computing the padding at the end of the struct to align - on the first member of the struct. This will probably the same as above, - but we don't have any guarantees. - */ -typedef struct { short x; char c; } __Pyx_pad_short; -typedef struct { int x; char c; } __Pyx_pad_int; -typedef struct { long x; char c; } __Pyx_pad_long; -typedef struct { float x; char c; } __Pyx_pad_float; -typedef struct { double x; char c; } __Pyx_pad_double; -typedef struct { long double x; char c; } __Pyx_pad_longdouble; -typedef struct { void *x; char c; } __Pyx_pad_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; -#endif -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); - case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); - case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } -} -static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { - switch (ch) { - case 'c': - return 'H'; - case 'b': case 'h': case 'i': - case 'l': case 'q': case 's': case 'p': - return 'I'; - case '?': case 'B': case 'H': case 'I': case 'L': case 'Q': - return 'U'; - case 'f': case 'd': case 'g': - return (is_complex ? 'C' : 'R'); - case 'O': - return 'O'; - case 'P': - return 'P'; - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } -} -static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { - if (ctx->head == NULL || ctx->head->field == &ctx->root) { - const char* expected; - const char* quote; - if (ctx->head == NULL) { - expected = "end"; - quote = ""; - } else { - expected = ctx->head->field->type->name; - quote = "'"; - } - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected %s%s%s but got %s", - quote, expected, quote, - __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); - } else { - __Pyx_StructField* field = ctx->head->field; - __Pyx_StructField* parent = (ctx->head - 1)->field; - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", - field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), - parent->type->name, field->name); - } -} -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset, arraysize = 1; - if (ctx->enc_type == 0) return 0; - if (ctx->head->field->type->arraysize[0]) { - int i, ndim = 0; - if (ctx->enc_type == 's' || ctx->enc_type == 'p') { - ctx->is_valid_array = ctx->head->field->type->ndim == 1; - ndim = 1; - if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { - PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %zu", - ctx->head->field->type->arraysize[0], ctx->enc_count); - return -1; - } - } - if (!ctx->is_valid_array) { - PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", - ctx->head->field->type->ndim, ndim); - return -1; - } - for (i = 0; i < ctx->head->field->type->ndim; i++) { - arraysize *= ctx->head->field->type->arraysize[i]; - } - ctx->is_valid_array = 0; - ctx->enc_count = 1; - } - group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); - do { - __Pyx_StructField* field = ctx->head->field; - __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { - size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); - } else { - size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); - } - if (ctx->enc_packmode == '@') { - size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); - size_t align_mod_offset; - if (align_at == 0) return -1; - align_mod_offset = ctx->fmt_offset % align_at; - if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; - if (ctx->struct_alignment == 0) - ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, - ctx->is_complex); - } - if (type->size != size || type->typegroup != group) { - if (type->typegroup == 'C' && type->fields != NULL) { - size_t parent_offset = ctx->head->parent_offset + field->offset; - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = parent_offset; - continue; - } - if ((type->typegroup == 'H' || group == 'H') && type->size == size) { - } else { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - } - offset = ctx->head->parent_offset + field->offset; - if (ctx->fmt_offset != offset) { - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", - (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); - return -1; - } - ctx->fmt_offset += size; - if (arraysize) - ctx->fmt_offset += (arraysize - 1) * size; - --ctx->enc_count; - while (1) { - if (field == &ctx->root) { - ctx->head = NULL; - if (ctx->enc_count != 0) { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - break; - } - ctx->head->field = ++field; - if (field->type == NULL) { - --ctx->head; - field = ctx->head->field; - continue; - } else if (field->type->typegroup == 'S') { - size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; - field = field->type->fields; - ++ctx->head; - ctx->head->field = field; - ctx->head->parent_offset = parent_offset; - break; - } else { - break; - } - } - } while (ctx->enc_count); - ctx->enc_type = 0; - ctx->is_complex = 0; - return 0; -} -static PyObject * -__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) -{ - const char *ts = *tsp; - int i = 0, number; - int ndim = ctx->head->field->type->ndim; -; - ++ts; - if (ctx->new_count != 1) { - PyErr_SetString(PyExc_ValueError, - "Cannot handle repeated arrays in format string"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - while (*ts && *ts != ')') { - switch (*ts) { - case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; - default: break; - } - number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) - return PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %d", - ctx->head->field->type->arraysize[i], number); - if (*ts != ',' && *ts != ')') - return PyErr_Format(PyExc_ValueError, - "Expected a comma in format string, got '%c'", *ts); - if (*ts == ',') ts++; - i++; - } - if (i != ndim) - return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", - ctx->head->field->type->ndim, i); - if (!*ts) { - PyErr_SetString(PyExc_ValueError, - "Unexpected end of format string, expected ')'"); - return NULL; - } - ctx->is_valid_array = 1; - ctx->new_count = 1; - *tsp = ++ts; - return Py_None; -} -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { - int got_Z = 0; - while (1) { - switch(*ts) { - case 0: - if (ctx->enc_type != 0 && ctx->head == NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - if (ctx->head != NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - return ts; - case ' ': - case '\r': - case '\n': - ++ts; - break; - case '<': - if (!__Pyx_Is_Little_Endian()) { - PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '>': - case '!': - if (__Pyx_Is_Little_Endian()) { - PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '=': - case '@': - case '^': - ctx->new_packmode = *ts++; - break; - case 'T': - { - const char* ts_after_sub; - size_t i, struct_count = ctx->new_count; - size_t struct_alignment = ctx->struct_alignment; - ctx->new_count = 1; - ++ts; - if (*ts != '{') { - PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; - ctx->enc_count = 0; - ctx->struct_alignment = 0; - ++ts; - ts_after_sub = ts; - for (i = 0; i != struct_count; ++i) { - ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); - if (!ts_after_sub) return NULL; - } - ts = ts_after_sub; - if (struct_alignment) ctx->struct_alignment = struct_alignment; - } - break; - case '}': - { - size_t alignment = ctx->struct_alignment; - ++ts; - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; - if (alignment && ctx->fmt_offset % alignment) { - ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); - } - } - return ts; - case 'x': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->fmt_offset += ctx->new_count; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->enc_packmode = ctx->new_packmode; - ++ts; - break; - case 'Z': - got_Z = 1; - ++ts; - if (*ts != 'f' && *ts != 'd' && *ts != 'g') { - __Pyx_BufFmt_RaiseUnexpectedChar('Z'); - return NULL; - } - CYTHON_FALLTHROUGH; - case '?': case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': - case 'l': case 'L': case 'q': case 'Q': - case 'f': case 'd': case 'g': - case 'O': case 'p': - if (ctx->enc_type == *ts && got_Z == ctx->is_complex && - ctx->enc_packmode == ctx->new_packmode) { - ctx->enc_count += ctx->new_count; - ctx->new_count = 1; - got_Z = 0; - ++ts; - break; - } - CYTHON_FALLTHROUGH; - case 's': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; - ++ts; - ctx->new_count = 1; - got_Z = 0; - break; - case ':': - ++ts; - while(*ts != ':') ++ts; - ++ts; - break; - case '(': - if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; - break; - default: - { - int number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - ctx->new_count = (size_t)number; - } - } - } -} - -/* BufferGetAndValidate */ - static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { - if (unlikely(info->buf == NULL)) return; - if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; - __Pyx_ReleaseBuffer(info); -} -static void __Pyx_ZeroBuffer(Py_buffer* buf) { - buf->buf = NULL; - buf->obj = NULL; - buf->strides = __Pyx_zeros; - buf->shape = __Pyx_zeros; - buf->suboffsets = __Pyx_minusones; -} -static int __Pyx__GetBufferAndValidate( - Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, - int nd, int cast, __Pyx_BufFmt_StackElem* stack) -{ - buf->buf = NULL; - if (unlikely(__Pyx_GetBuffer(obj, buf, flags) == -1)) { - __Pyx_ZeroBuffer(buf); - return -1; - } - if (unlikely(buf->ndim != nd)) { - PyErr_Format(PyExc_ValueError, - "Buffer has wrong number of dimensions (expected %d, got %d)", - nd, buf->ndim); - goto fail; - } - if (!cast) { - __Pyx_BufFmt_Context ctx; - __Pyx_BufFmt_Init(&ctx, stack, dtype); - if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; - } - if (unlikely((size_t)buf->itemsize != dtype->size)) { - PyErr_Format(PyExc_ValueError, - "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", - buf->itemsize, (buf->itemsize > 1) ? "s" : "", - dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); - goto fail; - } - if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; - return 0; -fail:; - __Pyx_SafeReleaseBuffer(buf); - return -1; -} - -/* PyObjectGetAttrStr */ - #if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#endif - -/* GetBuiltinName */ - static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -/* PyDictVersioning */ - #if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { - PyObject **dictptr = NULL; - Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; - if (offset) { -#if CYTHON_COMPILING_IN_CPYTHON - dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); -#else - dictptr = _PyObject_GetDictPtr(obj); -#endif - } - return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; -} -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) - return 0; - return obj_dict_version == __Pyx_get_object_dict_version(obj); -} -#endif - -/* GetModuleGlobalName */ - #if CYTHON_USE_DICT_VERSIONS -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) -#else -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) -#endif -{ - PyObject *result; -#if !CYTHON_AVOID_BORROWED_REFS -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 - result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } else if (unlikely(PyErr_Occurred())) { - return NULL; - } -#else - result = PyDict_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } -#endif -#else - result = PyObject_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } - PyErr_Clear(); -#endif - return __Pyx_GetBuiltinName(name); -} - -/* PyCFunctionFastCall */ - #if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { - PyCFunctionObject *func = (PyCFunctionObject*)func_obj; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - int flags = PyCFunction_GET_FLAGS(func); - assert(PyCFunction_Check(func)); - assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); - assert(nargs >= 0); - assert(nargs == 0 || args != NULL); - /* _PyCFunction_FastCallDict() must not be called with an exception set, - because it may clear it (directly or indirectly) and so the - caller loses its exception */ - assert(!PyErr_Occurred()); - if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { - return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); - } else { - return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); - } -} -#endif - -/* PyFunctionFastCall */ - #if CYTHON_FAST_PYCALL -static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, - PyObject *globals) { - PyFrameObject *f; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject **fastlocals; - Py_ssize_t i; - PyObject *result; - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) { - return NULL; - } - fastlocals = __Pyx_PyFrame_GetLocalsplus(f); - for (i = 0; i < na; i++) { - Py_INCREF(*args); - fastlocals[i] = *args++; - } - result = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return result; -} -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *closure; -#if PY_MAJOR_VERSION >= 3 - PyObject *kwdefs; -#endif - PyObject *kwtuple, **k; - PyObject **d; - Py_ssize_t nd; - Py_ssize_t nk; - PyObject *result; - assert(kwargs == NULL || PyDict_Check(kwargs)); - nk = kwargs ? PyDict_Size(kwargs) : 0; - if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { - return NULL; - } - if ( -#if PY_MAJOR_VERSION >= 3 - co->co_kwonlyargcount == 0 && -#endif - likely(kwargs == NULL || nk == 0) && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - if (argdefs == NULL && co->co_argcount == nargs) { - result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); - goto done; - } - else if (nargs == 0 && argdefs != NULL - && co->co_argcount == Py_SIZE(argdefs)) { - /* function called with no arguments, but all parameters have - a default value: use default values as arguments .*/ - args = &PyTuple_GET_ITEM(argdefs, 0); - result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); - goto done; - } - } - if (kwargs != NULL) { - Py_ssize_t pos, i; - kwtuple = PyTuple_New(2 * nk); - if (kwtuple == NULL) { - result = NULL; - goto done; - } - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i / 2; - } - else { - kwtuple = NULL; - k = NULL; - } - closure = PyFunction_GET_CLOSURE(func); -#if PY_MAJOR_VERSION >= 3 - kwdefs = PyFunction_GET_KW_DEFAULTS(func); -#endif - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } -#if PY_MAJOR_VERSION >= 3 - result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, kwdefs, closure); -#else - result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, closure); -#endif - Py_XDECREF(kwtuple); -done: - Py_LeaveRecursiveCall(); - return result; -} -#endif -#endif - -/* PyObjectCall */ - #if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = func->ob_type->tp_call; - if (unlikely(!call)) - return PyObject_Call(func, arg, kw); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCall2Args */ - static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { - PyObject *args, *result = NULL; - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyFunction_FastCall(function, args, 2); - } - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyCFunction_FastCall(function, args, 2); - } - #endif - args = PyTuple_New(2); - if (unlikely(!args)) goto done; - Py_INCREF(arg1); - PyTuple_SET_ITEM(args, 0, arg1); - Py_INCREF(arg2); - PyTuple_SET_ITEM(args, 1, arg2); - Py_INCREF(function); - result = __Pyx_PyObject_Call(function, args, NULL); - Py_DECREF(args); - Py_DECREF(function); -done: - return result; -} - -/* PyObjectCallMethO */ - #if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { - PyObject *self, *result; - PyCFunction cfunc; - cfunc = PyCFunction_GET_FUNCTION(func); - self = PyCFunction_GET_SELF(func); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = cfunc(self, arg); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCallOneArg */ - #if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, arg); - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, &arg, 1); - } -#endif - if (likely(PyCFunction_Check(func))) { - if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { - return __Pyx_PyObject_CallMethO(func, arg); -#if CYTHON_FAST_PYCCALL - } else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { - return __Pyx_PyCFunction_FastCall(func, &arg, 1); -#endif - } - } - return __Pyx__PyObject_CallOneArg(func, arg); -} -#else -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_Pack(1, arg); - if (unlikely(!args)) return NULL; - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -#endif - -/* RaiseTooManyValuesToUnpack */ - static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -/* RaiseNeedMoreValuesToUnpack */ - static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", - index, (index == 1) ? "" : "s"); -} - -/* IterFinish */ - static CYTHON_INLINE int __Pyx_IterFinish(void) { -#if CYTHON_FAST_THREAD_STATE - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* exc_type = tstate->curexc_type; - if (unlikely(exc_type)) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) { - PyObject *exc_value, *exc_tb; - exc_value = tstate->curexc_value; - exc_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; - Py_DECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } else { - return -1; - } - } - return 0; -#else - if (unlikely(PyErr_Occurred())) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { - PyErr_Clear(); - return 0; - } else { - return -1; - } - } - return 0; -#endif -} - -/* UnpackItemEndCheck */ - static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); - return -1; - } else { - return __Pyx_IterFinish(); - } - return 0; -} - -/* PyIntBinop */ - #if !CYTHON_COMPILING_IN_PYPY -#if PY_MAJOR_VERSION < 3 || CYTHON_USE_PYLONG_INTERNALS -#define __Pyx_PyInt_TrueDivideObjC_ZeroDivisionError(operand)\ - if (unlikely(zerodivision_check && ((operand) == 0))) {\ - PyErr_SetString(PyExc_ZeroDivisionError, "integer division by zero");\ - return NULL;\ - } -#endif -static PyObject* __Pyx_PyInt_TrueDivideObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, int inplace, int zerodivision_check) { - (void)inplace; - (void)zerodivision_check; - #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(op1))) { - const long b = intval; - long a = PyInt_AS_LONG(op1); - __Pyx_PyInt_TrueDivideObjC_ZeroDivisionError(b) - if (8 * sizeof(long) <= 53 || likely(labs(a) <= ((PY_LONG_LONG)1 << 53))) { - return PyFloat_FromDouble((double)a / (double)b); - } - return PyInt_Type.tp_as_number->nb_true_divide(op1, op2); - } - #endif - #if CYTHON_USE_PYLONG_INTERNALS - if (likely(PyLong_CheckExact(op1))) { - const long b = intval; - long a, x; - const digit* digits = ((PyLongObject*)op1)->ob_digit; - const Py_ssize_t size = Py_SIZE(op1); - if (likely(__Pyx_sst_abs(size) <= 1)) { - a = likely(size) ? digits[0] : 0; - if (size == -1) a = -a; - } else { - switch (size) { - case -2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT && 1 * PyLong_SHIFT < 53) { - a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case 2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT && 1 * PyLong_SHIFT < 53) { - a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case -3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT && 2 * PyLong_SHIFT < 53) { - a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case 3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT && 2 * PyLong_SHIFT < 53) { - a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case -4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT && 3 * PyLong_SHIFT < 53) { - a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case 4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT && 3 * PyLong_SHIFT < 53) { - a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - default: return PyLong_Type.tp_as_number->nb_true_divide(op1, op2); - } - } - __Pyx_PyInt_TrueDivideObjC_ZeroDivisionError(b) - if ((8 * sizeof(long) <= 53 || likely(labs(a) <= ((PY_LONG_LONG)1 << 53))) - || __Pyx_sst_abs(size) <= 52 / PyLong_SHIFT) { - return PyFloat_FromDouble((double)a / (double)b); - } - return PyLong_Type.tp_as_number->nb_true_divide(op1, op2); - return PyLong_FromLong(x); - - } - #endif - if (PyFloat_CheckExact(op1)) { - const long b = intval; - double a = PyFloat_AS_DOUBLE(op1); - double result; - if (unlikely(zerodivision_check && b == 0)) { - PyErr_SetString(PyExc_ZeroDivisionError, "float division by zero"); - return NULL; - } - PyFPE_START_PROTECT("divide", return NULL) - result = ((double)a) / (double)b; - PyFPE_END_PROTECT(result) - return PyFloat_FromDouble(result); - } - return (inplace ? PyNumber_InPlaceTrueDivide : PyNumber_TrueDivide)(op1, op2); -} -#endif - -/* DictGetItem */ - #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY -static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { - PyObject *value; - value = PyDict_GetItemWithError(d, key); - if (unlikely(!value)) { - if (!PyErr_Occurred()) { - if (unlikely(PyTuple_Check(key))) { - PyObject* args = PyTuple_Pack(1, key); - if (likely(args)) { - PyErr_SetObject(PyExc_KeyError, args); - Py_DECREF(args); - } - } else { - PyErr_SetObject(PyExc_KeyError, key); - } - } - return NULL; - } - Py_INCREF(value); - return value; -} -#endif - -/* ExtTypeTest */ - static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(__Pyx_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -/* GetItemInt */ - static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyList_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyTuple_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return NULL; - PyErr_Clear(); - } - } - return m->sq_item(o, i); - } - } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} - -/* PyErrFetchRestore */ - #if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} -#endif - -/* RaiseException */ - #if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - __Pyx_PyThreadState_declare - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - if (PyType_Check(type)) { -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - value = type; - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - } - __Pyx_PyThreadState_assign - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *instance_class = NULL; - if (value && PyExceptionInstance_Check(value)) { - instance_class = (PyObject*) Py_TYPE(value); - if (instance_class != type) { - int is_subclass = PyObject_IsSubclass(instance_class, type); - if (!is_subclass) { - instance_class = NULL; - } else if (unlikely(is_subclass == -1)) { - goto bad; - } else { - type = instance_class; - } - } - } - if (!instance_class) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyObject_Call(type, args, NULL); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } - if (cause) { - PyObject *fixed_cause; - if (cause == Py_None) { - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - PyErr_SetObject(type, value); - if (tb) { -#if CYTHON_COMPILING_IN_PYPY - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); - Py_INCREF(tb); - PyErr_Restore(tmp_type, tmp_value, tb); - Py_XDECREF(tmp_tb); -#else - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } -#endif - } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -/* RaiseNoneIterError */ - static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); -} - -/* GetTopmostException */ - #if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * -__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) -{ - _PyErr_StackItem *exc_info = tstate->exc_info; - while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && - exc_info->previous_item != NULL) - { - exc_info = exc_info->previous_item; - } - return exc_info; -} -#endif - -/* SaveResetException */ - #if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); - *type = exc_info->exc_type; - *value = exc_info->exc_value; - *tb = exc_info->exc_traceback; - #else - *type = tstate->exc_type; - *value = tstate->exc_value; - *tb = tstate->exc_traceback; - #endif - Py_XINCREF(*type); - Py_XINCREF(*value); - Py_XINCREF(*tb); -} -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = type; - exc_info->exc_value = value; - exc_info->exc_traceback = tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = type; - tstate->exc_value = value; - tstate->exc_traceback = tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -#endif - -/* PyErrExceptionMatches */ - #if CYTHON_FAST_THREAD_STATE -static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; icurexc_type; - if (exc_type == err) return 1; - if (unlikely(!exc_type)) return 0; - if (unlikely(PyTuple_Check(err))) - return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); - return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); -} -#endif - -/* GetException */ - #if CYTHON_FAST_THREAD_STATE -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) -#endif -{ - PyObject *local_type, *local_value, *local_tb; -#if CYTHON_FAST_THREAD_STATE - PyObject *tmp_type, *tmp_value, *tmp_tb; - local_type = tstate->curexc_type; - local_value = tstate->curexc_value; - local_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(&local_type, &local_value, &local_tb); -#endif - PyErr_NormalizeException(&local_type, &local_value, &local_tb); -#if CYTHON_FAST_THREAD_STATE - if (unlikely(tstate->curexc_type)) -#else - if (unlikely(PyErr_Occurred())) -#endif - goto bad; - #if PY_MAJOR_VERSION >= 3 - if (local_tb) { - if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) - goto bad; - } - #endif - Py_XINCREF(local_tb); - Py_XINCREF(local_type); - Py_XINCREF(local_value); - *type = local_type; - *value = local_value; - *tb = local_tb; -#if CYTHON_FAST_THREAD_STATE - #if CYTHON_USE_EXC_INFO_STACK - { - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = local_type; - exc_info->exc_value = local_value; - exc_info->exc_traceback = local_tb; - } - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = local_type; - tstate->exc_value = local_value; - tstate->exc_traceback = local_tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(local_type, local_value, local_tb); -#endif - return 0; -bad: - *type = 0; - *value = 0; - *tb = 0; - Py_XDECREF(local_type); - Py_XDECREF(local_value); - Py_XDECREF(local_tb); - return -1; -} - -/* TypeImport */ - #ifndef __PYX_HAVE_RT_ImportType -#define __PYX_HAVE_RT_ImportType -static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name, - size_t size, enum __Pyx_ImportType_CheckSize check_size) -{ - PyObject *result = 0; - char warning[200]; - Py_ssize_t basicsize; -#ifdef Py_LIMITED_API - PyObject *py_basicsize; -#endif - result = PyObject_GetAttrString(module, class_name); - if (!result) - goto bad; - if (!PyType_Check(result)) { - PyErr_Format(PyExc_TypeError, - "%.200s.%.200s is not a type object", - module_name, class_name); - goto bad; - } -#ifndef Py_LIMITED_API - basicsize = ((PyTypeObject *)result)->tp_basicsize; -#else - py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); - if (!py_basicsize) - goto bad; - basicsize = PyLong_AsSsize_t(py_basicsize); - Py_DECREF(py_basicsize); - py_basicsize = 0; - if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) - goto bad; -#endif - if ((size_t)basicsize < size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - goto bad; - } - if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - goto bad; - } - else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) { - PyOS_snprintf(warning, sizeof(warning), - "%s.%s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - } - return (PyTypeObject *)result; -bad: - Py_XDECREF(result); - return NULL; -} -#endif - -/* Import */ - static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - #if PY_MAJOR_VERSION < 3 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if (strchr(__Pyx_MODULE_NAME, '.')) { - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; - } - #endif - if (!module) { - #if PY_MAJOR_VERSION < 3 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } -bad: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - -/* ImportFrom */ - static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { - PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); - if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, - #if PY_MAJOR_VERSION < 3 - "cannot import name %.230s", PyString_AS_STRING(name)); - #else - "cannot import name %S", name); - #endif - } - return value; -} - -/* CLineInTraceback */ - #ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line) { - PyObject *use_cline; - PyObject *ptype, *pvalue, *ptraceback; -#if CYTHON_COMPILING_IN_CPYTHON - PyObject **cython_runtime_dict; -#endif - if (unlikely(!__pyx_cython_runtime)) { - return c_line; - } - __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); -#if CYTHON_COMPILING_IN_CPYTHON - cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); - if (likely(cython_runtime_dict)) { - __PYX_PY_DICT_LOOKUP_IF_MODIFIED( - use_cline, *cython_runtime_dict, - __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) - } else -#endif - { - PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); - if (use_cline_obj) { - use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; - Py_DECREF(use_cline_obj); - } else { - PyErr_Clear(); - use_cline = NULL; - } - } - if (!use_cline) { - c_line = 0; - PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); - } - else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { - c_line = 0; - } - __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); - return c_line; -} -#endif - -/* CodeObjectCache */ - static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = start + (end - start) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -/* AddTraceback */ - #include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, - 0, - 0, - 0, - 0, - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - if (c_line) { - c_line = __Pyx_CLineForTraceback(tstate, c_line); - } - py_code = __pyx_find_code_object(c_line ? -c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); - } - py_frame = PyFrame_New( - tstate, /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - __Pyx_PyFrame_SetLineNumber(py_frame, py_line); - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - if (__Pyx_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); - PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; -} -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject *obj = view->obj; - if (!obj) return; - if (PyObject_CheckBuffer(obj)) { - PyBuffer_Release(view); - return; - } - if ((0)) {} - else if (__Pyx_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); - view->obj = NULL; - Py_DECREF(obj); -} -#endif - - - /* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { - const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(long) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(long) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(long), - little, !is_unsigned); - } -} - -/* CIntFromPyVerify */ - #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) -#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) -#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ - {\ - func_type value = func_value;\ - if (sizeof(target_type) < sizeof(func_type)) {\ - if (unlikely(value != (func_type) (target_type) value)) {\ - func_type zero = 0;\ - if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ - return (target_type) -1;\ - if (is_unsigned && unlikely(value < zero))\ - goto raise_neg_overflow;\ - else\ - goto raise_overflow;\ - }\ - }\ - return (target_type) value;\ - } - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { - const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(int) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(int) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(int) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(int), - little, !is_unsigned); - } -} - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_char(char value) { - const char neg_one = (char) ((char) 0 - (char) 1), const_zero = (char) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(char) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(char) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(char) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(char), - little, !is_unsigned); - } -} - -/* Declarations */ - #if CYTHON_CCOMPLEX - #ifdef __cplusplus - static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { - return ::std::complex< float >(x, y); - } - #else - static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { - return x + y*(__pyx_t_float_complex)_Complex_I; - } - #endif -#else - static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { - __pyx_t_float_complex z; - z.real = x; - z.imag = y; - return z; - } -#endif - -/* Arithmetic */ - #if CYTHON_CCOMPLEX -#else - static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - return (a.real == b.real) && (a.imag == b.imag); - } - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - __pyx_t_float_complex z; - z.real = a.real + b.real; - z.imag = a.imag + b.imag; - return z; - } - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - __pyx_t_float_complex z; - z.real = a.real - b.real; - z.imag = a.imag - b.imag; - return z; - } - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - __pyx_t_float_complex z; - z.real = a.real * b.real - a.imag * b.imag; - z.imag = a.real * b.imag + a.imag * b.real; - return z; - } - #if 1 - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - if (b.imag == 0) { - return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); - } else if (fabsf(b.real) >= fabsf(b.imag)) { - if (b.real == 0 && b.imag == 0) { - return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag); - } else { - float r = b.imag / b.real; - float s = (float)(1.0) / (b.real + b.imag * r); - return __pyx_t_float_complex_from_parts( - (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); - } - } else { - float r = b.real / b.imag; - float s = (float)(1.0) / (b.imag + b.real * r); - return __pyx_t_float_complex_from_parts( - (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); - } - } - #else - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - if (b.imag == 0) { - return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); - } else { - float denom = b.real * b.real + b.imag * b.imag; - return __pyx_t_float_complex_from_parts( - (a.real * b.real + a.imag * b.imag) / denom, - (a.imag * b.real - a.real * b.imag) / denom); - } - } - #endif - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex a) { - __pyx_t_float_complex z; - z.real = -a.real; - z.imag = -a.imag; - return z; - } - static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex a) { - return (a.real == 0) && (a.imag == 0); - } - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex a) { - __pyx_t_float_complex z; - z.real = a.real; - z.imag = -a.imag; - return z; - } - #if 1 - static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex z) { - #if !defined(HAVE_HYPOT) || defined(_MSC_VER) - return sqrtf(z.real*z.real + z.imag*z.imag); - #else - return hypotf(z.real, z.imag); - #endif - } - static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { - __pyx_t_float_complex z; - float r, lnr, theta, z_r, z_theta; - if (b.imag == 0 && b.real == (int)b.real) { - if (b.real < 0) { - float denom = a.real * a.real + a.imag * a.imag; - a.real = a.real / denom; - a.imag = -a.imag / denom; - b.real = -b.real; - } - switch ((int)b.real) { - case 0: - z.real = 1; - z.imag = 0; - return z; - case 1: - return a; - case 2: - return __Pyx_c_prod_float(a, a); - case 3: - z = __Pyx_c_prod_float(a, a); - return __Pyx_c_prod_float(z, a); - case 4: - z = __Pyx_c_prod_float(a, a); - return __Pyx_c_prod_float(z, z); - } - } - if (a.imag == 0) { - if (a.real == 0) { - return a; - } else if (b.imag == 0) { - z.real = powf(a.real, b.real); - z.imag = 0; - return z; - } else if (a.real > 0) { - r = a.real; - theta = 0; - } else { - r = -a.real; - theta = atan2f(0.0, -1.0); - } - } else { - r = __Pyx_c_abs_float(a); - theta = atan2f(a.imag, a.real); - } - lnr = logf(r); - z_r = expf(lnr * b.real - theta * b.imag); - z_theta = theta * b.real + lnr * b.imag; - z.real = z_r * cosf(z_theta); - z.imag = z_r * sinf(z_theta); - return z; - } - #endif -#endif - -/* Declarations */ - #if CYTHON_CCOMPLEX - #ifdef __cplusplus - static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { - return ::std::complex< double >(x, y); - } - #else - static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { - return x + y*(__pyx_t_double_complex)_Complex_I; - } - #endif -#else - static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { - __pyx_t_double_complex z; - z.real = x; - z.imag = y; - return z; - } -#endif - -/* Arithmetic */ - #if CYTHON_CCOMPLEX -#else - static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - return (a.real == b.real) && (a.imag == b.imag); - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - z.real = a.real + b.real; - z.imag = a.imag + b.imag; - return z; - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - z.real = a.real - b.real; - z.imag = a.imag - b.imag; - return z; - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - z.real = a.real * b.real - a.imag * b.imag; - z.imag = a.real * b.imag + a.imag * b.real; - return z; - } - #if 1 - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - if (b.imag == 0) { - return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); - } else if (fabs(b.real) >= fabs(b.imag)) { - if (b.real == 0 && b.imag == 0) { - return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); - } else { - double r = b.imag / b.real; - double s = (double)(1.0) / (b.real + b.imag * r); - return __pyx_t_double_complex_from_parts( - (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); - } - } else { - double r = b.real / b.imag; - double s = (double)(1.0) / (b.imag + b.real * r); - return __pyx_t_double_complex_from_parts( - (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); - } - } - #else - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - if (b.imag == 0) { - return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); - } else { - double denom = b.real * b.real + b.imag * b.imag; - return __pyx_t_double_complex_from_parts( - (a.real * b.real + a.imag * b.imag) / denom, - (a.imag * b.real - a.real * b.imag) / denom); - } - } - #endif - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) { - __pyx_t_double_complex z; - z.real = -a.real; - z.imag = -a.imag; - return z; - } - static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) { - return (a.real == 0) && (a.imag == 0); - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) { - __pyx_t_double_complex z; - z.real = a.real; - z.imag = -a.imag; - return z; - } - #if 1 - static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) { - #if !defined(HAVE_HYPOT) || defined(_MSC_VER) - return sqrt(z.real*z.real + z.imag*z.imag); - #else - return hypot(z.real, z.imag); - #endif - } - static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { - __pyx_t_double_complex z; - double r, lnr, theta, z_r, z_theta; - if (b.imag == 0 && b.real == (int)b.real) { - if (b.real < 0) { - double denom = a.real * a.real + a.imag * a.imag; - a.real = a.real / denom; - a.imag = -a.imag / denom; - b.real = -b.real; - } - switch ((int)b.real) { - case 0: - z.real = 1; - z.imag = 0; - return z; - case 1: - return a; - case 2: - return __Pyx_c_prod_double(a, a); - case 3: - z = __Pyx_c_prod_double(a, a); - return __Pyx_c_prod_double(z, a); - case 4: - z = __Pyx_c_prod_double(a, a); - return __Pyx_c_prod_double(z, z); - } - } - if (a.imag == 0) { - if (a.real == 0) { - return a; - } else if (b.imag == 0) { - z.real = pow(a.real, b.real); - z.imag = 0; - return z; - } else if (a.real > 0) { - r = a.real; - theta = 0; - } else { - r = -a.real; - theta = atan2(0.0, -1.0); - } - } else { - r = __Pyx_c_abs_double(a); - theta = atan2(a.imag, a.real); - } - lnr = log(r); - z_r = exp(lnr * b.real - theta * b.imag); - z_theta = theta * b.real + lnr * b.imag; - z.real = z_r * cos(z_theta); - z.imag = z_r * sin(z_theta); - return z; - } - #endif -#endif - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value) { - const enum NPY_TYPES neg_one = (enum NPY_TYPES) ((enum NPY_TYPES) 0 - (enum NPY_TYPES) 1), const_zero = (enum NPY_TYPES) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(enum NPY_TYPES) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(enum NPY_TYPES) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(enum NPY_TYPES) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(enum NPY_TYPES), - little, !is_unsigned); - } -} - -/* CIntFromPy */ - static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { - const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(int) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (int) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { - return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { - return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { - return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (int) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(int) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) - case -2: - if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - } -#endif - if (sizeof(int) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - int val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (int) -1; - } - } else { - int val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (int) -1; - val = __Pyx_PyInt_As_int(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to int"); - return (int) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to int"); - return (int) -1; -} - -/* CIntFromPy */ - static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { - const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(long) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (long) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { - return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { - return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { - return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (long) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(long) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) - case -2: - if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - } -#endif - if (sizeof(long) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - long val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (long) -1; - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (long) -1; - val = __Pyx_PyInt_As_long(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to long"); - return (long) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long) -1; -} - -/* FastTypeChecks */ - #if CYTHON_COMPILING_IN_CPYTHON -static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { - while (a) { - a = a->tp_base; - if (a == b) - return 1; - } - return b == &PyBaseObject_Type; -} -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; - if (a == b) return 1; - mro = a->tp_mro; - if (likely(mro)) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - return __Pyx_InBases(a, b); -} -#if PY_MAJOR_VERSION == 2 -static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { - PyObject *exception, *value, *tb; - int res; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&exception, &value, &tb); - res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - if (!res) { - res = PyObject_IsSubclass(err, exc_type2); - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - } - __Pyx_ErrRestore(exception, value, tb); - return res; -} -#else -static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { - int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; - if (!res) { - res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); - } - return res; -} -#endif -static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - assert(PyExceptionClass_Check(exc_type)); - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; ip) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; - if (PyObject_Hash(*t->p) == -1) - return -1; - ++t; - } - return 0; -} - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); -} -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -#if !CYTHON_PEP393_ENABLED -static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } - } - } -#endif - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; -} -#else -static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (likely(PyUnicode_IS_ASCII(o))) { - *length = PyUnicode_GET_LENGTH(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } -#else - return PyUnicode_AsUTF8AndSize(o, length); -#endif -} -#endif -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { - return __Pyx_PyUnicode_AsStringAndSize(o, length); - } else -#endif -#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) - if (PyByteArray_Check(o)) { - *length = PyByteArray_GET_SIZE(o); - return PyByteArray_AS_STRING(o); - } else -#endif - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (unlikely(r < 0)) { - return NULL; - } else { - return result; - } - } -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { - int retval; - if (unlikely(!x)) return -1; - retval = __Pyx_PyObject_IsTrue(x); - Py_DECREF(x); - return retval; -} -static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { -#if PY_MAJOR_VERSION >= 3 - if (PyLong_Check(result)) { - if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, - "__int__ returned non-int (type %.200s). " - "The ability to return an instance of a strict subclass of int " - "is deprecated, and may be removed in a future version of Python.", - Py_TYPE(result)->tp_name)) { - Py_DECREF(result); - return NULL; - } - return result; - } -#endif - PyErr_Format(PyExc_TypeError, - "__%.4s__ returned non-%.4s (type %.200s)", - type_name, type_name, Py_TYPE(result)->tp_name); - Py_DECREF(result); - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { -#if CYTHON_USE_TYPE_SLOTS - PyNumberMethods *m; -#endif - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x) || PyLong_Check(x))) -#else - if (likely(PyLong_Check(x))) -#endif - return __Pyx_NewRef(x); -#if CYTHON_USE_TYPE_SLOTS - m = Py_TYPE(x)->tp_as_number; - #if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; - res = m->nb_int(x); - } - else if (m && m->nb_long) { - name = "long"; - res = m->nb_long(x); - } - #else - if (likely(m && m->nb_int)) { - name = "int"; - res = m->nb_int(x); - } - #endif -#else - if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { - res = PyNumber_Int(x); - } -#endif - if (likely(res)) { -#if PY_MAJOR_VERSION < 3 - if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { -#else - if (unlikely(!PyLong_CheckExact(res))) { -#endif - return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject *x; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(b))) { - if (sizeof(Py_ssize_t) >= sizeof(long)) - return PyInt_AS_LONG(b); - else - return PyInt_AsSsize_t(b); - } -#endif - if (likely(PyLong_CheckExact(b))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)b)->ob_digit; - const Py_ssize_t size = Py_SIZE(b); - if (likely(__Pyx_sst_abs(size) <= 1)) { - ival = likely(size) ? digits[0] : 0; - if (size == -1) ival = -ival; - return ival; - } else { - switch (size) { - case 2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - } - } - #endif - return PyLong_AsSsize_t(b); - } - x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { - return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); -} -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { - return PyInt_FromSize_t(ival); -} - - -#endif /* Py_PYTHON_H */ diff --git a/pylibjpeg/_libjpeg.pyx b/pylibjpeg/_libjpeg.pyx deleted file mode 100644 index d3fa11c..0000000 --- a/pylibjpeg/_libjpeg.pyx +++ /dev/null @@ -1,160 +0,0 @@ -# cython: language_level=3 -# distutils: language=c++ - -from math import ceil - -from libcpp cimport bool -from libcpp.string cimport string - -import numpy as np -cimport numpy as np - - -cdef extern from "decode.hpp": - cdef string Decode( - char *inArray, - char *outArray, - int inLength, - int outLength, - int colourspace, - ) - - cdef struct JPEGParameters: - int marker - long columns - long rows - int samples_per_pixel - char bits_per_sample - - cdef string GetJPEGParameters( - char *inArray, - int inLength, - JPEGParameters *param, - ) - - -def decode(np.ndarray[np.uint8_t, ndim=1] input_buffer, colourspace): - """Return the decoded JPEG data from `input_buffer`. - - Parameters - ---------- - input_buffer : numpy.ndarray - A 1D array of ``np.uint8`` containing the raw encoded JPEG image. - colourspace : int - | ``0`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_NONE`` - | ``1`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_YCBCR`` - | ``2`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_LSRCT`` - | ``2`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_RCT`` - | ``3`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_FREEFORM`` - - Returns - ------- - bytes - The status and any error message of the decoding operation. - numpy.ndarray or None - A 1D array of ``np.uint8`` containing the decoded image data. Returns - ``None`` if the decode fails. - dict - A :class:`dict` containing the image parameters. - """ - # Get the image parameters - status, param = get_parameters(input_buffer) - - # Pointer to first element in input array - cdef char *pInput = np.PyArray_DATA(input_buffer) - - # Create array for output and get pointer to first element - bpp = ceil(param['bits_per_sample'] / 8) - nr_bytes = ( - param['rows'] * param['columns'] * param['samples_per_pixel'] * bpp - ) - output_buffer = np.zeros(nr_bytes, dtype=np.uint8) - cdef char *pOutput = np.PyArray_DATA(output_buffer) - - # Decode the data - output is written to output_buffer - status = Decode( - pInput, - pOutput, - input_buffer.shape[0], - output_buffer.shape[0], - colourspace - ) - - return status, output_buffer, param - - -def get_parameters(np.ndarray[np.uint8_t, ndim=1] input_buffer): - """Return a :class:`dict` containing the JPEG image parameters. - - Parameters - ---------- - input_buffer : numpy.ndarray - A 1D array of ``np.uint8`` containing the encoded JPEG image. - - Returns - ------- - dict - A :class:`dict` containing the JPEG image parameters. - """ - cdef JPEGParameters param - param.columns = 0 - param.rows = 0 - param.samples_per_pixel = 0 - param.bits_per_sample = 0 - - # Pointer to the JPEGParameters object - cdef JPEGParameters *pParam = ¶m - - # Pointer to first element in input array - cdef char *pInput = np.PyArray_DATA(input_buffer) - - # Decode the data - output is written to output_buffer - status = GetJPEGParameters( - pInput, - input_buffer.shape[0], - pParam - ) - - parameters = { - 'rows' : param.rows, - 'columns' : param.columns, - 'samples_per_pixel' : param.samples_per_pixel, - 'bits_per_sample' : param.bits_per_sample, - } - - return status, parameters - - -cdef extern from "cmd/reconstruct.hpp": - cdef void Reconstruct( - const char *inArray, - const char *outArray, - int colortrafo, - const char *alpha, - bool upsample, - ) - - -def reconstruct(fin, fout, colourspace, falpha, upsample): - """Decode the JPEG file in `fin` and write it to `fout` as PNM. - - Parameters - ---------- - fin : bytes - The path to the JPEG file to be decoded. - fout : bytes - The path to the decoded PNM file. - colourspace : int - The colourspace transform to apply. - falpha : bytes or None - The path where any decoded alpha channel data will be written, - otherwise ``None`` to not write alpha channel data. Equivalent to the - ``-al file`` flag. - upsample : bool - ``True`` to disable automatic upsampling, equivalent to the ``-U`` - flag. - """ - if falpha is None: - Reconstruct(fin, fout, colourspace, NULL, upsample) - else: - Reconstruct(fin, fout, colourspace, falpha, upsample) diff --git a/pylibjpeg/libjpeg.py b/pylibjpeg/libjpeg.py deleted file mode 100755 index 62201b9..0000000 --- a/pylibjpeg/libjpeg.py +++ /dev/null @@ -1,246 +0,0 @@ - -from math import ceil -import pathlib -import warnings - -import numpy as np - -import _libjpeg - - -LIBJPEG_ERROR_CODES = { - -1024 : "A parameter for a function was out of range", - -1025 : "Stream run out of data", - -1026 : "A code block run out of data", - -1027 : "Tried to perform an unputc or or an unget on an empty stream", - -1028 : "Some parameter run out of range", - -1029 : "The requested operation does not apply", - -1030 : "Tried to create an already existing object", - -1031 : "Tried to access a non-existing object", - -1032 : "A non-optional parameter was left out", - -1033 : "Forgot to delay a 0xFF", - -1034 : ( - "Internal error: the requested operation is not available" - ), - -1035 : ( - "Internal error: an item computed on a former pass does not " - "coincide with the same item on a later pass" - ), - -1036 : "The stream passed in is no valid jpeg stream", - -1037 : ( - "A unique marker turned up more than once. The input stream is " - "most likely corrupt" - ), - -1038 : "A misplaced marker segment was found", - -1040 : ( - "The specified parameters are valid, but are not supported by " - "the selected profile. Either use a higher profile, or use " - "simpler parameters (encoder only). " - ), - -1041 : ( - "Internal error: the worker thread that was currently active had " - "to terminate unexpectedly" - ), - -1042 : ( - "The encoder tried to emit a symbol for which no Huffman code " - "was defined. This happens if the standard Huffman table is used " - "for an alphabet for which it was not defined. The reaction " - "to this exception should be to create a custom huffman table " - "instead" - ), - -2046 : "Failed to construct the JPEG object", -} - - -def add_handler(): - """Add the pixel data handler to *pydicom*. - - Raises - ------ - ImportError - If *pydicom* is not available. - """ - # Avoid circular import during unit testing - import pydicom.config - from . import libjpeg_handler - - if libjpeg_handler not in pydicom.config.pixel_data_handlers: - pydicom.config.pixel_data_handlers.append(libjpeg_handler) - - -def decode(arr, colourspace='YBR_FULL', reshape=True): - """Return the decoded JPEG data from `arr` as a :class:`numpy.ndarray`. - - Parameters - ---------- - arr : numpy.ndarray or bytes - A 1D array of ``np.uint8``, or a Python :class:`bytes` object - containing the encoded JPEG image. - colourspace : str, optional - One of ``'MONOCHROME1'``, ``'MONOCHROME2'``, ``'RGB'``, ``'YBR_FULL'``, - ``'YBR_FULL_422'``. - reshape : bool, optional - Reshape and review the output array so it matches the image data - (default), otherwise return a 1D array of ``np.uint8``. - - Returns - ------- - numpy.ndarray - An array of containing the decoded image data. - - Raises - ------ - RuntimeError - If the decoding failed. - """ - colours = { - 'MONOCHROME1': 0, - 'MONOCHROME2' : 0, - 'RGB' : 1, - 'YBR_FULL' : 0, - 'YBR_FULL_422' : 0, - -1 : -1, # For unit testing only - } - - try: - transform = colours[colourspace] - except KeyError: - warnings.warn( - "Unsupported colour space '{}', no colour transform will " - "be applied".format(colourspace) - ) - transform = 0 - - if isinstance(arr, bytes): - arr = np.frombuffer(arr, 'uint8') - - status, out, params = _libjpeg.decode(arr, transform) - status = status.decode("utf-8") - code, msg = status.split("::::") - code = int(code) - - if code == 0 and reshape is True: - bpp = ceil(params['bits_per_sample'] / 8) - if bpp == 2: - out = out.view('uint16') - - shape = [params['rows'], params['columns']] - if params['samples_per_pixel'] > 1: - shape.append(params['samples_per_pixel']) - - return out.reshape(*shape) - elif code == 0 and reshape is False: - return out - - if code in LIBJPEG_ERROR_CODES: - raise RuntimeError( - "libjpeg error code '{}' returned from Decode(): {} - {}" - .format(code, LIBJPEG_ERROR_CODES[code], msg) - ) - - raise RuntimeError( - "Unknown error code '{}' returned from Decode(): {}" - .format(code, msg) - ) - - -def get_parameters(arr): - """Return a :class:`dict` containing JPEG image parameters. - - Parameters - ---------- - arr : numpy.ndarray or bytes - A 1D array of ``np.uint8``, or a Python :class:`bytes` object - containing the raw encoded JPEG image. - - Returns - ------- - dict - A :class:`dict` containing JPEG image parameters with keys including - ``'rows'``, ``'columns'``, ``'samples_per_pixel'`` and - ``'bits_per_sample'``. - - Raises - ------ - RuntimeError - If reading the encoded JPEG data failed. - """ - if isinstance(arr, bytes): - arr = np.frombuffer(arr, 'uint8') - - status, params = _libjpeg.get_parameters(arr) - status = status.decode("utf-8") - code, msg = status.split("::::") - code = int(code) - - if code == 0: - return params - - if code in LIBJPEG_ERROR_CODES: - raise RuntimeError( - "libjpeg error code '{}' returned from GetJPEGParameters(): " - "{} - {}".format(code, LIBJPEG_ERROR_CODES[code], msg) - ) - - raise RuntimeError( - "Unknown error code '{}' returned from GetJPEGParameters(): {}" - .format(status, msg) - ) - - -def reconstruct(fin, fout, colourspace=1, falpha=None, upsample=True): - """Simple wrapper for the libjpeg ``cmd/reconstruct::Reconstruct()`` - function. - - Parameters - ---------- - fin : bytes - The path to the JPEG file to be decoded. - fout : bytes - The path to the decoded PPM or PGM (if `falpha` is ``True``) file(s). - colourspace : int, optional - The colourspace transform to apply. - | ``0`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_NONE`` (``-c`` flag) - | ``1`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_YCBCR`` (default) - | ``2`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_LSRCT`` (``-cls`` flag) - | ``2`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_RCT`` - | ``3`` : ``JPGFLAG_MATRIX_COLORTRANSFORMATION_FREEFORM`` - See `here`_ - for more information. - falpha : bytes, optional - The path where any decoded alpha channel data will be written (as a - PGM file), otherwise ``None`` (default) to not write alpha channel - data. Equivalent to the ``-al file`` flag. - upsample : bool, optional - ``True`` (default) to disable automatic upsampling, equivalent to - the ``-U`` flag. - """ - if isinstance(fin, (str, pathlib.Path)): - fin = str(fin) - fin = bytes(fin, 'utf-8') - - if isinstance(fout, (str, pathlib.Path)): - fout = str(fout) - fout = bytes(fout, 'utf-8') - - if falpha and isinstance(falpha, (str, pathlib.Path)): - falpha = str(falpha) - falpha = bytes(falpha, 'utf-8') - - _libjpeg.reconstruct(fin, fout, colourspace, falpha, upsample) - - -def remove_handler(): - """Remove the pixel data handler from *pydicom*. - - Raises - ------ - ImportError - If *pydicom* is not available. - """ - # Avoid circular import during unit testing - import pydicom.config - from . import libjpeg_handler - - if libjpeg_handler in pydicom.config.pixel_data_handlers: - pydicom.config.pixel_data_handlers.remove(libjpeg_handler) diff --git a/pylibjpeg/plugins.py b/pylibjpeg/plugins.py new file mode 100644 index 0000000..ceea5b2 --- /dev/null +++ b/pylibjpeg/plugins.py @@ -0,0 +1,78 @@ +"""Utilities for managing plugins.""" + + +class PluginManager(object): + """The plugin manager.""" + def __init__(self, plugins): + # dict {str name: module object, ...} + self._plugins = {} + for pkg_name in plugins: + plugin = self.import_package(pkg_name) + if plugin and plugin not in self._plugins: + self._plugins[pkg_name] = plugin + + def add_plugin(self, plugin): + """Add a plugin.""" + raise NotImplementedError() + + def import_package(pkg): + """Return the plugin for a package or ``None`` if not importable.""" + raise NotImplementedError() + + @property + def plugins(self): + """Return a list of available and enabled plugins.""" + out = {} + for (pkg_name, plugin) in self._plugins: + if plugin.is_available and plugin.enabled: + out[pkg_name] = plugin + + return out + + def remove_plugin(self, plugin): + """Remove a plugin.""" + raise NotImplementedError() + + @property + def transfer_syntaxes(self): + """Return a list of DICOM Transfer Syntax UIDs supported by the + plugins. + + """ + uids = [] + for (pkg_name, plugin) in self.plugins: + uids += plugin.transfer_syntaxes + + return list(set(uids)) + + +class Plugin(object): + """Base class for plugins.""" + def __init__(self, meta, enabled=True): + """Create a new Plugin object.""" + self.meta = meta + self._enabled = enabled + self._uids = [] + self._is_available = True + + @property + def enabled(self): + """Returns ``True`` if the plugin is enabled, ``False`` otherwise.""" + return self._enabled + + @enabled.setter + def enabled(self, is_enabled): + """Enable or disable the plugin.""" + self._enabled = bool(is_enabled) + + @property + def is_available(self): + """Return ``True`` if the plugin is available for use, ``False`` + otherwise. + """ + return self._is_available + + @property + def transfer_syntaxes(self): + """Return a list of supported DICOM Transfer Syntax UIDs.""" + return self._uids diff --git a/pylibjpeg/pydicom/__init__.py b/pylibjpeg/pydicom/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pylibjpeg/libjpeg_handler.py b/pylibjpeg/pydicom/pixel_data_handler.py similarity index 87% rename from pylibjpeg/libjpeg_handler.py rename to pylibjpeg/pydicom/pixel_data_handler.py index 29b2d4d..8722f6d 100644 --- a/pylibjpeg/libjpeg_handler.py +++ b/pylibjpeg/pydicom/pixel_data_handler.py @@ -1,16 +1,6 @@ -"""Use the `pylibjpeg `_ package +"""Use the `pylibjpeg `_ package to convert supported pixel data to a :class:`numpy.ndarray`. -**Supported transfer syntaxes** - -* 1.2.840.10008.1.2.4.50 : JPEG Baseline (Process 1) -* 1.2.840.10008.1.2.4.51 : JPEG Extended (Process 2 and 4) -* 1.2.840.10008.1.2.4.57 : JPEG Lossless, Non-Hierarchical (Process 14) -* 1.2.840.10008.1.2.4.70 : JPEG Lossless, Non-Hierarchical, First-Order - Prediction (Process 14 [Selection Value 1]) -* 1.2.840.10008.1.2.4.80 : JPEG-LS Lossless Image Compression -* 1.2.840.10008.1.2.4.81 : JPEG-LS Lossy (Near-Lossless) Image Compression - **Supported data** The numpy handler supports the conversion of data in the (7FE0,0010) @@ -49,32 +39,15 @@ import numpy as np from pydicom.encaps import generate_pixel_data_frame from pydicom.pixel_data_handlers.util import pixel_dtype, get_expected_length -from pydicom.uid import ( - JPEGBaseline, - JPEGExtended, - JPEGLosslessP14, - JPEGLossless, - JPEGLSLossless, - JPEGLSLossy, -) - -from pylibjpeg.libjpeg import decode HANDLER_NAME = 'pylibjpeg' - +# Set this dynamically based on unavailable plugins DEPENDENCIES = { 'numpy': ('http://www.numpy.org/', 'NumPy'), } - -SUPPORTED_TRANSFER_SYNTAXES = [ - JPEGBaseline, - JPEGExtended, - JPEGLosslessP14, - JPEGLossless, - JPEGLSLossless, - JPEGLSLossy, -] +SUPPORTED_TRANSFER_SYNTAXES = [] +_DECODERS = {} def is_available(): diff --git a/pylibjpeg/src/libjpeg b/pylibjpeg/src/libjpeg deleted file mode 160000 index 87636f3..0000000 --- a/pylibjpeg/src/libjpeg +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 87636f3b26b41b85b2fb7355c589a8c456ef808c diff --git a/pylibjpeg/src/pylibjpeg/decode.cpp b/pylibjpeg/src/pylibjpeg/decode.cpp deleted file mode 100644 index 6b90d14..0000000 --- a/pylibjpeg/src/pylibjpeg/decode.cpp +++ /dev/null @@ -1,333 +0,0 @@ - -// Includes -#include "std/stdio.hpp" -#include "std/string.hpp" -#include - -#include "decode.hpp" -#include "streamhook.hpp" - -#include "../libjpeg/cmd/reconstruct.hpp" -#include "../libjpeg/cmd/bitmaphook.hpp" -#include "../libjpeg/tools/environment.hpp" -#include "../libjpeg/tools/traits.hpp" -#include "../libjpeg/interface/types.hpp" -#include "../libjpeg/interface/hooks.hpp" -#include "../libjpeg/interface/tagitem.hpp" -#include "../libjpeg/interface/parameters.hpp" -#include "../libjpeg/interface/jpeg.hpp" - - -std::string Decode(char *inArray, char *outArray, int inLength, int outLength, int colourTransform) -{ - /* - - Parameters - ---------- - char *inArray - Pointer to the first element of a numpy.ndarray containing the JPEG - data to be decompressed. - char *outArray - Pointer to the first element of a numpy.ndarray where the decompressed - JPEG data should be written. - int inLength - Length of the input array - int outLength - Expected length of the output array - int colourTransform - JPGFLAG_MATRIX_COLORTRANSFORMATION_NONE 0 - JPGFLAG_MATRIX_COLORTRANSFORMATION_YCBCR 1 - JPGFLAG_MATRIX_COLORTRANSFORMATION_LSRCT 2 - JPGFLAG_MATRIX_COLORTRANSFORMATION_RCT 2 - JPGFLAG_MATRIX_COLORTRANSFORMATION_FREEFORM 3 - - */ - // Check valid value - if (colourTransform < 0 || colourTransform > 3) { - return "-8194::::Invalid colourTransform value"; - } - int colortrafo = colourTransform; - // No alpha channel - const char *alpha = NULL; - bool upsample = true; - - // Create a struct with for the input data so we can track its info - StreamData in = { - inArray, 0, inLength, &inArray[0], &inArray[inLength - 1] - }; - StreamData out = { - outArray, 0, outLength, &outArray[0], &outArray[outLength -1] - }; - - // Our custom hook handler - struct JPG_Hook streamhook(IStreamHook, &in); - // JPEG representation from main library interface - class JPEG *jpeg = JPEG::Construct(NULL); - - if (jpeg) { - int ok = 1; - - struct JPG_TagItem tags[] = { - JPG_PointerTag(JPGTAG_HOOK_IOHOOK, &streamhook), - JPG_PointerTag(JPGTAG_HOOK_IOSTREAM, in.pData), - JPG_EndTag - }; - - // Reads the data and stores various parameters in a struct - if (ok && jpeg->Read(tags)) { - UBYTE subx[4], suby[4]; - struct JPG_TagItem atags[] = { - JPG_ValueTag(JPGTAG_IMAGE_PRECISION, 0), - JPG_ValueTag(JPGTAG_IMAGE_IS_FLOAT, false), - JPG_ValueTag(JPGTAG_IMAGE_OUTPUT_CONVERSION, true), - JPG_EndTag - }; - struct JPG_TagItem itags[] = { - JPG_ValueTag(JPGTAG_IMAGE_WIDTH, 0), - JPG_ValueTag(JPGTAG_IMAGE_HEIGHT, 0), - JPG_ValueTag(JPGTAG_IMAGE_DEPTH, 0), - JPG_ValueTag(JPGTAG_IMAGE_PRECISION, 0), - JPG_ValueTag(JPGTAG_IMAGE_IS_FLOAT, false), - JPG_ValueTag(JPGTAG_IMAGE_OUTPUT_CONVERSION, true), - JPG_ValueTag(JPGTAG_ALPHA_MODE, JPGFLAG_ALPHA_OPAQUE), - JPG_PointerTag(JPGTAG_ALPHA_TAGLIST, atags), - JPG_PointerTag(JPGTAG_IMAGE_SUBX, subx), - JPG_PointerTag(JPGTAG_IMAGE_SUBY, suby), - JPG_ValueTag(JPGTAG_IMAGE_SUBLENGTH, 4), - JPG_EndTag - }; - - if (jpeg->GetInformation(itags)) { - ULONG width = itags->GetTagData(JPGTAG_IMAGE_WIDTH); - ULONG height = itags->GetTagData(JPGTAG_IMAGE_HEIGHT); - UBYTE depth = itags->GetTagData(JPGTAG_IMAGE_DEPTH); - UBYTE prec = itags->GetTagData(JPGTAG_IMAGE_PRECISION); - UBYTE aprec = 0; - bool pfm = itags->GetTagData(JPGTAG_IMAGE_IS_FLOAT)?true:false; - bool convert = itags->GetTagData(JPGTAG_IMAGE_OUTPUT_CONVERSION)?true:false; - bool doalpha = itags->GetTagData(JPGTAG_ALPHA_MODE, JPGFLAG_ALPHA_OPAQUE)?true:false; - bool apfm = false; - bool aconvert= false; - - if (alpha && doalpha) { - aprec = atags->GetTagData(JPGTAG_IMAGE_PRECISION); - apfm = atags->GetTagData(JPGTAG_IMAGE_IS_FLOAT)?true:false; - aconvert = atags->GetTagData(JPGTAG_IMAGE_OUTPUT_CONVERSION)?true:false; - } else { - doalpha = false; // alpha channel is ignored. - } - - UBYTE bytesperpixel = sizeof(UBYTE); - UBYTE pixeltype = CTYP_UBYTE; - if (prec > 8) { - bytesperpixel = sizeof(UWORD); - pixeltype = CTYP_UWORD; - } - if (pfm && convert == false) { - bytesperpixel = sizeof(FLOAT); - pixeltype = CTYP_FLOAT; - } - - // Make sure output array is the correct size - if (width * height * depth * bytesperpixel != outLength) { - return "-8195::::Invalid output array size"; - } - - UBYTE alphabytesperpixel = sizeof(UBYTE); - UBYTE alphapixeltype = CTYP_UBYTE; - if (aprec > 8) { - alphabytesperpixel = sizeof(UWORD); - alphapixeltype = CTYP_UWORD; - } - if (apfm && aconvert == false) { - alphabytesperpixel = sizeof(FLOAT); - alphapixeltype = CTYP_FLOAT; - } - - // Alpha channel memory allocation - UBYTE *amem = NULL; - // Output data memory allocation - UBYTE *mem = (UBYTE *)malloc(width * 8 * depth * bytesperpixel); - if (doalpha) - // only one component! - amem = (UBYTE *)malloc(width * 8 * alphabytesperpixel); - - if (mem) { - // I think the struct here is used to pass parameters to - // the writer hook - BitmapHook - // We could probably vastly simplify it? - struct StreamMemory omm; - omm.omm_pMemPtr = mem; - omm.omm_pAlphaPtr = amem; - omm.omm_ulWidth = width; - omm.omm_ulHeight = height; - omm.omm_usDepth = depth; - omm.omm_ucPixelType = pixeltype; - omm.omm_ucAlphaType = alphapixeltype; - omm.omm_pTarget = &out; - omm.omm_pAlphaTarget = (doalpha)?(fopen(alpha, "wb")):NULL; - omm.omm_pSource = NULL; - omm.omm_pAlphaSource = NULL; - omm.omm_pLDRSource = NULL; - omm.omm_bFloat = pfm; - omm.omm_bAlphaFloat = apfm; - omm.omm_bBigEndian = true; - omm.omm_bAlphaBigEndian = true; - omm.omm_bNoOutputConversion = !convert; - omm.omm_bNoAlphaOutputConversion = !aconvert; - omm.omm_bUpsampling = upsample; - - // If upsampling is enabled, the subsampling factors are - // all implicitly 1. - if (upsample) { - memset(subx, 1, sizeof(subx)); - memset(suby, 1, sizeof(suby)); - } - - struct JPG_Hook outhook(OStreamHook, &omm); - // TODO: implement writing alpha to numpy - // Not required for DICOM - struct JPG_Hook alphahook(AlphaHook, &omm); - - // Write the data - // Just as a demo, run a stripe-based - // reconstruction. - ULONG y = 0; - ULONG lastline; - struct JPG_TagItem tags[] = { - JPG_PointerTag(JPGTAG_BIH_HOOK, &outhook), - JPG_PointerTag(JPGTAG_BIH_ALPHAHOOK, &alphahook), - JPG_ValueTag(JPGTAG_DECODER_MINY, y), - JPG_ValueTag(JPGTAG_DECODER_MAXY, y + 7), - JPG_ValueTag(JPGTAG_DECODER_UPSAMPLE, upsample), - JPG_ValueTag(JPGTAG_MATRIX_LTRAFO, colortrafo), - JPG_EndTag - }; - - // Writes the image data to numpy array - // - // Reconstruct now the buffered image, line by - // line. Could also reconstruct the image as a - // whole. What we have here is just a demo - // that is not necessarily the most efficient - // way of handling images. - do { - lastline = height; - if (lastline > y + 8) - lastline = y + 8; - - tags[2].ti_Data.ti_lData = y; - tags[3].ti_Data.ti_lData = lastline - 1; - // I think this is the decode/writer line - ok = jpeg->DisplayRectangle(tags); - y = lastline; - } while(y < height && ok); - - if (omm.omm_pAlphaTarget) - fclose(omm.omm_pAlphaTarget); - - if (amem) - free(amem); - - free(mem); - } else { - // Unable to allocate memory to buffer the image - return "-8192::::Unable to allocate memory to buffer the image"; - } - } else ok = 0; - } else ok = 0; - - if (!ok) { - const char *error; - int code = jpeg->LastError(error); - std::ostringstream status; - status << code << "::::" << error; - return status.str(); - } - JPEG::Destruct(jpeg); - } else { - // Failed to construct the JPEG object - return "-8193::::Failed to construct the JPEG object"; - } - // Success - return "0::::"; -} - - -std::string GetJPEGParameters(char *inArray, int inLength, struct JPEGParameters *param) -{ - /* - - Parameters - ---------- - char *inArray - Pointer to the first element of a numpy.ndarray containing the JPEG - data to be read. - int inLength - Length of the input array - - */ - - // Create a struct for the input - StreamData in = { - inArray, 0, inLength, &inArray[0], &inArray[inLength - 1] - }; - - // Our custom hook handler - struct JPG_Hook streamhook(IStreamHook, &in); - // JPEG representation from main library interface - class JPEG *jpeg = JPEG::Construct(NULL); - - if (jpeg) { - int ok = 1; - - struct JPG_TagItem tags[] = { - JPG_PointerTag(JPGTAG_HOOK_IOHOOK, &streamhook), - JPG_PointerTag(JPGTAG_HOOK_IOSTREAM, in.pData), - JPG_EndTag, - }; - - // Reads the data and stores various parameters in a struct - // Peek marker is useless, returns 0 for most markers - if (ok && jpeg->Read(tags)) { - UBYTE subx[4], suby[4]; - struct JPG_TagItem itags[] = { - JPG_ValueTag(JPGTAG_IMAGE_WIDTH, 0), - JPG_ValueTag(JPGTAG_IMAGE_HEIGHT, 0), - JPG_ValueTag(JPGTAG_IMAGE_DEPTH, 0), - JPG_ValueTag(JPGTAG_IMAGE_PRECISION, 0), - JPG_ValueTag(JPGTAG_IMAGE_IS_FLOAT, false), - JPG_PointerTag(JPGTAG_IMAGE_SUBX, subx), - JPG_PointerTag(JPGTAG_IMAGE_SUBY, suby), - JPG_ValueTag(JPGTAG_IMAGE_SUBLENGTH, 4), - JPG_EndTag - }; - - if (jpeg->GetInformation(itags)) { - ULONG width = itags->GetTagData(JPGTAG_IMAGE_WIDTH); - ULONG height = itags->GetTagData(JPGTAG_IMAGE_HEIGHT); - UBYTE depth = itags->GetTagData(JPGTAG_IMAGE_DEPTH); - UBYTE prec = itags->GetTagData(JPGTAG_IMAGE_PRECISION); - - param->columns = width; - param->rows = height; - param->samples_per_pixel = depth; - param->bits_per_sample = prec; - } else ok = 0; - } else ok = 0; - - if (!ok) { - const char *error; - int code = jpeg->LastError(error); - std::ostringstream status; - status << code << "::::" << error; - return status.str(); - } - JPEG::Destruct(jpeg); - } else { - // Failed to construct the JPEG object - return "-8193::::Failed to construct the JPEG object"; - } - // Success - return "0::::"; -} diff --git a/pylibjpeg/src/pylibjpeg/decode.hpp b/pylibjpeg/src/pylibjpeg/decode.hpp deleted file mode 100644 index 936a0aa..0000000 --- a/pylibjpeg/src/pylibjpeg/decode.hpp +++ /dev/null @@ -1,44 +0,0 @@ - -#include -#include -#include "../libjpeg/interface/types.hpp" - -#ifndef DECODE_HPP -#define DECODE_HPP - - // Prototypes - // Decode the encoded JPEG file in `inArray` to `outArray` - extern std::string Decode( - char *inArray, - char *outArray, - int inLength, - int outLength, - int colourTransform - ); - - // Return the parameters of the encoded JPEG file in `inArray` - extern std::string GetJPEGParameters( - char *inArray, int inLength, struct JPEGParameters *param - ); - - struct StreamData { - // Pointer to the current offset of the raw encoded JPEG byte data - char *pData; - // The current offset, starts at 0 - int position; - // The total length of the byte data - int length; - // Pointer to the beginning of the byte data - char *pStart; - // Pointer to the end of the byte data - char *pEnd; - }; - - struct JPEGParameters { - ULONG columns; // width in pixels - ULONG rows; // height in pixels - UWORD samples_per_pixel; // number of components - UBYTE bits_per_sample; // bit depth of input - }; - -#endif diff --git a/pylibjpeg/src/pylibjpeg/streamhook.cpp b/pylibjpeg/src/pylibjpeg/streamhook.cpp deleted file mode 100644 index f8fb0aa..0000000 --- a/pylibjpeg/src/pylibjpeg/streamhook.cpp +++ /dev/null @@ -1,355 +0,0 @@ -// Includes -#include -#include "streamhook.hpp" -#include "decode.hpp" -#include "utils.hpp" -#include "../libjpeg/interface/hooks.hpp" -#include "../libjpeg/interface/tagitem.hpp" -#include "../libjpeg/interface/parameters.hpp" -#include "../libjpeg/cmd/iohelpers.hpp" -#include "../libjpeg/tools/traits.hpp" -#include "std/stdio.hpp" -#include "std/stdlib.hpp" -#include "std/string.hpp" -#include "std/assert.hpp" - - -// The input stream hook function -JPG_LONG IStreamHook(struct JPG_Hook *hook, struct JPG_TagItem *tags) -{ - // Pointer to the input struct which is stored by the hook - StreamData *in = (StreamData *)(hook->hk_pData); - // Pointer to current pointer of the input buffer - // The pointer itself gets updated so no guarantee where it is - char *data = (char *)(in->pData); - - switch(tags->GetTagData(JPGTAG_FIO_ACTION)) { - case JPGFLAG_ACTION_READ: - { - UBYTE *buffer = (UBYTE *)tags->GetTagPtr(JPGTAG_FIO_BUFFER); - ULONG size = (ULONG )tags->GetTagData(JPGTAG_FIO_SIZE); - - // Number of bytes read this session - ULONG bytes_read = 0; - // Usually reads in 2048 bytes per run - for (ULONG ii = 1; ii <= size; ii++) { - // Check that we haven't gone beyond the buffer - if (in->position >= in->length) { - break; - } - *buffer = *data; - in->position += 1; - bytes_read += 1; - - buffer++; - data++; - } - // Update the stored pointer - in->pData = data; - - return bytes_read; - } - case JPGFLAG_ACTION_WRITE: - { - UBYTE *buffer = (UBYTE *)tags->GetTagPtr(JPGTAG_FIO_BUFFER); - ULONG size = (ULONG )tags->GetTagData(JPGTAG_FIO_SIZE); - - // We want to raise an error so writing can be implemented - return -1; - } - case JPGFLAG_ACTION_SEEK: - { - LONG mode = tags->GetTagData(JPGTAG_FIO_SEEKMODE); - LONG offset = tags->GetTagData(JPGTAG_FIO_OFFSET); - - // We want to raise an error here seek can be implemented - switch(mode) { - case JPGFLAG_OFFSET_CURRENT: - return -1; - case JPGFLAG_OFFSET_BEGINNING: - return -1; - case JPGFLAG_OFFSET_END: - return -1; - } - return -1; - } - case JPGFLAG_ACTION_QUERY: - { - return 0; - } - } - return -1; -} - - -// The output stream hook function -JPG_LONG OStreamHook(struct JPG_Hook *hook, struct JPG_TagItem *tags) -{ - static ULONG OpenComponents = 0; - struct StreamMemory *omm = (struct StreamMemory *)(hook->hk_pData); - struct StreamData *out = (struct StreamData *)(omm->omm_pTarget); - // Pointer to the output numpy array, currently at offset out->position - char *oArray = (char *)(out->pData); - - UWORD comp = tags->GetTagData(JPGTAG_BIO_COMPONENT); - ULONG miny = tags->GetTagData((omm->omm_bUpsampling)?(JPGTAG_BIO_MINY):(JPGTAG_BIO_PIXEL_MINY)); - ULONG maxy = tags->GetTagData((omm->omm_bUpsampling)?(JPGTAG_BIO_MAXY):(JPGTAG_BIO_PIXEL_MAXY)); - ULONG width = 1 + (tags->GetTagData((omm->omm_bUpsampling)?(JPGTAG_BIO_MAXX):(JPGTAG_BIO_PIXEL_MAXX))); - - assert(comp < omm->omm_usDepth); - assert(maxy - miny < omm->omm_ulHeight); - - switch(tags->GetTagData(JPGTAG_BIO_ACTION)) { - case JPGFLAG_BIO_REQUEST: - { - if (omm->omm_ucPixelType == CTYP_UBYTE) { - UBYTE *mem = (UBYTE *)(omm->omm_pMemPtr); - mem += comp; - mem -= miny * omm->omm_usDepth * width; - tags->SetTagPtr(JPGTAG_BIO_MEMORY ,mem); - tags->SetTagData(JPGTAG_BIO_WIDTH ,width); - tags->SetTagData(JPGTAG_BIO_HEIGHT ,8 + miny); - tags->SetTagData(JPGTAG_BIO_BYTESPERROW ,omm->omm_usDepth * width * sizeof(UBYTE)); - tags->SetTagData(JPGTAG_BIO_BYTESPERPIXEL,omm->omm_usDepth * sizeof(UBYTE)); - tags->SetTagData(JPGTAG_BIO_PIXELTYPE ,omm->omm_ucPixelType); - } else if (omm->omm_ucPixelType == CTYP_UWORD) { - UWORD *mem = (UWORD *)(omm->omm_pMemPtr); - mem += comp; - mem -= miny * omm->omm_usDepth * width; - tags->SetTagPtr(JPGTAG_BIO_MEMORY ,mem); - tags->SetTagData(JPGTAG_BIO_WIDTH ,width); - tags->SetTagData(JPGTAG_BIO_HEIGHT ,8 + miny); - tags->SetTagData(JPGTAG_BIO_BYTESPERROW ,omm->omm_usDepth * width * sizeof(UWORD)); - tags->SetTagData(JPGTAG_BIO_BYTESPERPIXEL,omm->omm_usDepth * sizeof(UWORD)); - tags->SetTagData(JPGTAG_BIO_PIXELTYPE ,omm->omm_ucPixelType); - } else if (omm->omm_ucPixelType == CTYP_FLOAT) { - FLOAT *mem = (FLOAT *)(omm->omm_pMemPtr); - mem += comp; - mem -= miny * omm->omm_usDepth * width; - tags->SetTagPtr(JPGTAG_BIO_MEMORY ,mem); - tags->SetTagData(JPGTAG_BIO_WIDTH ,width); - tags->SetTagData(JPGTAG_BIO_HEIGHT ,8 + miny); - tags->SetTagData(JPGTAG_BIO_BYTESPERROW ,omm->omm_usDepth * width * sizeof(FLOAT)); - tags->SetTagData(JPGTAG_BIO_BYTESPERPIXEL,omm->omm_usDepth * sizeof(FLOAT)); - tags->SetTagData(JPGTAG_BIO_PIXELTYPE ,omm->omm_ucPixelType); - } else { - tags->SetTagData(JPGTAG_BIO_PIXELTYPE ,0); - } - - // Read the source data. - if (comp == 0) { - ULONG height = maxy + 1 - miny; - // Since we are here indicating the size of the available data, - // clip to the eight lines available. - if (height > 8) - height = 8; - - if ( - omm->omm_ucPixelType == CTYP_UBYTE || - omm->omm_ucPixelType == CTYP_UWORD || - omm->omm_ucPixelType == CTYP_FLOAT - ) - { - if (omm->omm_pLDRSource && omm->omm_pLDRMemPtr) { - // A designated LDR source is available. Read from - // here rather than using our primitive tone mapper. - fread( - omm->omm_pLDRMemPtr, - sizeof(UBYTE), - width * height * omm->omm_usDepth, - omm->omm_pLDRSource - ); - } - - if (omm->omm_pSource) { - if (omm->omm_bFloat) { - if (omm->omm_bNoOutputConversion) { - ULONG count = width * height * omm->omm_usDepth; - FLOAT *data = (FLOAT *)omm->omm_pMemPtr; - UBYTE *ldr = (UBYTE *)omm->omm_pLDRMemPtr; - do { - double in = readFloat(omm->omm_pSource,omm->omm_bBigEndian); - UWORD half; - if (omm->omm_bClamp && in < 0.0) - in = 0.0; - - half = DoubleToHalf(in); - // Tone-map the input unless there is an LDR source. - if (omm->omm_pLDRMemPtr && omm->omm_pLDRSource == NULL) - *ldr = omm->omm_HDR2LDR[half]; - - *data = FLOAT(in); - data++,ldr++; - } while(--count); - } else { - ULONG count = width * height * omm->omm_usDepth; - UWORD *data = (UWORD *)omm->omm_pMemPtr; - UBYTE *ldr = (UBYTE *)omm->omm_pLDRMemPtr; - - do { - double in = readFloat(omm->omm_pSource, omm->omm_bBigEndian); - if (omm->omm_bClamp && in < 0.0) - in = 0.0; - - *data = DoubleToHalf(in); - // Tone-map the input unless there is an LDR source. - if (omm->omm_pLDRMemPtr && omm->omm_pLDRSource == NULL) { - if (in >= 0.0) { - *ldr = omm->omm_HDR2LDR[*data]; - } else { - *ldr = 0; - } - } - data++,ldr++; - } while(--count); - } - } else { - fread( - omm->omm_pMemPtr, - omm->omm_ucPixelType & CTYP_SIZE_MASK, - width * height * omm->omm_usDepth, - omm->omm_pSource - ); - - #ifdef JPG_LIL_ENDIAN - // On those bloddy little endian machines, an endian swap is necessary - // as PNM is big-endian. - if (omm->omm_ucPixelType == CTYP_UWORD) { - ULONG count = width * height * omm->omm_usDepth; - UWORD *data = (UWORD *)omm->omm_pMemPtr; - - do { - *data = (*data >> 8) | ((*data & 0xff) << 8); - data++; - } while(--count); - } - #endif - - // Construct the tone-mapped LDR version of the image - // if there is no designated LDR input. - if (omm->omm_pLDRMemPtr && omm->omm_pLDRSource == NULL) { - if (omm->omm_ucPixelType == CTYP_UWORD) { - ULONG count = width * height * omm->omm_usDepth; - UWORD *data = (UWORD *)omm->omm_pMemPtr; - UBYTE *ldr = (UBYTE *)omm->omm_pLDRMemPtr; - - do { - *ldr++ = omm->omm_HDR2LDR[*data++]; - } while(--count); - } else { // Huh, why tone mapping on 8 bit input? Ok, anyhow.... - ULONG count = width * height * omm->omm_usDepth; - UBYTE *data = (UBYTE *)omm->omm_pMemPtr; - UBYTE *ldr = (UBYTE *)omm->omm_pLDRMemPtr; - - do { - *ldr++ = omm->omm_HDR2LDR[*data++]; - } while(--count); - } - } - } - } - } - } - - assert((OpenComponents & (1UL << comp)) == 0); - OpenComponents |= 1UL << comp; - } - break; - case JPGFLAG_BIO_RELEASE: - { - // omm_ucPixelType: precision - // omm_usDepth: number of components - // omm_bFloat: input is floating point - assert(OpenComponents & (1UL << comp)); - if (comp == omm->omm_usDepth - 1) { - ULONG height = maxy + 1 - miny; - if ( - omm->omm_ucPixelType == CTYP_UBYTE || - omm->omm_ucPixelType == CTYP_UWORD || - omm->omm_ucPixelType == CTYP_FLOAT - ) - { - if (oArray) { - if (omm->omm_bFloat) { - // No floating point input allowed for DICOM - if (omm->omm_bNoOutputConversion) { - ULONG count = width * height; - FLOAT *data = (FLOAT *)omm->omm_pMemPtr; - double r = 0.0, g = 0.0, b = 0.0; - - do { - switch(omm->omm_usDepth) { - case 1: - write_float( - oArray, - *data++, - omm->omm_bBigEndian - ); - break; - case 3: - r = *data++; - g = *data++; - b = *data++; - write_float(oArray, r, omm->omm_bBigEndian); - write_float(oArray, g, omm->omm_bBigEndian); - write_float(oArray, b, omm->omm_bBigEndian); - break; - } - } while(--count); - } else { - ULONG count = width * height; - UWORD *data = (UWORD *)omm->omm_pMemPtr; - double r = 0.0, g = 0.0, b = 0.0; - - do { - switch(omm->omm_usDepth) { - case 1: - write_float( - oArray, - HalfToDouble(*data++), - omm->omm_bBigEndian - ); - break; - case 3: - r = HalfToDouble(*data++); - g = HalfToDouble(*data++); - b = HalfToDouble(*data++); - write_float(oArray, r, omm->omm_bBigEndian); - write_float(oArray, g, omm->omm_bBigEndian); - write_float(oArray, b, omm->omm_bBigEndian); - break; - } - } while(--count); - } - } else { - // DICOM should always be integer input - // Write pixel data to target - ULONG size = omm->omm_ucPixelType & CTYP_SIZE_MASK; - ULONG count = width * height * omm->omm_usDepth; - UBYTE *mem = (UBYTE *)(omm->omm_pMemPtr); - // For each pixel - for (ULONG ii = 1; ii <= count; ii++) { - // For each byte of the pixel - for (ULONG jj = 1; jj <= size; jj++) { - if (out->position >= out->length) { - break; - } - // Write the byte value to the output - *oArray = *mem; - oArray++; - out->position += 1; - mem++; - } - } - // Update the buffer pointer - out->pData = oArray; - } - } - } - } - OpenComponents &= ~(1UL << comp); - } - break; - } - return 0; -} diff --git a/pylibjpeg/src/pylibjpeg/streamhook.hpp b/pylibjpeg/src/pylibjpeg/streamhook.hpp deleted file mode 100644 index 07cffda..0000000 --- a/pylibjpeg/src/pylibjpeg/streamhook.hpp +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef PYLIBJPEG_STREAMHOOK_HPP -#define PYLIBJPEG_STREAMHOOK_HPP - -// Includes -#include "../libjpeg/interface/types.hpp" -#include "std/stdio.hpp" -#include "decode.hpp" - - -// Forwards -struct JPG_Hook; -struct JPG_TagItem; - - -// Prototypes -// Handler for the input and output stream hooks -extern JPG_LONG IStreamHook(struct JPG_Hook *hook, struct JPG_TagItem *tags); -extern JPG_LONG OStreamHook(struct JPG_Hook *hook, struct JPG_TagItem *tags); - -/// Administration of output stream -struct StreamMemory { - APTR omm_pMemPtr; // interleaved memory for the HDR image - APTR omm_pLDRMemPtr; // interleaved memory for the LDR version of the image - APTR omm_pAlphaPtr; // memory for the alpha channel - ULONG omm_ulWidth; // width in pixels. - ULONG omm_ulHeight; // height in pixels; this is only one block in our application. - UWORD omm_usDepth; // number of components. - UBYTE omm_ucPixelType; // precision etc. - UBYTE omm_ucAlphaType; // pixel type of the alpha channel - StreamData *omm_pTarget; // where to write the data to. - FILE *omm_pSource; // where the data comes from on reading (encoding) - FILE *omm_pLDRSource; // if there is a separate source for the LDR image, this is non-NULL. - // TODO: output alpha to numpy array - FILE *omm_pAlphaTarget;// where the alpha (if any) goes to on decoding - FILE *omm_pAlphaSource;// where the alpha data (if any) comes from. There is no dedicated alpha LDR file - const UWORD *omm_HDR2LDR; // the (simple global) tone mapper used for encoding the image. - bool omm_bFloat; // is true if the input is floating point - bool omm_bAlphaFloat; // is true if the opacity information is floating point - bool omm_bBigEndian; // is true if the floating point input is big endian - bool omm_bAlphaBigEndian; // if true, the floating point alpha channel is big endian - bool omm_bNoOutputConversion; // if true, the FLOAT stays float and the half-map is not applied. - bool omm_bNoAlphaOutputConversion; // ditto for alpha - bool omm_bClamp; // if set, clamp negative values to zero. - bool omm_bAlphaClamp; // if set, alpha values outside [0,1] will be clamped to range - bool omm_bUpsampling; // if set, data is already upsampled. -}; - -#endif diff --git a/pylibjpeg/src/pylibjpeg/utils.hpp b/pylibjpeg/src/pylibjpeg/utils.hpp deleted file mode 100644 index 1d84122..0000000 --- a/pylibjpeg/src/pylibjpeg/utils.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2020 pylibjpeg contributors -// -// This work is licensed under GPL-3.0-only, see LICENSE.txt for details. - -#include "decode.hpp" - -void inline write_float(char *out, FLOAT f, bool bigendian) -{ - union { - LONG long_buf; - FLOAT float_buf; - } u; - - u.float_buf = f; - - if (bigendian) { - *out = u.long_buf >> 24; - out++; - *out = u.long_buf >> 16; - out++; - *out = u.long_buf >> 8; - out++; - *out = u.long_buf >> 0; - out++; - } else { - *out = u.long_buf >> 0; - out++; - *out = u.long_buf >> 8; - out++; - *out = u.long_buf >> 16; - out++; - *out = u.long_buf >> 24; - out++; - } -} diff --git a/pylibjpeg/tests/README.md b/pylibjpeg/tests/README.md new file mode 100644 index 0000000..f7a6b32 --- /dev/null +++ b/pylibjpeg/tests/README.md @@ -0,0 +1,11 @@ +## Unit tests for pylibjpeg + +### Dependencies + +#### Required +[pytest](https://docs.pytest.org/) +[pylibjpeg-data](https://github.com/pydicom/pylibjpeg-data) + +#### Optional +[pydicom](https://github.com/pydicom/pydicom) +[pylibjpeg-jpeg](https://github.com/pydicom/pylibjpeg-libjpeg) diff --git a/pylibjpeg/tests/README.rst b/pylibjpeg/tests/README.rst deleted file mode 100644 index 66b4137..0000000 --- a/pylibjpeg/tests/README.rst +++ /dev/null @@ -1,13 +0,0 @@ -Unit tests for pylibjpeg - -Dependencies ------------- - -Required -........ -pytest -pylibjpeg-data - -Optional -........ -pydicom diff --git a/pylibjpeg/tests/test_decode.py b/pylibjpeg/tests/test_decode.py deleted file mode 100644 index ab2d777..0000000 --- a/pylibjpeg/tests/test_decode.py +++ /dev/null @@ -1,538 +0,0 @@ -"""Tests for pylibjpeg.decode().""" - -from io import BytesIO -import os -import pytest -import warnings - -import numpy as np - -try: - import pydicom - from pydicom.encaps import generate_pixel_data_frame - HAS_PYDICOM = True -except ImportError: - HAS_PYDICOM = False - -from pylibjpeg import add_handler, remove_handler, decode -from pylibjpeg.data import get_indexed_datasets, JPEG_DIRECTORY - - -DIR_10918 = os.path.join(JPEG_DIRECTORY, '10918') -DIR_14495 = os.path.join(JPEG_DIRECTORY, '14495') - -REF_DCM = { - '1.2.840.10008.1.2.4.50' : [ - # filename, (rows, columns, samples/px, bits/sample) - ('JPEGBaseline_1s_1f_u_08_08.dcm', (100, 100, 1, 8)), - ('SC_rgb_dcmtk_+eb+cy+np.dcm', (100, 100, 3, 8)), - ('color3d_jpeg_baseline.dcm', (480, 640, 3, 8)), - ('SC_rgb_dcmtk_+eb+cr.dcm', (100, 100, 3, 8)), - ('SC_rgb_dcmtk_+eb+cy+n1.dcm', (100, 100, 3, 8)), - ('SC_rgb_dcmtk_+eb+cy+s4.dcm', (100, 100, 3, 8)), - ], - '1.2.840.10008.1.2.4.51' : [ - ('RG2_JPLY_fixed.dcm', (2140, 1760, 1, 12)), - ('JPEGExtended_1s_1f_u_16_12.dcm', (1024, 256, 1, 12)), - ('JPEGExtended_3s_1f_u_08_08.dcm', (576, 768, 3, 8)), - ], - '1.2.840.10008.1.2.4.57' : [ - ('JPEGLossless_1s_1f_u_16_12.dcm', (1024, 1024, 1, 12)), - ], - '1.2.840.10008.1.2.4.70' : [ - ('JPEG-LL.dcm', (1024, 256, 1, 16)), - ('JPEGLosslessP14SV1_1s_1f_u_08_08.dcm', (768, 1024, 1, 8)), - ('JPEGLosslessP14SV1_1s_1f_u_16_16.dcm', (535, 800, 1, 16)), - ('MG1_JPLL.dcm', (4664, 3064, 1, 12)), - ('RG1_JPLL.dcm', (1955, 1841, 1, 15)), - ('RG2_JPLL.dcm', (2140, 1760, 1, 10)), - ('SC_rgb_jpeg_gdcm.dcm', (100, 100, 3, 8)), - ], - '1.2.840.10008.1.2.4.80' : [ - ('emri_small_jpeg_ls_lossless.dcm', (64, 64, 1, 12)), - ('MR_small_jpeg_ls_lossless.dcm', (64, 64, 1, 16)), - ('RG1_JLSL.dcm', (1955, 1841, 1, 16)), - ('RG2_JLSL.dcm', (2140, 1760, 1, 10)), - ], - '1.2.840.10008.1.2.4.81' : [ - ('CT1_JLSN.dcm', (512, 512, 1, 16)), - ('MG1_JLSN.dcm', (4664, 3064, 1, 12)), - ('RG1_JLSN.dcm', (1955, 1841, 1, 15)), - ('RG2_JLSN.dcm', (2140, 1760, 1, 10)), - ], -} - - -# TODO: convert to using straight JPG data -@pytest.mark.skipif(not HAS_PYDICOM, reason="No pydicom") -def test_decode_bytes(): - """Test decode using bytes.""" - index = get_indexed_datasets('1.2.840.10008.1.2.4.50') - ds = index['JPEGBaseline_1s_1f_u_08_08.dcm']['ds'] - nr_frames = ds.get('NumberOfFrames', 1) - frame = next(generate_pixel_data_frame(ds.PixelData, nr_frames)) - arr = decode(frame) - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - # Reference values from GDCM handler - assert 76 == arr[ 5, 50] - assert 167 == arr[15, 50] - assert 149 == arr[25, 50] - assert 203 == arr[35, 50] - assert 29 == arr[45, 50] - assert 142 == arr[55, 50] - assert 1 == arr[65, 50] - assert 64 == arr[75, 50] - assert 192 == arr[85, 50] - assert 255 == arr[95, 50] - - -# TODO: convert to using straight JPG data -@pytest.mark.skipif(not HAS_PYDICOM, reason="No pydicom") -def test_invalid_colourspace_warns(): - """Test that using an unknown colourspace gives a warning.""" - index = get_indexed_datasets('1.2.840.10008.1.2.4.50') - ds = index['JPEGBaseline_1s_1f_u_08_08.dcm']['ds'] - nr_frames = ds.get('NumberOfFrames', 1) - frame = next(generate_pixel_data_frame(ds.PixelData, nr_frames)) - msg = ( - r"" - ) - with pytest.warns(UserWarning, match=msg): - arr = decode(np.frombuffer(frame, 'uint8'), colourspace='ANY') - - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - # Reference values from GDCM handler - assert 76 == arr[ 5, 50] - assert 167 == arr[15, 50] - assert 149 == arr[25, 50] - assert 203 == arr[35, 50] - assert 29 == arr[45, 50] - assert 142 == arr[55, 50] - assert 1 == arr[65, 50] - assert 64 == arr[75, 50] - assert 192 == arr[85, 50] - assert 255 == arr[95, 50] - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="No pydicom") -class TestDecodeDCM(object): - """Tests for get_parameters() using DICOM datasets.""" - def generate_frames(self, ds): - """Return a generator object with the dataset's pixel data frames.""" - nr_frames = ds.get('NumberOfFrames', 1) - return generate_pixel_data_frame(ds.PixelData, nr_frames) - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.50']) - def test_baseline(self, fname, info): - """Test get_parameters() for the baseline datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.50') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - arr = decode(np.frombuffer(frame, 'uint8'), reshape=True) - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - if 1 <= info[3] <= 8: - assert arr.dtype == 'uint8' - if 9 <= info[3] <= 16: - assert arr.dtype == 'uint16' - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.51']) - def test_extended(self, fname, info): - """Test get_parameters() for the baseline datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.51') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - arr = decode(np.frombuffer(frame, 'uint8'), reshape=True) - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - if 1 <= info[3] <= 8: - assert arr.dtype == 'uint8' - if 9 <= info[3] <= 16: - assert arr.dtype == 'uint16' - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.57']) - def test_lossless(self, fname, info): - """Test get_parameters() for the lossless datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.57') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - arr = decode(np.frombuffer(frame, 'uint8'), reshape=True) - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - if 1 <= info[3] <= 8: - assert arr.dtype == 'uint8' - if 9 <= info[3] <= 16: - assert arr.dtype == 'uint16' - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.70']) - def test_lossless_sv1(self, fname, info): - """Test get_parameters() for the lossless SV1 datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.70') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - arr = decode(np.frombuffer(frame, 'uint8'), reshape=True) - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - if 1 <= info[3] <= 8: - assert arr.dtype == 'uint8' - if 9 <= info[3] <= 16: - assert arr.dtype == 'uint16' - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.80']) - def test_extended(self, fname, info): - """Test get_parameters() for the LS lossless datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.80') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - arr = decode(np.frombuffer(frame, 'uint8'), reshape=True) - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - if 1 <= info[3] <= 8: - assert arr.dtype == 'uint8' - if 9 <= info[3] <= 16: - assert arr.dtype == 'uint16' - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.81']) - def test_extended(self, fname, info): - """Test get_parameters() for the LS lossy datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.81') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - arr = decode(np.frombuffer(frame, 'uint8'), reshape=True) - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - if 1 <= info[3] <= 8: - assert arr.dtype == 'uint8' - if 9 <= info[3] <= 16: - assert arr.dtype == 'uint16' - - -REF_JPG = { - '10918' : { - # Reference values using libjpeg's `jpeg` app + imageJ - # Very circular but having issues with other programs interpreting - # it as CYMK and doing weird stuff - 'p1' : [ - # ([top left pixel], [bottom right pixel]) - ( - 'A1.JPG', (257, 255, 4, 8), - ([138, 76, 239, 216], [155, 217, 191, 115]) - ), - #('B1.JPG', (1, 1, 1, 1)), - #('B2.JPG', (1, 1, 1, 1)), missing DHT marker (its in B1.JPG) - ], - 'p2' : [ - ( - 'A1.JPG', (257, 255, 4, 8), - ([138, 76, 239, 216], [155, 217, 191, 115]) - ), - #('B1.JPG', ()), - #('B2.JPG', ()), missing DHT (in B1) - ( - 'C1.JPG', (257, 255, 4, 8), - ([138, 76, 239, 216], [155, 217, 191, 115]) - ), - ( - 'C2.JPG', (257, 255, 4, 8), - ([138, 76, 239, 216], [155, 217, 191, 115]) - ), - ], - 'p4' : [ - ( - 'A1.JPG', (257, 255, 4, 8), - ([138, 76, 239, 216], [155, 217, 191, 115]) - ), - #('B1.JPG', ()), - #('B2.JPG', ()), - ( - 'C1.JPG', (257, 255, 4, 8), - ([138, 76, 239, 216], [155, 217, 191, 115]) - ), - ( - 'C2.JPG', (257, 255, 4, 8), - ([138, 76, 239, 216], [155, 217, 191, 115]) - ), - ( - 'E1.JPG', (257, 255, 4, 12), - ([2119, 1183, 3907, 3487], [2502, 3402, 3041, 1872]) - ), - ( - 'E2.JPG', (257, 255, 4, 12), - ([2119, 1183, 3907, 3487], [2502, 3402, 3041, 1872]) - ), - ], - 'p14' : [ - ( - 'O1.JPG', (257, 255, 4, 8), - ([132, 76, 245, 218], [156, 211, 191, 116]) - ), - ( - 'O2.JPG', (257, 255, 4, 16), - ([33792, 19456, 62720, 55808], [39936, 53888, 48768, 29696]) - ), - ], - }, - '14495' : { - 'JLS' : [ # Lossless - ( - # Reference values using GDCM - 'T8C0E0.JLS', (256, 256, 3, 8), - ([161, 122, 108], [101, 99, 95]) - ), - ( - # GDCM and CharPyLS fail on this one - both use CharLS - # Circular reference - 'T8C1E0.JLS', (256, 256, 3, 8), - ([161, 122, 108], [101, 99, 95]) - ), - ( - # CharLS fails - # Circular reference - 'T8C2E0.JLS', (256, 256, 3, 8), - ([161, 122, 108], [101, 99, 95]) - ), - ( - # Reference values using GDCM - 'T8NDE0.JLS', (128, 128, 1, 8), - (108, 231) - ), - ( - # CharLS fails - # Circular reference - 'T8SSE0.JLS', (256, 256, 3, 8), - ([161, 122, 108], [101, 171, 231]) - ), - ( - # Reference values using GDCM - 'T16E0.JLS', (256, 256, 1, 12), - (1963, 1596) - ), - ], - 'JNL' : [ # Near lossless - ( - # Reference values using GDCM - 'T8C0E3.JLS', (256, 256, 3, 8), - ([161, 119, 105], [98, 96, 93]) - ), - ( - # CharLS fails - # Circular reference - 'T8C1E3.JLS', (256, 256, 3, 8), - ([161, 119, 105], [101, 100, 97]) - ), - ( - # CharLS fails - # Circular reference - 'T8C2E3.JLS', (256, 256, 3, 8), - ([161, 119, 105], [98, 96, 94]) - ), - ( - # Reference values using GDCM - 'T8NDE3.JLS', (128, 128, 1, 8), - (105, 229) - ), - ( - # CharLS fails - # Circular reference - 'T8SSE3.JLS', (256, 256, 3, 8), - ([161, 119, 105], [102, 169, 234]) - ), - ( - # Reference values using GDCM - 'T16E3.JLS', (256, 256, 1, 12), - (1960, 1593) - ), - ], - }, - '15444' : {}, -} - - -class TestDecodeJPG(object): - """Tests for get_parameters() using JPEG compliance data.""" - @pytest.mark.parametrize("fname, info, ref", REF_JPG['10918']['p1']) - def test_baseline(self, fname, info, ref): - """Test decoding the baseline compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_10918, 'p1', fname), 'rb') as fp: - data = fp.read() - - arr = decode(np.frombuffer(data, 'uint8'), reshape=True) - assert arr.flags.writeable - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - # Process 1 is always 8-bit - assert arr.dtype == 'uint8' - - assert ref[0] == arr[0, 0, :].tolist() - assert ref[1] == arr[-1, -1, :].tolist() - - @pytest.mark.parametrize("fname, info, ref", REF_JPG['10918']['p2']) - def test_extended_p2(self, fname, info, ref): - """Test decoding the extended p2 compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_10918, 'p2', fname), 'rb') as fp: - data = fp.read() - - arr = decode(np.frombuffer(data, 'uint8'), reshape=True) - assert arr.flags.writeable - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - # Process 2 is always 8-bit - assert arr.dtype == 'uint8' - - assert ref[0] == arr[0, 0, :].tolist() - assert ref[1] == arr[-1, -1, :].tolist() - - @pytest.mark.parametrize("fname, info, ref", REF_JPG['10918']['p4']) - def test_extended_p4(self, fname, info, ref): - """Test decoding the extended p4 compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_10918, 'p4', fname), 'rb') as fp: - data = fp.read() - - arr = decode(np.frombuffer(data, 'uint8'), reshape=True) - assert arr.flags.writeable - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - if 1 <= info[3] <= 8: - assert arr.dtype == 'uint8' - if 9 <= info[3] <= 16: - assert arr.dtype == 'uint16' - - assert ref[0] == arr[0, 0, :].tolist() - assert ref[1] == arr[-1, -1, :].tolist() - - @pytest.mark.parametrize("fname, info, ref", REF_JPG['10918']['p14']) - def test_lossless_p14(self, fname, info, ref): - """Test decoding the extended p14 compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_10918, 'p14', fname), 'rb') as fp: - data = fp.read() - - arr = decode(np.frombuffer(data, 'uint8'), reshape=True) - assert arr.flags.writeable - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - if 1 <= info[3] <= 8: - assert arr.dtype == 'uint8' - if 9 <= info[3] <= 16: - assert arr.dtype == 'uint16' - - assert ref[0] == arr[0, 0, :].tolist() - assert ref[1] == arr[-1, -1, :].tolist() - - @pytest.mark.parametrize("fname, info, ref", REF_JPG['14495']['JLS']) - def test_jls(self, fname, info, ref): - """Test decoding the JPEG-LS lossless compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_14495, 'JLS', fname), 'rb') as fp: - data = fp.read() - - arr = decode( - np.frombuffer(data, 'uint8'), - reshape=True, - ) - assert arr.flags.writeable - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - if 1 <= info[3] <= 8: - assert arr.dtype == 'uint8' - if 9 <= info[3] <= 16: - assert arr.dtype == 'uint16' - - if info[2] == 1: - assert ref[0] == arr[0, 0].tolist() - assert ref[1] == arr[-1, -1].tolist() - else: - assert ref[0] == arr[0, 0, :].tolist() - assert ref[1] == arr[-1, -1, :].tolist() - - @pytest.mark.parametrize("fname, info, ref", REF_JPG['14495']['JNL']) - def test_jnl(self, fname, info, ref): - """Test decoding the JPEG-LS near lossless compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_14495, 'JNL', fname), 'rb') as fp: - data = fp.read() - - arr = decode(np.frombuffer(data, 'uint8'), reshape=True) - assert arr.flags.writeable - - if info[2] == 1: - assert (info[0], info[1]) == arr.shape - else: - assert (info[0], info[1], info[2]) == arr.shape - - if 1 <= info[3] <= 8: - assert arr.dtype == 'uint8' - if 9 <= info[3] <= 16: - assert arr.dtype == 'uint16' - - if info[2] == 1: - assert ref[0] == arr[0, 0].tolist() - assert ref[1] == arr[-1, -1].tolist() - else: - assert ref[0] == arr[0, 0, :].tolist() - assert ref[1] == arr[-1, -1, :].tolist() diff --git a/pylibjpeg/tests/test_handler.py b/pylibjpeg/tests/test_handler.py deleted file mode 100644 index ae4ba99..0000000 --- a/pylibjpeg/tests/test_handler.py +++ /dev/null @@ -1,1156 +0,0 @@ -"""Tests for the pylibjpeg pixel data handler.""" - -import pytest -import warnings - -import numpy as np - -try: - import pydicom - import pydicom.config - from pydicom.pixel_data_handlers.util import convert_color_space - from pydicom.encaps import defragment_data - from pylibjpeg import libjpeg_handler - HAS_PYDICOM = True -except ImportError: - HAS_PYDICOM = False - -from pylibjpeg import add_handler, remove_handler, decode -from pylibjpeg.data import get_indexed_datasets - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="pydicom unavailable") -class TestHandler(object): - """Tests for the pixel data handler.""" - def test_unsupported_syntax_raises(self): - """Test exception gets raised if unsupported transfer syntax.""" - index = get_indexed_datasets('1.2.840.10008.1.2.1') - ds = index['CT_small.dcm']['ds'] - assert '1.2.840.10008.1.2.1' == ds.file_meta.TransferSyntaxUID - msg = ( - r"Unable to convert the pixel data as the transfer syntax " - r"is not supported by the pylibjpeg pixel data handler." - ) - with pytest.raises(NotImplementedError, match=msg): - libjpeg_handler.get_pixeldata(ds) - - def test_missing_element_raises(self): - """Test exception gets raised if required element missing.""" - index = get_indexed_datasets('1.2.840.10008.1.2.4.50') - ds = index['JPEGBaseline_1s_1f_u_08_08.dcm']['ds'] - del ds.BitsAllocated - assert 'BitsAllocated' not in ds - msg = ( - r"Unable to convert the pixel data as the following required " - r"elements are missing from the dataset: BitsAllocated" - ) - with pytest.raises(AttributeError, match=msg): - libjpeg_handler.get_pixeldata(ds) - - def test_should_change_pi(self): - """Test the pointless function.""" - index = get_indexed_datasets('1.2.840.10008.1.2.4.50') - ds = index['JPEGBaseline_1s_1f_u_08_08.dcm']['ds'] - func = ( - libjpeg_handler.should_change_PhotometricInterpretation_to_RGB - ) - assert not func(ds) - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="pydicom unavailable") -def test_add_handler(): - """Test adding the handler to pydicom.""" - assert libjpeg_handler in pydicom.config.pixel_data_handlers - remove_handler() - assert libjpeg_handler not in pydicom.config.pixel_data_handlers - add_handler() - assert libjpeg_handler in pydicom.config.pixel_data_handlers - - pydicom.config.pixel_data_handlers.remove(libjpeg_handler) - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="pydicom unavailable") -def test_remove_handler(): - """Test removing the handler from pydicom.""" - add_handler() - assert libjpeg_handler in pydicom.config.pixel_data_handlers - remove_handler() - assert libjpeg_handler not in pydicom.config.pixel_data_handlers - - -@pytest.mark.skipif(HAS_PYDICOM, reason="pydicom available") -def test_add_handler_raises(): - """Test adding the handler raises if no pydicom.""" - with pytest.raises(ImportError): - add_handler() - - -@pytest.mark.skipif(HAS_PYDICOM, reason="pydicom available") -def test_remove_handler_raises(): - """Test removing the handler raises if no pydicom.""" - with pytest.raises(ImportError): - remove_handler() - - -class HandlerTestBase(object): - """Baseclass for handler tests.""" - uid = None - - def setup(self): - add_handler() - self.ds = get_indexed_datasets(self.uid) - - def teardown(self): - remove_handler() - - def plot(self, arr, index=None, cmap=None): - import matplotlib.pyplot as plt - - if index is not None: - if cmap: - plt.imshow(arr[index], cmap=cmap) - else: - plt.imshow(arr[index]) - else: - if cmap: - plt.imshow(arr, cmap=cmap) - else: - plt.imshow(arr) - - plt.show() - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="No dependencies") -class TestLibrary(object): - """Tests for libjpeg itself.""" - def setup(self): - add_handler() - - def teardown(self): - remove_handler() - - def test_non_conformant_raises(self): - """Test that a non-conformant JPEG image raises an exception.""" - ds_list = get_indexed_datasets('1.2.840.10008.1.2.4.51') - # Image has invalid Se value in the SOS marker segment - item = ds_list['JPEG-lossy.dcm'] - assert 0xC000 == item['Status'][1] - msg = ( - r"libjpeg error code '-1038' returned from Decode\(\): A " - r"misplaced marker segment was found - scan start must be zero " - r"and scan stop must be 63 for the sequential operating modes" - ) - with pytest.raises(RuntimeError, match=msg): - item['ds'].pixel_array - - def test_invalid_colour_transform(self): - """Test that an invalid colour transform raises an exception.""" - ds_list = get_indexed_datasets('1.2.840.10008.1.2.4.50') - # Image has invalid Se value in the SOS marker segment - ds = ds_list['color3d_jpeg_baseline.dcm']['ds'] - data = defragment_data(ds.PixelData) - msg = ( - r"Unknown error code '-8194' returned from Decode\(\): " - r"Invalid colourTransform value" - ) - with pytest.raises(RuntimeError, match=msg): - decode(np.frombuffer(data, 'uint8'), -1) - - def test_invalid_buffer(self): - """Test that an invalid colour transform raises an exception.""" - msg = ( - r"Buffer dtype mismatch, expected 'uint8_t' but got 'double'" - ) - with pytest.raises(ValueError, match=msg): - decode(np.zeros(1), 'YBR_FULL') - - -# ISO/IEC 10918 JPEG -@pytest.mark.skipif(not HAS_PYDICOM, reason="No dependencies") -class TestJPEGBaseline(HandlerTestBase): - """Test the handler with ISO 10918 JPEG images. - - 1.2.840.10008.1.2.4.50 : JPEG Baseline (Process 1) - - Process 1: Baseline sequential DCT, 8-bit sample precision. - - Image samples assumed to be unsigned in the range 0 to 255. - - Supported Values - ---------------- - Photometric Interpretation: MONOCHROME1, MONOCHROME2, YBR_FULL_422 - Samples Per Pixel: 1 or 3 - Planar Configuration: 0 (for YBR_FULL_422) - Pixel Representation: 0 (unsigned) - Bits Allocated/Stored: 8/8 - - References - ---------- - * :dcm:`DICOM Standard, Part 5, Table 8.2.1-1 - ` - * ISO/IEC 10918-1 (ITU T.81) - * ISO/IEC 10918-2 - * `JPEG Image Compression Systems - `_ - - Missing datasets - ---------------- - 1 sample/px, 8/8 bits allocated/stored, unsigned, > 1 frame - """ - uid = '1.2.840.10008.1.2.4.50' - - def test_1s_1f(self): - """Test greyscale.""" - ds = self.ds['JPEGBaseline_1s_1f_u_08_08.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 8 == ds.BitsAllocated == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr, cmap='gray') - - # Reference values from GDCM handler - assert 76 == arr[ 5, 50] - assert 167 == arr[15, 50] - assert 149 == arr[25, 50] - assert 203 == arr[35, 50] - assert 29 == arr[45, 50] - assert 142 == arr[55, 50] - assert 1 == arr[65, 50] - assert 64 == arr[75, 50] - assert 192 == arr[85, 50] - assert 255 == arr[95, 50] - - @pytest.mark.skip('No suitable dataset') - def test_1s_Nf(self): - """Test greyscale with N frames.""" - ds = self.ds['JPEGBaseline_1s_2f_08_08.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 2 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 8 == ds.BitsAllocated == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (2, ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr, index=0, cmap='gray') - - def test_3s_1f_ybr_422(self): - """Test YBR with 422 subsampling.""" - # +cy is YCbCr - # +s2 is 422 subsampling w/ YBR_FULL_422 - ds = self.ds['SC_rgb_dcmtk_+eb+cy+np.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 3 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'YBR_FULL_422' == ds.PhotometricInterpretation - assert 8 == ds.BitsAllocated == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.Rows, ds.Columns, 3) == arr.shape - - #self.plot(arr) - - # Reference values may be slightly different depending on handler - # Pillow: assert ( 76, 86, 251) == tuple(arr[ 5, 50, :]) - assert ( 76, 85, 254) == tuple(arr[ 5, 50, :]) - # GDCM: assert (166, 109, 190) == tuple(arr[15, 50, :]) - # Pillow: assert (166, 112, 185) == tuple(arr[15, 50, :]) - assert (166, 108, 190) == tuple(arr[15, 50, :]) - # Pillow: assert (150, 46, 17) == tuple(arr[25, 50, :]) - assert (150, 46, 21) == tuple(arr[25, 50, :]) - # GDCM: assert (203, 85, 74) == tuple(arr[35, 50, :]) - # Pillow: assert (203, 95, 75) == tuple(arr[35, 50, :]) - assert (203, 86, 74) == tuple(arr[35, 50, :]) - # GDCM: assert ( 29, 255, 108) == tuple(arr[45, 50, :]) - # Pillow: assert ( 29, 255, 109) == tuple(arr[45, 50, :]) - assert ( 29, 255, 107) == tuple(arr[45, 50, :]) - # Pillow: assert (142, 189, 118) == tuple(arr[55, 50, :]) - assert (142, 192, 117) == tuple(arr[55, 50, :]) - assert ( 0, 128, 128) == tuple(arr[65, 50, :]) - assert ( 64, 128, 128) == tuple(arr[75, 50, :]) - assert (192, 128, 128) == tuple(arr[85, 50, :]) - assert (255, 128, 128) == tuple(arr[95, 50, :]) - - def test_3s_Nf_ybr_422(self): - """Test 3 sample/px with N frames.""" - ds = self.ds['color3d_jpeg_baseline.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 3 == ds.SamplesPerPixel - assert 1 != getattr(ds, 'NumberOfFrames', 1) - assert 8 == ds.BitsAllocated == ds.BitsStored - assert 'YBR_FULL_422' == ds.PhotometricInterpretation - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.NumberOfFrames, ds.Rows, ds.Columns, 3) == arr.shape - - arr = convert_color_space(arr, 'YBR_FULL', 'RGB') - - #self.plot(arr, index=3) - - # GDCM: all match - assert (41, 41, 41) == tuple(arr[3, 159, 290, :]) - assert (57, 57, 57) == tuple(arr[3, 169, 290, :]) - # Pillow: assert (71, 168, 125) == tuple(arr[3, 41, 380, :]) - assert (72, 167, 125) == tuple(arr[3, 41, 380, :]) - - # Non-conformant datasets - def test_3s_1f_rgb_non(self): - """Test RGB.""" - # +cr is RGB - DICOM non-conformant - ds = self.ds['SC_rgb_dcmtk_+eb+cr.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 3 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'RGB' == ds.PhotometricInterpretation - assert 8 == ds.BitsAllocated == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.Rows, ds.Columns, 3) == arr.shape - - #self.plot(arr) - - assert (255, 0, 0) == tuple(arr[ 5, 50, :]) - assert (255, 128, 128) == tuple(arr[15, 50, :]) - assert ( 0, 255, 0) == tuple(arr[25, 50, :]) - assert (128, 255, 128) == tuple(arr[35, 50, :]) - assert ( 0, 0, 255) == tuple(arr[45, 50, :]) - assert (128, 128, 255) == tuple(arr[55, 50, :]) - assert ( 0, 0, 0) == tuple(arr[65, 50, :]) - assert ( 64, 64, 64) == tuple(arr[75, 50, :]) - assert (192, 192, 192) == tuple(arr[85, 50, :]) - assert (255, 255, 255) == tuple(arr[95, 50, :]) - - def test_3s_1f_ybr_411_non(self): - """Test YBR with 411 subsampling.""" - # +cy is YCbCr - # +n1 is 411 subsampling w/ YBR_FULL - DICOM non-conformant - ds = self.ds['SC_rgb_dcmtk_+eb+cy+n1.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 3 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'YBR_FULL' == ds.PhotometricInterpretation - assert 8 == ds.BitsAllocated == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.Rows, ds.Columns, 3) == arr.shape - - arr = convert_color_space(arr, 'YBR_FULL', 'RGB') - - #self.plot(arr) - - # GDCM: all match - # Pillow: assert (248, 3, 2) == tuple(arr[ 5, 50, :]) - assert (253, 1, 0) == tuple(arr[ 5, 50, :]) - # Pillow: assert (246, 131, 138) == tuple(arr[15, 50, :]) - assert (253, 129, 131) == tuple(arr[15, 50, :]) - # Pillow: assert (129, 252, 145) == tuple(arr[35, 50, :]) - assert (127, 255, 129) == tuple(arr[35, 50, :]) - # Pillow: assert ( 2, 0, 254) == tuple(arr[45, 50, :]) - assert ( 0, 0, 254) == tuple(arr[45, 50, :]) - # Pillow: assert (128, 128, 250) == tuple(arr[55, 50, :]) - assert (127, 128, 255) == tuple(arr[55, 50, :]) - assert ( 0, 0, 0) == tuple(arr[65, 50, :]) - assert ( 64, 64, 64) == tuple(arr[75, 50, :]) - assert (192, 192, 192) == tuple(arr[85, 50, :]) - assert (255, 255, 255) == tuple(arr[95, 50, :]) - - def test_3s_1f_ybr_444_non(self): - """Test YBR with 444 subsampling.""" - # +cy is YCbCr - # +s4 is 444 subsampling w/ YBR_FULL - DICOM non-conformant - ds = self.ds['SC_rgb_dcmtk_+eb+cy+s4.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 3 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'YBR_FULL' == ds.PhotometricInterpretation - assert 8 == ds.BitsAllocated == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.Rows, ds.Columns, 3) == arr.shape - - arr = convert_color_space(arr, 'YBR_FULL', 'RGB') - - #self.plot(arr) - - assert (254, 0, 0) == tuple(arr[ 5, 50, :]) - assert (255, 127, 127) == tuple(arr[15, 50, :]) - assert ( 0, 255, 5) == tuple(arr[25, 50, :]) - assert (129, 255, 129) == tuple(arr[35, 50, :]) - assert ( 0, 0, 254) == tuple(arr[45, 50, :]) - assert (128, 127, 255) == tuple(arr[55, 50, :]) - assert ( 0, 0, 0) == tuple(arr[65, 50, :]) - assert ( 64, 64, 64) == tuple(arr[75, 50, :]) - assert (192, 192, 192) == tuple(arr[85, 50, :]) - assert (255, 255, 255) == tuple(arr[95, 50, :]) - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="No dependencies") -class TestJPEGExtended(HandlerTestBase): - """Test the handler with ISO 10918 JPEG images. - - 1.2.840.10008.1.2.4.51 : JPEG Extended (Process 2 and 4) - - Process 2: Extended sequential DCT, Huffman coding, 8-bit sample precision - Process 4: Extended sequential DCT, Huffman coding, 12-bit sample precision - - Supported Values - ---------------- - Photometric Interpretation: MONOCHROME1, MONOCHROME2 - Samples Per Pixel: 1 - Pixel Representation: 0 (unsigned) - Bits Allocated/Stored: 8/8 or 16/12 - - References - ---------- - * :dcm:`DICOM Standard, Part 5, Table 8.2.1-1 - ` - * ISO/IEC 10918-1 (ITU T.81) - * ISO/IEC 10918-2 - * `JPEG Image Compression Systems - `_ - - Missing datasets - ---------------- - 1 sample/px, 8/8 bits allocated/stored, unsigned, 1 frame - 1 sample/px, 8/8 bits allocated/stored, unsigned, > 1 frame - 1 sample/px, 16/12 bits allocated/stored, unsigned, > 1 frame - """ - uid = '1.2.840.10008.1.2.4.51' - - # Process 2 - @pytest.mark.skip("No suitable dataset") - def test_1s_1f_u_08_08(self): - pass - - @pytest.mark.skip("No suitable dataset") - def test_1s_Nf_u_08_08(self): - pass - - # Process 4 - def test_1s_1f_u_16_10(self): - """Test process 4 greyscale.""" - ds = self.ds['RG2_JPLY_fixed.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - # Input precision is 12, not 10 - assert 10 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from output of IJG's djpeg recompiled for 12-bit - # Note differences | | - # IJG: [571, 582, 666, 766, 803, 781, 726, 651, 595, 578] - assert [571, 582, 666, 765, 803, 781, 725, 651, 595, 578] == ( - arr[845, 964:974].tolist() - ) - - def test_1s_1f_u_16_12(self): - """Test process 4 greyscale.""" - ds = self.ds['JPEGExtended_1s_1f_u_16_12.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 12 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from output of IJG's djpeg recompiled for 12-bit - # Note differences | - # IJG: [134, 143, 161, 172, 180, 193, 249, 214, 223, 247] - assert [134, 143, 160, 172, 180, 193, 249, 214, 223, 247] == ( - arr[410:420, 136].tolist() - ) - - @pytest.mark.skip("No suitable dataset") - def test_1s_Nf_u_16_12(self): - pass - - # Non-conformant datasets - def test_3s_1f_u_08_08_non(self): - """Test process 2 greyscale.""" - # Non-conformant to DICOM - ds = self.ds['JPEGExtended_3s_1f_u_08_08.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 3 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'YBR_FULL' in ds.PhotometricInterpretation - assert 8 == ds.BitsAllocated - assert 8 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.Rows, ds.Columns, 3) == arr.shape - - #self.plot(arr) - - # Reference values from GDCM handler - in YBR colour space - assert [ - [ 71, 86, 147], - [124, 62, 167], - [138, 66, 175], - [145, 65, 172], - [150, 59, 168], - [178, 59, 167], - [183, 56, 171], - [201, 83, 165], - [213, 92, 153], - [255, 132, 134] - ] == arr[41, 105:115].tolist() - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="No dependencies") -class TestJPEGLossless(HandlerTestBase): - """Test the handler with ISO 10918 JPEG images. - - 1.2.840.10008.1.2.4.57 : JPEG Lossless, Non-Hierarchical (Process 14) - - Process 14: Lossless, Huffman coding, 2 to 16-bit sample precision - - Supported Values - ---------------- - Photometric Interpretation: MONOCHROME1, MONOCHROME2, PALETTE COLOR, - YBR_FULL, RGB - Samples Per Pixel: 1 or 3 - Planar Configuration: 0 (for RGB/YBR_FULL) - Pixel Representation: 0 (unsigned) or 1 (signed, monochrome only) - Bits Allocated: 8 or 16 - Bits Stored: 1 to 16 - - References - ---------- - * :dcm:`DICOM Standard, Part 5, Table 8.2.1-2 - ` - * ISO/IEC 10918-1 (ITU T.81) - * ISO/IEC 10918-2 - * `JPEG Image Compression Systems - `_ - - Missing datasets - ---------------- - 1 sample/px, 8/8 bits allocated/stored, signed, 1 frame - 1 sample/px, 8/8 bits allocated/stored, signed, > 1 frame - 1 sample/px, 8/8 bits allocated/stored, unsigned, > 1 frame - 1 sample/px, 16/xx bits allocated/stored, signed, 1 frame - 1 sample/px, 16/xx bits allocated/stored, signed, > 1 frame - 1 sample/px, 16/16 bits allocated/stored, signed, > 1 frame - 1 sample/px, 16/xx bits allocated/stored, unsigned, > 1 frame - 1 sample/px, 16/16 bits allocated/stored, unsigned, 1 frame - 1 sample/px, 16/16 bits allocated/stored, unsigned, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, PALETTE COLOR, 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, PALETTE COLOR, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, YBR_FULL, 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, YBR_FULL, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, RGB, > 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, PALETTE COLOR, 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, PALETTE COLOR, > 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, YBR_FULL, 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, YBR_FULL, > 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, YBR_FULL, 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, YBR_FULL, > 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, RGB, > 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, RGB, > 1 frame - """ - uid = '1.2.840.10008.1.2.4.57' - - def test_1s_1f_u_08_08(self): - """Test process 2 greyscale.""" - ds = self.ds['JPEGLossless_1s_1f_u_16_12.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 12 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from GDCM handler - lossless must be identical! - assert [392, 304, 238, 250, 224, 257, 221, 182, 166, 68] == ( - arr[779, 170:180].tolist() - ) - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="No dependencies") -class TestJPEGLosslessSV1(HandlerTestBase): - """Test the handler with ISO 10918 JPEG images. - - 1.2.840.10008.1.2.4.70 : JPEG Lossless, Non-Hierarchical, First-Order - Prediction (Process 14 [Selection Value 1] - - Process 14: Lossless, Huffman coding, 2 to 16-bit sample precision, - selection value of 1 - - Supported Values - ---------------- - Photometric Interpretation: MONOCHROME1, MONOCHROME2, PALETTE COLOR, - YBR_FULL, RGB - Samples Per Pixel: 1 or 3 - Planar Configuration: 0 (for RGB/YBR_FULL) - Pixel Representation: 0 (unsigned) or 1 (signed, monochrome only) - Bits Allocated: 8 or 16 - Bits Stored: 1 to 16 - - References - ---------- - * :dcm:`DICOM Standard, Part 5, Table 8.2.1-2 - ` - * ISO/IEC 10918-1 (ITU T.81) - * ISO/IEC 10918-2 - * `JPEG Image Compression Systems - `_ - - Missing datasets - ---------------- - 1 sample/px, 8/8 bits allocated/stored, signed, 1 frame - 1 sample/px, 8/8 bits allocated/stored, signed, > 1 frame - 1 sample/px, 8/8 bits allocated/stored, unsigned, > 1 frame - 1 sample/px, 16/xx bits allocated/stored, signed, 1 frame - 1 sample/px, 16/xx bits allocated/stored, signed, > 1 frame - 1 sample/px, 16/16 bits allocated/stored, signed, > 1 frame - 1 sample/px, 16/xx bits allocated/stored, unsigned, > 1 frame - 1 sample/px, 16/16 bits allocated/stored, unsigned, 1 frame - 1 sample/px, 16/16 bits allocated/stored, unsigned, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, PALETTE COLOR, 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, PALETTE COLOR, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, YBR_FULL, 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, YBR_FULL, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, RGB, > 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, PALETTE COLOR, 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, PALETTE COLOR, > 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, YBR_FULL, 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, YBR_FULL, > 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, YBR_FULL, 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, YBR_FULL, > 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, RGB, > 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, RGB, > 1 frame - """ - uid = '1.2.840.10008.1.2.4.70' - - # 1 sample/px, 8/8 - def test_1s_1f_u_08_08(self): - """Test process 2 greyscale.""" - ds = self.ds['JPEGLosslessP14SV1_1s_1f_u_08_08.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 8 == ds.BitsAllocated - assert 8 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from GDCM handler - assert [0, 255, 254, 253, 253, 252, 251] == arr[121:128, 974].tolist() - - # 1 sample/px, 16/NN - def test_1s_1f_u_16_10(self): - """Test process 2 greyscale.""" - ds = self.ds['RG2_JPLL.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 10 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from GDCM handler - assert [574, 669, 763, 782, 789, 736, 637, 583, 592, 589] == ( - arr[845, 965:975].tolist() - ) - - def test_1s_1f_u_16_12(self): - """Test process 2 greyscale.""" - ds = self.ds['MG1_JPLL.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 12 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from GDCM handler - assert [3023, 2862, 2841, 2825, 2841] == arr[1830:1835, 1285].tolist() - - def test_1s_1f_u_16_15(self): - """Test process 2 greyscale.""" - ds = self.ds['RG1_JPLL.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 15 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from GDCM handler - assert [24043, 23906, 23669, 23526, 22962, 22874, 22501, 22066] == ( - arr[1900, 1805:1813].tolist() - ) - - def test_1s_1f_i_16_16(self): - """Test process 2 greyscale.""" - ds = self.ds['JPEG-LL.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 16 == ds.BitsStored - assert 1 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'int16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - assert 227 == arr[420, 140] - assert 105 == arr[230, 120] - - # 3 samples/px, 8/8 - def test_3s_1f_u_08_08_rgb(self): - """Test process 2 greyscale.""" - ds = self.ds['SC_rgb_jpeg_gdcm.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 3 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'RGB' in ds.PhotometricInterpretation - assert 8 == ds.BitsAllocated - assert 8 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint8' == arr.dtype - assert (ds.Rows, ds.Columns, 3) == arr.shape - - #self.plot(arr) - - assert (255, 0, 0) == tuple(arr[ 5, 50, :]) - assert (255, 128, 128) == tuple(arr[15, 50, :]) - assert ( 0, 255, 0) == tuple(arr[25, 50, :]) - assert (128, 255, 128) == tuple(arr[35, 50, :]) - assert ( 0, 0, 255) == tuple(arr[45, 50, :]) - assert (128, 128, 255) == tuple(arr[55, 50, :]) - assert ( 0, 0, 0) == tuple(arr[65, 50, :]) - assert ( 64, 64, 64) == tuple(arr[75, 50, :]) - assert (192, 192, 192) == tuple(arr[85, 50, :]) - assert (255, 255, 255) == tuple(arr[95, 50, :]) - - -# ISO/IEC 14495 JPEG-LS -@pytest.mark.skipif(not HAS_PYDICOM, reason="No dependencies") -class TestJPEGLSLossless(HandlerTestBase): - """Test the handler with ISO 14495 JPEG-LS images. - - 1.2.840.10008.1.2.4.80 : JPEG-LS Lossless Image Compression - - Supported Values - ---------------- - Photometric Interpretation: MONOCHROME1, MONOCHROME2, PALETTE COLOR, - YBR_FULL, RGB - Samples Per Pixel: 1 or 3 - Planar Configuration: 1 (for RGB/YBR_FULL) - Pixel Representation: 0 (unsigned) or 1 (signed, monochrome only) - Bits Allocated: 8 or 16 - Bits Stored: 2 to 16 - - References - ---------- - * :dcm:`DICOM Standard, Part 5, Table 8.2.3-1 - ` - * ISO/IEC 14495 - - Missing datasets - ---------------- - 1 sample/px, 8/8 bits allocated/stored, signed, 1 frame - 1 sample/px, 8/8 bits allocated/stored, signed, > 1 frame - 1 sample/px, 8/8 bits allocated/stored, unsigned, 1 frame - 1 sample/px, 8/8 bits allocated/stored, unsigned, > 1 frame - 1 sample/px, 16/xx bits allocated/stored, signed, 1 frame - 1 sample/px, 16/xx bits allocated/stored, signed, > 1 frame - 1 sample/px, 16/16 bits allocated/stored, signed, > 1 frame - 1 sample/px, 16/xx bits allocated/stored, unsigned, 1 frame - 1 sample/px, 16/16 bits allocated/stored, unsigned, 1 frame - 1 sample/px, 16/16 bits allocated/stored, unsigned, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, PALETTE COLOR, 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, PALETTE COLOR, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, YBR_FULL, 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, YBR_FULL, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, RGB, > 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, PALETTE COLOR, 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, PALETTE COLOR, > 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, RGB, > 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, RGB, > 1 frame - """ - uid = '1.2.840.10008.1.2.4.80' - - def test_1s_1f_i_16_16(self): - """Test process 2 greyscale.""" - ds = self.ds['MR_small_jpeg_ls_lossless.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 16 == ds.BitsStored - assert 1 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'int16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr, cmap='gray') - - # Reference values from GDCM handler - assert [1194, 879, 127, 661, 1943, 1885, 1857, 1746, 1699] == ( - arr[55:65, 38].tolist() - ) - - def test_1s_Nf_u_16_12(self): - """Test process 2 greyscale.""" - ds = self.ds['emri_small_jpeg_ls_lossless.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 10 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 12 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint16' == arr.dtype - assert (10, ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr, index=0, cmap='gray') - - # Reference values from GDCM handler - assert [361, 295, 215, 98, 79, 70, 41, 29, 61, 64] == ( - arr[0, 18:28, 48].tolist() - ) - assert [298, 332, 355, 361, 324, 263, 169, 105, 53, 45] == ( - arr[9, 18:28, 48].tolist() - ) - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="No dependencies") -class TestJPEGLS(HandlerTestBase): - """Test the handler with ISO 14495 JPEG-LS images. - - Transfer Syntaxes - ----------------- - - 1.2.840.10008.1.2.4.81 : JPEG-LS Lossy (Near-Lossless) Image Compression - - Supported Values - ---------------- - Photometric Interpretation: MONOCHROME1, MONOCHROME2, YBR_FULL, RGB - Samples Per Pixel: 1 or 3 - Planar Configuration: 1 (for RGB/YBR_FULL) - Pixel Representation: 0 (unsigned) or 1 (signed, monochrome only) - Bits Allocated: 8 or 16 - Bits Stored: 2 to 16 - - References - ---------- - * :dcm:`DICOM Standard, Part 5, Table 8.2.3-1 - ` - * ISO/IEC 14495 - - Missing datasets - ---------------- - 1 sample/px, 8/8 bits allocated/stored, signed, 1 frame - 1 sample/px, 8/8 bits allocated/stored, signed, > 1 frame - 1 sample/px, 8/8 bits allocated/stored, unsigned, 1 frame - 1 sample/px, 8/8 bits allocated/stored, unsigned, > 1 frame - 1 sample/px, 16/xx bits allocated/stored, signed, 1 frame - 1 sample/px, 16/xx bits allocated/stored, signed, > 1 frame - 1 sample/px, 16/16 bits allocated/stored, signed, > 1 frame - 1 sample/px, 16/xx bits allocated/stored, unsigned, > 1 frame - 1 sample/px, 16/16 bits allocated/stored, unsigned, 1 frame - 1 sample/px, 16/16 bits allocated/stored, unsigned, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, YBR_FULL, 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, YBR_FULL, > 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 8/8 bits allocated/stored, unsigned, RGB, > 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 16/xx bits allocated/stored, unsigned, RGB, > 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, RGB, 1 frame - 3 sample/px, 16/16 bits allocated/stored, unsigned, RGB, > 1 frame - """ - uid = '1.2.840.10008.1.2.4.81' - - def test_1s_1f_i_16_16(self): - """Test process 2 greyscale.""" - ds = self.ds['CT1_JLSN.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 16 == ds.BitsStored - assert 1 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'int16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from GDCM handler - assert [-2000, -2000, 936, 946, 927, 925, 918, 929, 931, 921] == ( - arr[433, 69:79].tolist() - ) - - def test_1s_1f_u_16_10(self): - """Test process 2 greyscale.""" - ds = self.ds['RG2_JLSN.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 10 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from GDCM handler - assert [574, 666, 760, 781, 789, 733, 634, 585, 594, 589] == ( - arr[845, 965:975].tolist() - ) - - def test_1s_1f_u_16_12(self): - """Test process 2 greyscale.""" - ds = self.ds['MG1_JLSN.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 12 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from GDCM handler - assert [3027, 2859, 2839, 2821, 2837, 2834, 2817, 2844, 2837] == ( - arr[1830:1839, 1285].tolist() - ) - - def test_1s_1f_u_16_15(self): - """Test process 2 greyscale.""" - ds = self.ds['RG1_JLSN.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 15 == ds.BitsStored - assert 0 == ds.PixelRepresentation - - arr = ds.pixel_array - assert arr.flags.writeable - assert 'uint16' == arr.dtype - assert (ds.Rows, ds.Columns) == arr.shape - - #self.plot(arr) - - # Reference values from GDCM handler - assert [24047, 23910, 23668, 23529, 22960, 22871, 22505, 22066] == ( - arr[1900, 1805:1813].tolist() - ) - - -# ISO/IEC 15444 JPEG 2000 - Expected fail -@pytest.mark.skipif(not HAS_PYDICOM, reason="No dependencies") -class TestJPEG2000Lossless(HandlerTestBase): - """Test the handler with ISO 15444 JPEG2000 images. - - 1.2.840.10008.1.2.4.90 : JPEG 2000 Image Compression (Lossless Only) - """ - uid = '1.2.840.10008.1.2.4.90' - - def setup(self): - add_handler() - self.ds = get_indexed_datasets(self.uid) - - # Check if J2K is already supported, and if not add it - self.has_tsyntax = True - if self.uid not in libjpeg_handler.SUPPORTED_TRANSFER_SYNTAXES: - self.has_tsyntax = False - libjpeg_handler.SUPPORTED_TRANSFER_SYNTAXES.append(self.uid) - - def teardown(self): - remove_handler() - - # Restore J2K if it was originally supported - if not self.has_tsyntax: - libjpeg_handler.SUPPORTED_TRANSFER_SYNTAXES.remove(self.uid) - - def test_1s_1f_i_16_16(self): - """Test process 2 greyscale.""" - ds = self.ds['693_J2KR.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 16 == ds.BitsStored - assert 1 == ds.PixelRepresentation - - msg = ( - r"libjpeg error code '-1038' returned from Decode\(\): A " - r"misplaced marker segment was found - stream does not contain a " - r"JPEG file, SOI marker missing" - ) - with pytest.raises(RuntimeError, match=msg): - arr = ds.pixel_array - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="No dependencies") -class TestJPEG2000(HandlerTestBase): - """Test the handler with ISO 15444 JPEG2000 images. - - 1.2.840.10008.1.2.4.91 : JPEG 2000 Image Compression - """ - uid = '1.2.840.10008.1.2.4.91' - - def setup(self): - add_handler() - self.ds = get_indexed_datasets(self.uid) - - # Check if J2K is already supported, and if not add it - self.has_tsyntax = True - if self.uid not in libjpeg_handler.SUPPORTED_TRANSFER_SYNTAXES: - self.has_tsyntax = False - libjpeg_handler.SUPPORTED_TRANSFER_SYNTAXES.append(self.uid) - - def teardown(self): - remove_handler() - - # Restore J2K if it was originally supported - if not self.has_tsyntax: - libjpeg_handler.SUPPORTED_TRANSFER_SYNTAXES.remove(self.uid) - - def test_1s_1f_i_16_16(self): - """Test process 2 greyscale.""" - ds = self.ds['693_J2KI.dcm']['ds'] - assert self.uid == ds.file_meta.TransferSyntaxUID - assert 1 == ds.SamplesPerPixel - assert 1 == getattr(ds, 'NumberOfFrames', 1) - assert 'MONOCHROME' in ds.PhotometricInterpretation - assert 16 == ds.BitsAllocated - assert 14 == ds.BitsStored - assert 1 == ds.PixelRepresentation - - msg = ( - r"libjpeg error code '-1038' returned from Decode\(\): A " - r"misplaced marker segment was found - stream does not contain a " - r"JPEG file, SOI marker missing" - ) - with pytest.raises(RuntimeError, match=msg): - arr = ds.pixel_array diff --git a/pylibjpeg/tests/test_parameters.py b/pylibjpeg/tests/test_parameters.py deleted file mode 100644 index 95fdc51..0000000 --- a/pylibjpeg/tests/test_parameters.py +++ /dev/null @@ -1,320 +0,0 @@ -"""Tests for the pylibjpeg pixel data handler.""" - -from io import BytesIO -import os -import pytest -import warnings - -import numpy as np - -try: - import pydicom - import pydicom.config - from pydicom.pixel_data_handlers.util import convert_color_space - from pydicom.encaps import defragment_data, generate_pixel_data_frame - from pylibjpeg import libjpeg_handler - HAS_PYDICOM = True -except ImportError: - HAS_PYDICOM = False - -from pylibjpeg import add_handler, remove_handler, get_parameters -from pylibjpeg.data import get_indexed_datasets, JPEG_DIRECTORY - - -DIR_10918 = os.path.join(JPEG_DIRECTORY, '10918') -DIR_14495 = os.path.join(JPEG_DIRECTORY, '14495') - - -REF_DCM = { - '1.2.840.10008.1.2.4.50' : [ - # filename, (rows, columns, samples/px, bits/sample) - ('JPEGBaseline_1s_1f_u_08_08.dcm', (100, 100, 1, 8)), - ('SC_rgb_dcmtk_+eb+cy+np.dcm', (100, 100, 3, 8)), - ('color3d_jpeg_baseline.dcm', (480, 640, 3, 8)), - ('SC_rgb_dcmtk_+eb+cr.dcm', (100, 100, 3, 8)), - ('SC_rgb_dcmtk_+eb+cy+n1.dcm', (100, 100, 3, 8)), - ('SC_rgb_dcmtk_+eb+cy+s4.dcm', (100, 100, 3, 8)), - ], - '1.2.840.10008.1.2.4.51' : [ - ('RG2_JPLY_fixed.dcm', (2140, 1760, 1, 12)), - ('JPEGExtended_1s_1f_u_16_12.dcm', (1024, 256, 1, 12)), - ('JPEGExtended_3s_1f_u_08_08.dcm', (576, 768, 3, 8)), - ], - '1.2.840.10008.1.2.4.57' : [ - ('JPEGLossless_1s_1f_u_16_12.dcm', (1024, 1024, 1, 12)), - ], - '1.2.840.10008.1.2.4.70' : [ - ('JPEG-LL.dcm', (1024, 256, 1, 16)), - ('JPEGLosslessP14SV1_1s_1f_u_08_08.dcm', (768, 1024, 1, 8)), - ('JPEGLosslessP14SV1_1s_1f_u_16_16.dcm', (535, 800, 1, 16)), - ('MG1_JPLL.dcm', (4664, 3064, 1, 12)), - ('RG1_JPLL.dcm', (1955, 1841, 1, 15)), - ('RG2_JPLL.dcm', (2140, 1760, 1, 10)), - ('SC_rgb_jpeg_gdcm.dcm', (100, 100, 3, 8)), - ], - '1.2.840.10008.1.2.4.80' : [ - ('emri_small_jpeg_ls_lossless.dcm', (64, 64, 1, 12)), - ('MR_small_jpeg_ls_lossless.dcm', (64, 64, 1, 16)), - ('RG1_JLSL.dcm', (1955, 1841, 1, 16)), - ('RG2_JLSL.dcm', (2140, 1760, 1, 10)), - ], - '1.2.840.10008.1.2.4.81' : [ - ('CT1_JLSN.dcm', (512, 512, 1, 16)), - ('MG1_JLSN.dcm', (4664, 3064, 1, 12)), - ('RG1_JLSN.dcm', (1955, 1841, 1, 15)), - ('RG2_JLSN.dcm', (2140, 1760, 1, 10)), - ], -} - - -def test_get_parameters_bytes(): - """Test get_parameters() using bytes.""" - with open(os.path.join(DIR_10918, 'p1', 'A1.JPG'), 'rb') as fp: - data = fp.read() - - params = get_parameters(data) - - info = (257, 255, 4, 8) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="No pydicom") -def test_non_conformant_raises(): - """Test that a non-conformant JPEG image raises an exception.""" - ds_list = get_indexed_datasets('1.2.840.10008.1.2.4.51') - # Image has invalid Se value in the SOS marker segment - item = ds_list['JPEG-lossy.dcm'] - assert 0xC000 == item['Status'][1] - ds = item['ds'] - - nr_frames = ds.get('NumberOfFrames', 1) - frame = next(generate_pixel_data_frame(ds.PixelData, nr_frames)) - - msg = ( - r"libjpeg error code '-1038' returned from GetJPEGParameters\(\): A " - r"misplaced marker segment was found - scan start must be zero " - r"and scan stop must be 63 for the sequential operating modes" - ) - with pytest.raises(RuntimeError, match=msg): - get_parameters(frame) - - -@pytest.mark.skip("Not sure how to trigger exception") -def test_unknown_error_raised(): - """Test that an unknown error is handled properly.""" - #get_parameters(b'') - pass - - -@pytest.mark.skipif(not HAS_PYDICOM, reason="No pydicom") -class TestGetParametersDCM(object): - """Tests for get_parameters() using DICOM datasets.""" - def generate_frames(self, ds): - """Return a generator object with the dataset's pixel data frames.""" - nr_frames = ds.get('NumberOfFrames', 1) - return generate_pixel_data_frame(ds.PixelData, nr_frames) - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.50']) - def test_baseline(self, fname, info): - """Test get_parameters() for the baseline datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.50') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - params = get_parameters(np.frombuffer(frame, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.51']) - def test_extended(self, fname, info): - """Test get_parameters() for the baseline datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.51') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - params = get_parameters(np.frombuffer(frame, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.57']) - def test_lossless(self, fname, info): - """Test get_parameters() for the lossless datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.57') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - params = get_parameters(np.frombuffer(frame, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.70']) - def test_lossless_sv1(self, fname, info): - """Test get_parameters() for the lossless SV1 datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.70') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - params = get_parameters(np.frombuffer(frame, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.80']) - def test_extended(self, fname, info): - """Test get_parameters() for the LS lossless datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.80') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - params = get_parameters(np.frombuffer(frame, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - @pytest.mark.parametrize("fname, info", REF_DCM['1.2.840.10008.1.2.4.81']) - def test_extended(self, fname, info): - """Test get_parameters() for the LS lossy datasets.""" - #info: (rows, columns, spp, bps) - index = get_indexed_datasets('1.2.840.10008.1.2.4.81') - ds = index[fname]['ds'] - - frame = next(self.generate_frames(ds)) - params = get_parameters(np.frombuffer(frame, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - -REF_JPG = { - '10918' : { - 'p1' : [ - ('A1.JPG', (257, 255, 4, 8)), - #('B1.JPG', (1, 1, 1, 1)), - #('B2.JPG', (1, 1, 1, 1)), missing DHT marker (its in B1.JPG) - ], - 'p2' : [ - ('A1.JPG', (257, 255, 4, 8)), - #('B1.JPG', ()), - #('B2.JPG', ()), missing DHT (in B1) - ('C1.JPG', (257, 255, 4, 8)), - ('C2.JPG', (257, 255, 4, 8)), - ], - 'p4' : [ - ('A1.JPG', (257, 255, 4, 8)), - #('B1.JPG', ()), - #('B2.JPG', ()), - ('C1.JPG', (257, 255, 4, 8)), - ('C2.JPG', (257, 255, 4, 8)), - ('E1.JPG', (257, 255, 4, 12)), - ('E2.JPG', (257, 255, 4, 12)), - ], - 'p14' : [ - ('O1.JPG', (257, 255, 4, 8)), - ('O2.JPG', (257, 255, 4, 16)), - ], - }, - '14495' : { - 'JLS' : [ - ('T8C0E0.JLS', (256, 256, 3, 8)), - ('T8C1E0.JLS', (256, 256, 3, 8)), - ('T8C2E0.JLS', (256, 256, 3, 8)), - ('T8NDE0.JLS', (128, 128, 1, 8)), - ('T8SSE0.JLS', (256, 256, 3, 8)), - ('T16E0.JLS', (256, 256, 1, 12)), - ], - 'JNL' : [ - ('T8C0E3.JLS', (256, 256, 3, 8)), - ('T8C1E3.JLS', (256, 256, 3, 8)), - ('T8C2E3.JLS', (256, 256, 3, 8)), - ('T8NDE3.JLS', (128, 128, 1, 8)), - ('T8SSE3.JLS', (256, 256, 3, 8)), - ('T16E3.JLS', (256, 256, 1, 12)), - ], - }, - '15444' : {}, -} - - -class TestGetParametersJPG(object): - """Tests for get_parameters() using JPEG compliance data.""" - @pytest.mark.parametrize("fname, info", REF_JPG['10918']['p1']) - def test_baseline(self, fname, info): - """Test get_parameters() for the baseline compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_10918, 'p1', fname), 'rb') as fp: - data = fp.read() - - params = get_parameters(np.frombuffer(data, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - @pytest.mark.parametrize("fname, info", REF_JPG['10918']['p2']) - def test_extended_p2(self, fname, info): - """Test get_parameters() for the extended p2 compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_10918, 'p2', fname), 'rb') as fp: - data = fp.read() - - params = get_parameters(np.frombuffer(data, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - @pytest.mark.parametrize("fname, info", REF_JPG['10918']['p4']) - def test_extended_p4(self, fname, info): - """Test get_parameters() for the extended p4 compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_10918, 'p4', fname), 'rb') as fp: - data = fp.read() - - params = get_parameters(np.frombuffer(data, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - @pytest.mark.parametrize("fname, info", REF_JPG['10918']['p14']) - def test_lossless_p14(self, fname, info): - """Test get_parameters() for the extended p14 compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_10918, 'p14', fname), 'rb') as fp: - data = fp.read() - - params = get_parameters(np.frombuffer(data, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] - - @pytest.mark.parametrize("fname, info", REF_JPG['14495']['JLS']) - def test_jls(self, fname, info): - """Test get_parameters() for the JPEG-LS compliance images.""" - #info: (rows, columns, spp, bps) - with open(os.path.join(DIR_14495, 'JLS', fname), 'rb') as fp: - data = fp.read() - - params = get_parameters(np.frombuffer(data, 'uint8')) - - assert (info[0], info[1]) == (params['rows'], params['columns']) - assert info[2] == params['samples_per_pixel'] - assert info[3] == params['bits_per_sample'] diff --git a/pylibjpeg/tests/test_plugins.py b/pylibjpeg/tests/test_plugins.py new file mode 100644 index 0000000..eaff405 --- /dev/null +++ b/pylibjpeg/tests/test_plugins.py @@ -0,0 +1,14 @@ +"""Tests for the plugins""" + +import os +import platform +import sys + +import pytest + +from pylibjpeg.plugins import PluginManager + + +class TestPluginManager(object): + """Tests for PluginManager.""" + pass diff --git a/pylibjpeg/tests/test_pydicom.py b/pylibjpeg/tests/test_pydicom.py new file mode 100644 index 0000000..c77fa07 --- /dev/null +++ b/pylibjpeg/tests/test_pydicom.py @@ -0,0 +1,37 @@ +"""Tests for interacting with pydicom.""" + +import os +import platform +import sys + +import pytest + +try: + import pydicom + HAS_PYDICOM = True +except ImportError: + HAS_PYDICOM = False + +from pylibjpeg import _plugin_manager + +HAS_PLUGINS = False +if _plugin_manager.plugins: + HAS_PLUGINS = True + + +@pytest.mark.skipif(not HAS_PYDICOM or HAS_PLUGINS) +class TestNoPlugins(object): + """Test interactions with no plugins.""" + # Should basically just not mess up the usual pydicom behaviour + pass + + +@pytest.mark.skipif(not HAS_PYDICOM or not HAS_PLUGINS) +class TestPlugins(object): + """Test interaction with plugins.""" + # Simple tests to ensure plugins work as intended + pass + + +# May need pydicom to reload some data if dynamically changing +# available plugins diff --git a/pylibjpeg/tests/test_reconstruct.py b/pylibjpeg/tests/test_reconstruct.py deleted file mode 100644 index ba5a8ba..0000000 --- a/pylibjpeg/tests/test_reconstruct.py +++ /dev/null @@ -1,60 +0,0 @@ -"""Tests for the pylibjpeg pixel data handler.""" - -from io import BytesIO -import os -import tempfile -from tempfile import NamedTemporaryFile -import pytest - -from pylibjpeg.libjpeg import reconstruct -from pylibjpeg.data import JPEG_DIRECTORY - -DIR_10918 = os.path.join(JPEG_DIRECTORY, '10918') -DIR_14495 = os.path.join(JPEG_DIRECTORY, '14495') - - -def test_reconstruct_no_alpha(): - """Basic test of reconstruct().""" - # Windows workarounds - tempdir = tempfile.TemporaryDirectory() - inname = os.path.join(tempdir.name, os.urandom(24).hex()) - outname = os.path.join(tempdir.name, os.urandom(24).hex()) - - infile = open(inname, 'wb') - with open(os.path.join(DIR_14495, 'JLS', 'T8C0E0.JLS'), 'rb') as fp: - infile.write(fp.read()) - - infile.close() - - # Output file - reconstruct( - inname, outname, colourspace=0, falpha=None, upsample=True - ) - with open(outname, 'rb') as f: - data = f.read() - - tempdir.cleanup() - - assert b'P6\n256 256' == data[:10] - - -@pytest.mark.skip("Needs more understanding") -def test_reconstruct_alpha(): - """Basic test of reconstruct() with pretend alpha data.""" - # Input file - infile = NamedTemporaryFile('rb+') - with open(os.path.join(DIR_10918, 'p1', 'A1.JPG'), 'rb') as fp: - infile.write(fp.read()) - - # Output file - CMY - outfile = NamedTemporaryFile('rb+') - # Output file - "alpha" - alphafile = NamedTemporaryFile('rb+') - - reconstruct( - infile.name, outfile.name, colourspace=0, - falpha=alphafile.name, upsample=True - ) - - assert b'' == alphafile.read(10) - assert b'P6\n256 256' == outfile.read(10) diff --git a/pylibjpeg/utils.py b/pylibjpeg/utils.py new file mode 100644 index 0000000..e69de29 diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 7933e57..0000000 --- a/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -cython -numpy diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..2a9acf1 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal = 1 diff --git a/setup.py b/setup.py index 38199fb..c70a177 100644 --- a/setup.py +++ b/setup.py @@ -1,144 +1,7 @@ - import os -import sys -from pathlib import Path -import platform -import setuptools from setuptools import setup, find_packages -from setuptools.extension import Extension -import subprocess -from distutils.command.build import build as build_orig -import distutils.sysconfig - - -LIBJPEG_SRC = os.path.join('pylibjpeg', 'src', 'libjpeg') -PYLIBJPEG_SRC = os.path.join('pylibjpeg', 'src', 'pylibjpeg') - - -# Workaround for needing cython and numpy -# Solution from: https://stackoverflow.com/a/54128391/12606901 -class build(build_orig): - def finalize_options(self): - super().finalize_options() - __builtins__.__NUMPY_SETUP__ = False - - import numpy - for ext in self.distribution.ext_modules: - if ext in extensions: - ext.include_dirs.append(numpy.get_include()) - - -def get_mscv_args(): - """Return a list of compiler args for MSVC++'s compiler.""" - flags = [ - '/GS', # Buffer security check - '/W3', # Warning level - '/wd"4335"', # Ignore warning 4335 - '/Zc:wchar_t', # Use windows char type - '/Zc:inline', # Remove unreferenced function or data (...) - '/Zc:forScope', - '/Od', # Disable optimisation - '/Oy-', # (x86 only) don't omit frame pointer - '/openmp-', # Disable #pragma omp directive - '/FC', # Display full path of source code files - '/fp:precise', # Floating-point behaviour - '/Gd', # (x86 only) use __cdecl calling convention - '/GF-', # Disable string pooling - '/GR', # Enable run-time type info - '/RTC1', # Enable run-time error checking - # /D defines constants and macros - '/D_UNICODE', - '/DUNICODE', - ] - # Set the architecture based on system architecture and Python - is_x64 = platform.architecture()[0] == '64bit' - if is_x64 and sys.maxsize > 2**32: - flags.append('/DWIN64=1') - else: - # Architecture is 32-bit, or Python is 32-bit - flags.append('/DWIN32=1') - - return flags - - -def get_gcc_args(): - """Return a list of compiler and linker args for GCC/clang. - - The args are determined by running the src/libjpeg/configure script then - parsing src/libjpeg/automakefile for the relevant values. - - Returns - ------- - dict - A dict with keys COMPILER_CMD, CC_ONLY, SETTINGS, PREFIX, - PTHREADCFLAGS, PTHREADLDFLAGS, PTHREADLIBS, HWTYPE, HAVE_ADDONS, - BITSIZE, ADDOPTS, LIB_OPTS, EXTRA_LIBS, CPU, TUNE. - """ - # Run configure script once - # Using GCC or clang, run `configure` bash script once - if 'config.log' not in os.listdir(LIBJPEG_SRC): - # Needs to be determined before changing the working dir - fpath = os.path.abspath(LIBJPEG_SRC) - # Needs to be run from within the src/libjpeg directory - current_dir = os.getcwd() - os.chdir(LIBJPEG_SRC) - subprocess.call([os.path.join(fpath, 'configure')]) - os.chdir(current_dir) - - # Get compilation options - with open(os.path.join(LIBJPEG_SRC, 'automakefile')) as fp: - lines = fp.readlines() - - lines = [ll for ll in lines if not ll.startswith('#')] - opts = [ll.split('=', 1) for ll in lines] - opts = {vv[0].strip():list(vv[1].strip().split(' ')) for vv in opts} - - return opts - - -def get_source_files(): - """Return a list of paths to the source files to be compiled.""" - source_files = [ - 'pylibjpeg/_libjpeg.pyx', - os.path.join(PYLIBJPEG_SRC, 'decode.cpp'), - os.path.join(PYLIBJPEG_SRC, 'streamhook.cpp'), - ] - for fname in Path(LIBJPEG_SRC).glob('*/*'): - if '.cpp' in str(fname): - source_files.append(str(fname)) - - return source_files - - -# Compiler and linker arguments -extra_compile_args = [] -extra_link_args = [] -if platform.system() == 'Windows': - os.environ['LIB'] = os.path.abspath( - os.path.join(sys.executable, '../', 'libs') - ) - extra_compile_args = get_mscv_args() -elif platform.system() in ['Darwin', 'Linux']: - opts = get_gcc_args() - extra_compile_args += opts['ADDOPTS'] - extra_link_args += opts['EXTRA_LIBS'] - +import sys -extensions = [ - Extension( - '_libjpeg', - get_source_files(), - language='c++', - include_dirs=[ - LIBJPEG_SRC, - PYLIBJPEG_SRC, - distutils.sysconfig.get_python_inc(), - # Numpy includes get added by the `build` subclass - ], - extra_compile_args=extra_compile_args, - extra_link_args=extra_link_args, - ) -] VERSION_FILE = os.path.join('pylibjpeg', '_version.py') with open(VERSION_FILE) as fp: @@ -150,8 +13,8 @@ def get_source_files(): setup( name = 'pylibjpeg', description = ( - "A Python wrapper for libjpeg, with a focus on JPEG support " - "for pydicom" + "A Python framework for decoding JPEG files, with a focus on " + "supporting pydicom" ), long_description = long_description, long_description_content_type = 'text/markdown', @@ -159,17 +22,17 @@ def get_source_files(): author = "scaramallion", author_email = "scaramallion@users.noreply.github.com", url = "https://github.com/pydicom/pylibjpeg", - license = "GPL V3.0", + license = "MIT", keywords = ( "dicom pydicom python medicalimaging radiotherapy oncology imaging " - "jpg jpeg jpg-ls jpeg-ls libjpeg pylibjpeg" + "jpg jpeg pylibjpeg" ), project_urls = { # Might give it it's own docs eventually 'Documentation' : 'https://pydicom.github.io/pydicom/' }, classifiers = [ - "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", + "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", "Intended Audience :: Healthcare Industry", "Intended Audience :: Science/Research", @@ -177,23 +40,15 @@ def get_source_files(): #"Development Status :: 4 - Beta", #"Development Status :: 5 - Production/Stable", "Natural Language :: English", - "Programming Language :: C++", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", - "Operating System :: MacOS :: MacOS X", # Tested OK - "Operating System :: POSIX :: Linux", # Tested OK - "Operating System :: Microsoft :: Windows", # Tested OK + "Operating System :: OS Independent", "Topic :: Scientific/Engineering :: Medical Science Apps.", "Topic :: Software Development :: Libraries", ], packages = find_packages(), - package_data = {'': ['*.txt', '*.cpp', '*.h', '*.hpp', '*.pyx']}, include_package_data = True, zip_safe = False, python_requires = ">=3.6", - setup_requires = ['setuptools>=18.0', 'cython', 'numpy'], - install_requires = ['cython', "numpy"], - cmdclass = {'build': build}, - ext_modules = extensions, ) From 2c0b77cbd638ef7e9259b5f6a30de160541237fb Mon Sep 17 00:00:00 2001 From: scaramallion Date: Wed, 11 Mar 2020 10:08:54 +1100 Subject: [PATCH 2/4] Merge in tools --- .coveragerc | 1 + codecov.yml | 1 + pylibjpeg/tools/__init__.py | 0 pylibjpeg/tools/jpegio.py | 53 +++ pylibjpeg/tools/s10918/__init__.py | 2 + pylibjpeg/tools/s10918/_markers.py | 83 +++++ pylibjpeg/tools/s10918/_parsers.py | 491 ++++++++++++++++++++++++++++ pylibjpeg/tools/s10918/_printers.py | 401 +++++++++++++++++++++++ pylibjpeg/tools/s10918/io.py | 140 ++++++++ pylibjpeg/tools/s10918/rep.py | 430 ++++++++++++++++++++++++ pylibjpeg/tools/tests/__init__.py | 0 pylibjpeg/tools/tests/test_utils.py | 82 +++++ pylibjpeg/tools/utils.py | 43 +++ 13 files changed, 1727 insertions(+) create mode 100644 pylibjpeg/tools/__init__.py create mode 100644 pylibjpeg/tools/jpegio.py create mode 100644 pylibjpeg/tools/s10918/__init__.py create mode 100644 pylibjpeg/tools/s10918/_markers.py create mode 100644 pylibjpeg/tools/s10918/_parsers.py create mode 100644 pylibjpeg/tools/s10918/_printers.py create mode 100644 pylibjpeg/tools/s10918/io.py create mode 100644 pylibjpeg/tools/s10918/rep.py create mode 100644 pylibjpeg/tools/tests/__init__.py create mode 100644 pylibjpeg/tools/tests/test_utils.py create mode 100644 pylibjpeg/tools/utils.py diff --git a/.coveragerc b/.coveragerc index 70d6069..f62cb3b 100644 --- a/.coveragerc +++ b/.coveragerc @@ -2,6 +2,7 @@ omit = pylibjpeg/tests/* pylibjpeg/scripts/* + pylibjpeg/tools/* pylibjpeg-data/* pylibjpeg-libjpeg/* pydicom/* diff --git a/codecov.yml b/codecov.yml index 23a28b2..1c7eec4 100644 --- a/codecov.yml +++ b/codecov.yml @@ -14,6 +14,7 @@ coverage: ignore: - "pylibjpeg/tests" - "pylibjpeg/scripts" + - "pylibjpeg/tools" - "pylibjpeg-libjpeg" - "pylibjpeg-data" - "pydicom" diff --git a/pylibjpeg/tools/__init__.py b/pylibjpeg/tools/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pylibjpeg/tools/jpegio.py b/pylibjpeg/tools/jpegio.py new file mode 100644 index 0000000..ff30e62 --- /dev/null +++ b/pylibjpeg/tools/jpegio.py @@ -0,0 +1,53 @@ + +import logging + +from .s10918 import parse, JPEG + + +LOGGER = logging.getLogger('pylibjpeg.tools.jpegio') +PARSERS = { + '10918' : (parse, JPEG), +} + + +def get_specification(fp): + """ + """ + if fp.read(1) != b'\xff': + raise ValueError('File is not JPEG') + + # Skip any initial fill bytes + while fp.read(1) == b'\xff': + pass + + fp.seek(-2, 1) + + # Confirm SOI marker + marker = fp.read(2) + + if marker == b'\xFF\xD8': + fp.seek(0) + return '10918' + + raise NotImplementedError( + "Reading a JPEG file with first marker '0x{}' is not supported" + .format(marker) + ) + + +def jpgread(fpath): + """Return a represention of the JPEG file at `fpath`.""" + LOGGER.debug("Reading file: {}".format(fpath)) + if isinstance(fpath, str): + with open(fpath, 'rb') as fp: + jpg_format = get_specification(fp) + parser, jpg_class = PARSERS[jpg_format] + meta = parser(fp) + LOGGER.debug("File parsed successfully") + else: + jpg_format = get_specification(fpath) + parser, jpg_class = PARSERS[jpg_format] + meta = parser(fpath) + LOGGER.debug("File parsed successfully") + + return jpg_class(meta) diff --git a/pylibjpeg/tools/s10918/__init__.py b/pylibjpeg/tools/s10918/__init__.py new file mode 100644 index 0000000..9b62df1 --- /dev/null +++ b/pylibjpeg/tools/s10918/__init__.py @@ -0,0 +1,2 @@ +from .io import parse +from .rep import JPEG diff --git a/pylibjpeg/tools/s10918/_markers.py b/pylibjpeg/tools/s10918/_markers.py new file mode 100644 index 0000000..59c44a2 --- /dev/null +++ b/pylibjpeg/tools/s10918/_markers.py @@ -0,0 +1,83 @@ +"""JPEG 10918 markers""" + +from ._parsers import * + +MARKERS = {} +# JPEG reserved markers +for _marker in range(0xFF02, 0xFFBF + 1): + MARKERS[_marker] = ('RES', 'Reserved', None) + +MARKERS.update({ + 0xFF01 : ('TEM', 'For temporary private use in artithmetic coding', None), + # Start of frame markers, non-differential, Huffman coding + 0xFFC0 : ('SOF0', 'Baseline DCT', SOF), + 0xFFC1 : ('SOF1', 'Extended sequential DCT', SOF), + 0xFFC2 : ('SOF2', 'Progressive DCT', SOF), + 0xFFC3 : ('SOF3', 'Lossless (sequential)', SOF), + # Huffman table specification + 0xFFC4 : ('DHT', 'Define Huffman table(s)', DHT), + # Start of frame markers, differential, Huffman coding + 0xFFC5 : ('SOF5', 'Differential sequential DCT', SOF), + 0xFFC6 : ('SOF6', 'Differential progressive DCT', SOF), + 0xFFC7 : ('SOF7', 'Differential lossless (sequential)', SOF), + # Start of frame markers, non-differential, arithmetic coding + 0xFFC8 : ('JPG', 'Reserved for JPEG extensions', None), + 0xFFC9 : ('SOF9', 'Extended sequential DCT', SOF), + 0xFFCA : ('SOF10', 'Progressive DCT', SOF), + 0xFFCB : ('SOF11', 'Lossless (sequential)', SOF), + # Define arithmetic coding conditioning(s) + 0xFFCC : ('DAC', 'Define arithmetic coding conditioning(s)', DAC), + # Start of frame markers, differential, arithmetic coding + 0xFFCD : ('SOF13', 'Differential sequential DCT', SOF), + 0xFFCE : ('SOF14', 'Differential progressive DCT', SOF), + 0xFFCF : ('SOF15', 'Differential lossless (sequential)', SOF), + # Restart interval termination + 0xFFD0 : ('RST0', 'Restart with modulo 8, count "0"', None), + 0xFFD1 : ('RST1', 'Restart with modulo 8, count "1"', None), + 0xFFD2 : ('RST2', 'Restart with modulo 8, count "2"', None), + 0xFFD3 : ('RST3', 'Restart with modulo 8, count "3"', None), + 0xFFD4 : ('RST4', 'Restart with modulo 8, count "4"', None), + 0xFFD5 : ('RST5', 'Restart with modulo 8, count "5"', None), + 0xFFD6 : ('RST6', 'Restart with modulo 8, count "6"', None), + 0xFFD7 : ('RST7', 'Restart with modulo 8, count "7"', None), + # Other markers + 0xFFD8 : ('SOI', 'Start of image', None), + 0xFFD9 : ('EOI', 'End of image', None), + 0xFFDA : ('SOS', 'Start of scan', SOS), + 0xFFDB : ('DQT', 'Define quantization table(s)', DQT), + 0xFFDC : ('DNL', 'Define number of lines', DNL), + 0xFFDD : ('DRI', 'Define restart interval', DRI), + 0xFFDE : ('DHP', 'Define hierarchical progression', SOF), # Identical + 0xFFDF : ('EXP', 'Expand reference component(s)', EXP), + 0xFFE0 : ('APP0', 'Reserved for application segments', APP), + 0xFFE1 : ('APP1', 'Reserved for application segments', APP), + 0xFFE2 : ('APP2', 'Reserved for application segments', APP), + 0xFFE3 : ('APP3', 'Reserved for application segments', APP), + 0xFFE4 : ('APP4', 'Reserved for application segments', APP), + 0xFFE5 : ('APP5', 'Reserved for application segments', APP), + 0xFFE6 : ('APP6', 'Reserved for application segments', APP), + 0xFFE7 : ('APP7', 'Reserved for application segments', APP), + 0xFFE8 : ('APP8', 'Reserved for application segments', APP), + 0xFFE9 : ('APP9', 'Reserved for application segments', APP), + 0xFFEA : ('APP10', 'Reserved for application segments', APP), + 0xFFEB : ('APP11', 'Reserved for application segments', APP), + 0xFFEC : ('APP12', 'Reserved for application segments', APP), + 0xFFED : ('APP13', 'Reserved for application segments', APP), + 0xFFEE : ('APP14', 'Reserved for application segments', APP), + 0xFFEF : ('APP15', 'Reserved for application segments', APP), + 0xFFF0 : ('JPG0', 'Reserved for JPEG extensions', None), + 0xFFF1 : ('JPG1', 'Reserved for JPEG extensions', None), + 0xFFF2 : ('JPG2', 'Reserved for JPEG extensions', None), + 0xFFF3 : ('JPG3', 'Reserved for JPEG extensions', None), + 0xFFF4 : ('JPG4', 'Reserved for JPEG extensions', None), + 0xFFF5 : ('JPG5', 'Reserved for JPEG extensions', None), + 0xFFF6 : ('JPG6', 'Reserved for JPEG extensions', None), + 0xFFF7 : ('JPG7', 'Reserved for JPEG extensions', None), + 0xFFF8 : ('JPG8', 'Reserved for JPEG extensions', None), + 0xFFF9 : ('JPG9', 'Reserved for JPEG extensions', None), + 0xFFFA : ('JPG10', 'Reserved for JPEG extensions', None), + 0xFFFB : ('JPG11', 'Reserved for JPEG extensions', None), + 0xFFFC : ('JPG12', 'Reserved for JPEG extensions', None), + 0xFFFD : ('JPG13', 'Reserved for JPEG extensions', None), + 0xFFFE : ('COM', 'Comment', COM), +}) diff --git a/pylibjpeg/tools/s10918/_parsers.py b/pylibjpeg/tools/s10918/_parsers.py new file mode 100644 index 0000000..134bdf6 --- /dev/null +++ b/pylibjpeg/tools/s10918/_parsers.py @@ -0,0 +1,491 @@ +"""Parsers for 10918 JPEG segments. + +For parameters which are 2 bytes, the most significant byte shall come first +in the compressed data's ordered sequence of bytes. Parameters which are 4 +bits in length always come in pairs and the pair shall always be encoded as +a single byte. The first 4-bit parameter of the pair shall occupy the most +significant 4 bits of the byte. Within and 16-, 8- or 4-bit parameter the +MSB shall come first and the LSB shall come last. + +BIG ENDIAN. + +Non-hierarchical + +SOI | Frame | EOI + +Frame +[Tables/misc] | SOF Frame header | Scan_1 | [DNL segment] | [Scan_2] ... | [Scan_n] | + +Scan +[Tables/misc] | Scan header | [ECS_0 | RST_0 | ... | RST_n] | ECS_n | + +ECS +, , ..., + +---------------------------------------------------------- + +**Marker Segments** + +A marker segments consists of a marker followed by a sequence of related +parameters. The first parameter is the two-byte length parameter, which encodes +the number of bytes in the marker segment (including the length parameter and +excluding the two-byte marker). + +The SOF and SOS marker segments are referred to as the frame header and the +scan header, respectively. + +See ISO/IEC 10918-1, Section B.1.1.4 + +The following marker segments are supported: + +* APP +* COM +* DAC +* DHT +* DNL +* DQT +* DRI +* EXP +* SOF +* SOS +""" + +from struct import unpack + +from tools.utils import split_byte + + +def APP(fp): + """Return a dict containing APP data. + + See ISO/IEC 10918-1 Section B.2.4.6. + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + + Returns + ------- + dict + A dict with keys: + + * ``Lp`` : application data segment length + * ``Ap`` : application data + """ + length = unpack('>H', fp.read(2))[0] + + return {'Lp' : length, 'Ap' : fp.read(length - 2)} + + +def COM(fp): + """Return a dict containing COM data. + + See ISO/IEC 10918-1 Section B.2.4.5. + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + + Returns + ------- + dict + A dict with keys: + + * ``Lc`` : comment data segment length + * ``Cm`` : comment bytes + """ + length = unpack('>H', fp.read(2))[0] + comment = unpack('{}s'.format(length - 2), fp.read(length - 2))[0] + + return {'Lc' : length, 'Cm' : comment} + + +def DAC(fp): + """Return a dict containing DAC segment data. + + See ISO/IEC 10918-1 Section B.2.4.3. + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + + Returns + ------- + dict + A dict with keys: + + * ``La`` : arithmetic coding conditioning definition length + * ``Tc`` : table class (0 for DC or lossless, 1 for AC) + * ``Tb`` : arithmetic coding conditioning table destination identifier + * ``Cs`` : conditioning table value + """ + length = unpack('>H', fp.read(2))[0] + bytes_to_read = length - 2 + + tc, tb, cs = [], [], [] + while bytes_to_read > 0: + _tc, _tb = split_byte(fp.read(1)) + cs.append(unpack('>B', fp.read(1))[0]) + tc.append(_tc) + tb.append(_tb) + + bytes_to_read -= 2 + + return {'La' : length, 'Tc' : tc, 'Tb' : tb, 'Cs' : cs} + + +def DHT(fp): + """Return a dict containing DHT segment data. + + See ISO/IEC 10918-1 Section B.2.4.2. + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + + Returns + ------- + dict + A dict with keys: + + * ``Lh`` : Huffman table definition length + * ``Tc`` : table class (0 for DC or lossless, 1 for AC) + * ``Th`` : Huffman table destination identifier, one of four possible + destinations at the decoder into which the table shall be installed + * ``Li`` : number of Huffman codes of length *i*, equivalent to the + list *BITS* + * ``Vij`` : value associated with each Huffman code of length *i*, + equivalent to *HUFFVAL* + """ + length = unpack('>H', fp.read(2))[0] + bytes_to_read = length - 2 + + tc, th, li = [], [], [] + vij = {} + while bytes_to_read > 0: + _tc, _th = split_byte(fp.read(1)) + tc.append(_tc) + th.append(_th) + + bytes_to_read -= 1 + + # li (BITS) is the number of codes for each code length, from 1 to 16 + _li = unpack('>16B', fp.read(16)) + bytes_to_read -= 16 + + # vij is a list of the 8-bit symbols values (HUFFVAL), each of which + # is assigned a Huffman code. + _vij = {} + for ii in range(16): + nr = _li[ii] + if nr: + _vij[ii + 1] = unpack('>{}B'.format(nr), fp.read(nr)) + bytes_to_read -= nr + + li.append(_li) + vij[(_tc, _th)] = _vij + + return {'Lh' : length, 'Tc' : tc, 'Th' : th, 'Li' : li, 'Vij' : vij} + + +def DNL(fp): + """Return a dict containing DNL segment data. + + See ISO/IEC 10918-1 Section B.2.5. + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + + Returns + ------- + dict + A dict with keys: + + * ``Ld`` : DNL segment length + * ``NL`` : number of lines in the frame + """ + length = unpack('>H', fp.read(2))[0] + nr_lines = unpack('>H', fp.read(2))[0] + + return {'Ld' : length, 'NL' : nr_lines} + + +def DQT(fp): + """Return a dict containing DQT segment data. + + See ISO/IEC 10918-1 Section B.2.4.1. + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + + Returns + ------- + dict + A dict with keys: + + * ``Lq`` : quantization table definition length + * ``Pq`` : quantization table element precision + * ``Tq`` : quantization table destination identifier + * ``Qk`` : quantization table element + """ + # length is 2 + sum(t=1, N) of (65 + 64 * Pq(t)) + length = unpack('>H', fp.read(2))[0] + bytes_to_read = length - 2 + + pq, tq, qk = [], [], [] + while bytes_to_read > 0: + precision, table_id = split_byte(fp.read(1)) + bytes_to_read -= 1 + pq.append(precision) + tq.append(table_id) + + if precision not in (0, 1): + raise ValueError( + "JPEG 10918 - DQT: invalid precision '{}'".format(precision) + ) + + # If Pq is 0, Qk is 8-bit, if Pq is 1, Qk is 16-bit + Q_k = [] + for ii in range(64): + if precision == 0: + Q_k.append(unpack('>B', fp.read(1))[0]) + bytes_to_read -= 1 + elif precision == 1: + Q_k.append(unpack('>H', fp.read(2))[0]) + bytes_to_read -= 2 + + qk.append(Q_k) + + return {'Lq' : length, 'Pq' : pq, 'Tq' : tq, 'Qk' : qk} + + +def DRI(fp): + """Return a dict containing DRI segment data. + + See ISO/IEC 10918-1 Section B.2.4.4. + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + + Returns + ------- + dict + A dict with keys: + + * ``Lr`` : DRI segment length + * ``Ri`` : restart interval (number of MCU in the restart interval) + """ + return { + 'Lr' : unpack('>H', fp.read(2))[0], + 'Ri' : unpack('>H', fp.read(2))[0] + } + + +def EXP(fp): + """Return a dict containing EXP segment data. + + See ISO/IEC 10918-1 Section B.3.3. + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + + Returns + ------- + dict + A dict with keys: + + * ``Le`` : EXP segment length + * ``Eh`` : expand horizontally + * ``Ev`` : expand vertically + """ + length = unpack('>H', fp.read(2))[0] + eh, ev = split_byte(unpack('>B', fp.read(1))[0]) + + return {'Le' : length, 'Eh' : eh, 'Ev' : ev} + + +def SOF(fp): + """Return a dict containing SOF header data. + + See ISO/IEC 10918-1 Section B.2.2. + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + + Returns + ------- + dict + A dict with keys: + + * ``Lf`` : frame header length + * ``P`` : sample precision + * ``Y`` : number of lines + * ``X`` : number of samples per line + * ``Nf`` : number of image components in frame + * ``Ci`` : component identifier + * ``Hi`` : horizontal sampling factor + * ``Vi`` : vertical sampling factor + * ``Tqi`` : quantization table destination selector + """ + (length, + precision, + nr_lines, + samples_per_line, + nr_components) = unpack('>HBHHB', fp.read(8)) + + component_id = {} + #horizontal_sampling_factor = [] + #vertical_sampling_factor = [] + #quantisation_selector = [] + for ii in range(nr_components): + _ci = unpack('>B', fp.read(1))[0] + _hor, _vert = split_byte(fp.read(1)) + #horizontal_sampling_factor.append(_hor) + #vertical_sampling_factor.append(_vert) + _tqi = unpack('>B', fp.read(1))[0] + #quantisation_selector.append(_tqi) + + component_id[_ci] = { + 'Hi' : _hor, + 'Vi' : _vert, + 'Tqi' : _tqi, + } + + return { + 'Lf' : length, + 'P' : precision, + 'Y' : nr_lines, + 'X' : samples_per_line, + 'Nf' : nr_components, + 'Ci' : component_id, + } + + +def SOS(fp): + """Return a dict containing SOS header data. + + See ISO/IEC 10918-1 Section B.2.3. + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + + Returns + ------- + dict + A dict with keys: + + * ``Ls`` : scan header length + * ``Ns`` : number of image components in scan + * ``Csj`` : scan component selector + * ``Tdj`` : DC entropy coding table destination selector. + * ``Taj`` : AC entropy coding table destination selector. Set to 0 for + lossless. + * ``Ss`` : start of spectral or predictor selection. Shall be 0 for + sequential DCT, for lossless this is the predictor. + * ``Se`` : end of spectral selection. Shall be 63 for sequential DCT. + In lossless this has no meaning and shall be set to 0. + * ``Ah`` : successive approximation bit position high. In lossless + this has no meaning and shall be set to 0. + * ``Al`` : successive approximation bit position low or point transform + Shall be set to 0 for sequential DCT. In lossless mode specifies + the point transform Pt. + """ + (length, nr_components) = unpack('>HB', fp.read(3)) + + csj, tdj, taj, tmj = [], [], [], [] + for ii in range(nr_components): + _cs = unpack('>B', fp.read(1))[0] + csj.append(_cs) + _td, _ta = split_byte(fp.read(1)) + tdj.append(_td) + taj.append(_ta) + + + (ss, se) = unpack('>BB', fp.read(2)) + ah, al = split_byte(fp.read(1)) + + return { + 'Ls' : length, + 'Ns' : nr_components, + 'Csj' : csj, + 'Tdj' : tdj, + 'Taj' : taj, + 'Ss' : ss, + 'Se' : se, + 'Ah' : ah, + 'Al' : al, + } + + +def skip(fp): + """Skip the next N - 2 bytes. + + See ISO/IEC 10918-1 Section ??? + + After returning, `fp` will be positioned at the end of the current marker + segment. + + Parameters + ---------- + fp : file-life + A file-like positioned at the start of the length byte for the current + marker segment. + """ + length = unpack('>H', fp.read(2))[0] + fp.seek(length - 2, 1) diff --git a/pylibjpeg/tools/s10918/_printers.py b/pylibjpeg/tools/s10918/_printers.py new file mode 100644 index 0000000..16e510e --- /dev/null +++ b/pylibjpeg/tools/s10918/_printers.py @@ -0,0 +1,401 @@ +"""Printing functions for 10918 JPEG marker segments. + +The following segments are supported: + +* APP : 0xFFE0 to 0xFFEF +* COM : 0xFFFE +* DAC : 0xFFCC +* DHP : 0xFFDE +* DHT : 0xFFC4 +* DQT : 0xFFDB +* DNL : 0xFFDC +* DRI : 0xFFDD +* EOI : 0xFFD9 +* EXP : 0xFFDF +* SOF : 0xFFC0 to 0xFFC3, 0xFFC5 to 0xFFC7, 0xFFC9 to 0xFFCB, 0xFFCD to 0xFFCF +* SOI : 0xFFD8 +* SOS : 0xFFDA +""" + +from struct import unpack + + +ZIGZAG = [ + 0, 1, 5, 6, 14, 15, 27, 28, + 2, 4, 7, 13, 16, 26, 29, 42, + 3, 8, 12, 17, 25, 30, 41, 43, + 9, 11, 18, 24, 31, 40, 44, 53, + 10, 19, 23, 32, 39, 45, 52, 54, + 20, 22, 33, 38, 46, 51, 55, 60, + 21, 34, 37, 47, 50, 56, 59, 61, + 35, 36, 48, 49, 57, 58, 62, 63 +] +# ASCII codes for CMYK, RGB +_COMMON_COMPONENT_IDS = { + 66 : 'B', 67 : 'C', 71 : 'G', 75 : 'K', 77 : 'M', 82 : 'R', + 89 : 'Y', +} + + +def _print_app(marker, offset, info): + """String output for an APP segment.""" + _, _, info = info + + ss = [] + ss.append( + '\n{:-^63}'.format(' {} marker at offset {}, length {} ' + .format(marker, offset, info['Lp'] + 2)) + ) + + app_data = info['Ap'] + if app_data[:5] == b'\x4a\x46\x49\x46\x00': + # JFIF https://en.wikipendia.org/wiki/JPEG_File_Interchange_Format + version = (app_data[5], app_data[6]) + # density units, 0: no units, 1: px/inch: 2 px/cm + units = unpack('B', app_data[7:8])[0] + if units == 0: + units = 'unitless' + elif units == 1: + units = 'px/inch' + elif units == 2: + units = 'px/cm' + # horizontal/vertical px density + x = unpack('>H', app_data[8:10])[0] + y = unpack('>H', app_data[10:12])[0] + # Thumbnail horizontal/vertical pixel count + width, height = unpack('BB', app_data[12:14]) + # Thumbnail data + thumbnail = app_data[14:] + if width != 0 and height != 0: + ss.append( + 'JFIF v{}.{}, {}, ({}, {}), {} by {} px' + .format(*version, units, x, y, width, height) + ) + else: + ss.append('JFIF v{}.{}, no thumbnail'.format(*version)) + + if thumbnail: + data = ' '.join(['{:02x}'.format(cc) for cc in thumbnail]) + for ii in range(0, len(data), 60): + ss.append(' {}'.format(data[ii:ii + 60])) + + elif app_data[:6] == b'\x45\x78\x69\x66\x00\x00': + ss.append('EXIF:') + data = ' '.join(['{:02x}'.format(cc) for cc in app_data[6:]]) + for ii in range(0, len(data), 60): + ss.append(' {}'.format(data[ii:ii + 60])) + elif app_data[:6] == b'\x41\x64\x6f\x62\x65\x00': + # Adobe + ss.append('Adobe v{}:'.format(app_data[6])) + data = ' '.join(['{:02x}'.format(cc) for cc in app_data[6:]]) + for ii in range(0, len(data), 60): + ss.append(' {}'.format(data[ii:ii + 60])) + else: + # Unknown + ss.append('Unknown APP data') + data = ['{:02x}'.format(cc) for cc in app_data] + for ii in range(0, len(data), 20): + ss.append(' {}'.format(' '.join(data[ii:ii + 20]))) + + return '\n'.join(ss) + + +def _print_com(marker, offset, info): + """String output for a COM segment.""" + _m, fill, info = info + ss = [] + ss.append( + '\n{:-^63}'.format(' {} marker at offset {}, length {} ' + .format(marker, offset, info['Lc'] + 2)) + ) + + comment = "'" + info['Cm'].decode('utf-8') + "'" + ss.append("{}".format(comment[:47])) + comment = comment[47:] + + while True: + if not comment: + break + line = comment[:63] + comment = comment[63:] + + ss.append(" {}".format(line)) + + return '\n'.join(ss) + + +def _print_dac(marker, offset, info): + """String output for a DAC segment.""" + m_bytes, fill, info = info + ss = [] + ss.append( + '\n{:-^63}'.format( + ' {} marker at offset {}, length {} ' + .format(marker, offset, info['La'] + 2) + ) + ) + ss.append( + "Tc={}, Tb={}, Cs={}".format(info['Tc'], info['Tb'], info['Cs']) + ) + + return '\n'.join(ss) + + +def _print_dhp(marker, offset, info): + """String output for a DHP segment.""" + m_bytes, fill, info = info + ss = [] + ss.append( + '\n{:-^63}'.format(' {} marker at offset {}, length {} ' + .format(marker, offset, info['Lf'] + 2)) + ) + + ss.append('Sample size (px): {} x {}'.format(info['X'], info['Y'])) + ss.append('Sample precision (bits): {}'.format(info['P'])) + ss.append('Number of component images: {}'.format(info['Nf'])) + + for ci, vv in info['Ci'].items(): + h, v, tqi = vv['Hi'], vv['Vi'], vv['Tqi'] + try: + ci = _COMMON_COMPONENT_IDS[ci] + except KeyError: + pass + ss.append(' Component ID: {}'.format(ci)) + ss.append(' Horizontal sampling factor: {}'.format(h)) + ss.append(' Vertical sampling factor: {}'.format(v)) + ss.append(' Quantization table destination: {}'.format(tqi)) + + return '\n'.join(ss) + + +def _print_dht(marker, offset, info): + """String output for a DHT segment.""" + _m, fill, info = info + ss = [] + ss.append( + '\n{:-^63}'.format(' {} marker at offset {}, length {} ' + .format(marker, offset, info['Lh'] + 2)) + ) + + for tc, th, li in zip(info['Tc'], info['Th'], info['Li']): + vij = info['Vij'][(tc, th)] + if tc == 0: + ss.append('Lossless/DC Huffman, table ID: {}'.format(th)) + elif tc == 1: + ss.append('AC Huffman, table ID: {}'.format(th)) + else: + raise NotImplementedError + + ss.append(' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16') + nr_values = ' '.join(['{:>02x}'.format(val) for val in li]) + ss.append(' {} : # codes'.format(nr_values)) + + for ii, (kk, values) in enumerate(vij.items()): + if values is not None: + for jj in range(0, len(values), 16): + vals = ['{:>02x}'.format(vv) for vv in values[jj:jj + 16]] + val = ' '.join(vals) + ss.append(' {:<47} : L = {}'.format(val, kk)) + + return '\n'.join(ss) + + +def _print_dqt(marker, offset, info): + """String output for a DQT segment.""" + _m, fill, info = info + ss = [] + ss.append( + '\n{:-^63}'.format(' {} marker at offset {}, length {} ' + .format(marker, offset, info['Lq'] + 2)) + ) + for pq, tq, qk in zip(info['Pq'], info['Tq'], info['Qk']): + ss.append('Table destination ID: {}'.format(tq)) + if pq == 0: + ss.append('Table precision: {} (8-bit)'.format(pq)) + else: + ss.append('Table precision: {} (16-bit)'.format(pq)) + + new_qk = [] + for index in ZIGZAG: + new_qk.append(qk[index]) + + ss.append('Quantization table:') + for ii in range(0, 64, 8): + if not pq: + # 8-bit + table_rows = ['{:>2}'.format(qq) for qq in new_qk[ii:ii + 8]] + else: + # 16-bit + table_rows = ['{:>3}'.format(qq) for qq in new_qk[ii:ii + 8]] + + ss.append(' {}'.format(' '.join(table_rows))) + + return '\n'.join(ss) + + +def _print_dnl(marker, offset, info): + """String output for a DNL segment.""" + m_bytes, fill, info = info + ss = [] + ss.append( + '\n{:-^63}'.format( + ' {} marker at offset {}, length {} ' + .format(marker, offset, info['Ld'] + 2) + ) + ) + ss.append("NL={}".format(info['NL'])) + + return '\n'.join(ss) + + +def _print_dri(marker, offset, info): + """String output for a DRI segment.""" + m_bytes, fill, info = info + ss = [] + ss.append( + '\n{:-^63}'.format(' {} marker at offset {}, length {} ' + .format(marker, offset, info['Lr'] + 2)) + ) + ss.append( + "Ri={}".format(info['Ri']) + ) + return '\n'.join(ss) + + +def _print_eoi(marker, offset, info): + """String output for an EOI segment.""" + return ( + '\n{:=^63}'.format(' {} marker at offset {} '.format(marker, offset)) + ) + + +def _print_exp(marker, offset, info): + """String output for an EXP segment.""" + m_bytes, fill, info = info + ss = [] + ss.append( + '\n{:-^63}'.format( + ' {} marker at offset {}, length {} ' + .format(marker, offset, info['Le'] + 2) + ) + ) + ss.append("Eh={}, Ev={}".format(info['Eh'], info['Ev'])) + + return '\n'.join(ss) + + +def _print_sof(marker, offset, info): + """String output for a SOF segment.""" + m_bytes, fill, info = info + ss = [] + ss.append( + '\n{:-^63}'.format(' {} marker at offset {}, length {} ' + .format(marker, offset, info['Lf'] + 2)) + ) + + sof_type = { + 0xFFC0: 'Baseline sequential DCT', # SOF0 + 0xFFC1: 'Extended sequential DCT, Huffman coding', # SOF1 + 0xFFC2: 'Progressive DCT, Huffman coding', # SOF2 + 0xFFC3: 'Lossless (sequential), Huffman coding', # SOF3 + 0xFFC5: 'Differential sequential DCT, Huffman coding', # SOF5 + 0xFFC6: 'Differential progressive DCT, Huffman coding', # SOF6 + 0xFFC7: 'Differential lossless (sequential), Huffman coding', # SOF7 + 0xFFC9: 'Extended sequential DCT, arithmetic coding', # SOF9 + 0xFFCA: 'Progressive DCT, arithmetic coding', # SOF10 + 0xFFCB: 'Lossless (sequential), arithmetic coding', # SOF11 + 0xFFCD: 'Differential sequential DCT, arithmetic coding', # SOF13 + 0xFFCE: 'Differential progressive DCT, arithmetic coding', # SOF14 + 0xFFCF: 'Differential lossless (sequential), arithmetic coding', # SOF15 + } + + try: + ss.append('{}'.format(sof_type[m_bytes])) + except KeyError: + ss.append('Unknown SOF type: {}'.format(hex(m_bytes))) + + ss.append('Sample size (px): {} x {}'.format(info['X'], info['Y'])) + ss.append('Sample precision (bits): {}'.format(info['P'])) + ss.append('Number of component images: {}'.format(info['Nf'])) + + for ci, vv in info['Ci'].items(): + h, v, tqi = vv['Hi'], vv['Vi'], vv['Tqi'] + try: + ci = _COMMON_COMPONENT_IDS[ci] + except KeyError: + pass + ss.append(' Component ID: {}'.format(ci)) + ss.append(' Horizontal sampling factor: {}'.format(h)) + ss.append(' Vertical sampling factor: {}'.format(v)) + ss.append(' Quantization table destination: {}'.format(tqi)) + + return '\n'.join(ss) + + +def _print_soi(marker, offset, info): + """String output for a SOI segment.""" + return '\n{:=^63}'.format(' {} marker at offset {} '.format(marker, offset)) + + +def _print_sos(marker, offset, info): + """String output for a SOS segment.""" + _m, fill, info = info + ss = [] + ss.append( + '\n{:-^63}'.format(' {} marker at offset {}, length {} ' + .format(marker, offset, info['Ls'] + 2)) + ) + ss.append("Number of image components: {}".format(info['Ns'])) + + for csk, td, ta in zip(info['Csj'], info['Tdj'], info['Taj']): + try: + csk = _COMMON_COMPONENT_IDS[csk] + except KeyError: + pass + ss.append( + ' Component: {}, DC table: {}, AC table: {}'.format(csk, td, ta) + ) + + ss.append( + 'Spectral selectors start-end: {}-{}'.format(info['Ss'], info['Se']) + ) + ss.append( + 'Successive approximation bit high-low: {}-{}' + .format(info['Ah'], info['Al']) + ) + + # Write RST and encoded data lengths + remove = ['Ls', 'Ns', 'Csj', 'Tdj', 'Taj', 'Ss', 'Se', 'Ah', 'Al'] + keys = [kk for kk in info if kk not in remove] + for key in keys: + if key[0] == 'ENC': + ss.append( + '\n{:.^63}'.format(' ENC marker at offset {}'.format(key[1])) + ) + ss.append( + '\n{} bytes of entropy-coded data'.format(len(info[key])) + ) + else: + (name, offset) = key + ss.append( + '{:<7}{}({})'.format(offset, name, 'ffd{}'.format(name[-1])) + ) + + return '\n'.join(ss) + + +PRINTERS = { + 'APP' : _print_app, + 'COM' : _print_com, + 'DAC' : _print_dac, + 'DHP' : _print_dhp, + 'DHT' : _print_dht, + 'DQT' : _print_dqt, + 'DNL' : _print_dnl, + 'DRI' : _print_dri, + 'EOI' : _print_eoi, + 'EXP' : _print_exp, + 'SOF' : _print_sof, + 'SOI' : _print_soi, + 'SOS' : _print_sos, +} diff --git a/pylibjpeg/tools/s10918/io.py b/pylibjpeg/tools/s10918/io.py new file mode 100644 index 0000000..5c50ee1 --- /dev/null +++ b/pylibjpeg/tools/s10918/io.py @@ -0,0 +1,140 @@ +"""""" + +from functools import partial +import logging +from struct import unpack + +from ._markers import MARKERS + + +LOGGER = logging.getLogger('jpg') + + +def parse(fp): + """Return a JPEG but don't decode yet.""" + _fill_bytes = 0 + while fp.read(1) == b'\xff': + _fill_bytes += 1 + pass + + fp.seek(-2, 1) + + # Confirm SOI marker + if fp.read(2) != b'\xFF\xD8': + raise ValueError('SOI marker not found') + + info = { + ('SOI', fp.tell() - 2) : ( + unpack('>H', b'\xFF\xD8')[0], _fill_bytes, {} + ) + } + + END_OF_FILE = False + + while True: + _fill_bytes = 0 + + # Skip fill + next_byte = fp.read(1) + while next_byte == b'\xFF': + _fill_bytes += 1 + next_byte = fp.read(1) + + # Remove the byte thats actually part of the marker + if _fill_bytes: + _fill_bytes -= 1 + + fp.seek(-2, 1) + + _marker = unpack('>H', fp.read(2))[0] + + if _marker in MARKERS: + name, description, handler = MARKERS[_marker] + key = (name, fp.tell() - 2) + if name not in ['SOS', 'EOI']: + if handler is None: + length = unpack('>H', fp.read(2))[0] - 2 + fp.seek(length, 1) + continue + + info[key] = (_marker, _fill_bytes , handler(fp)) + + elif name is 'SOS': + # SOS's info dict contains an extra 'encoded_data' keys + # which use RSTN@offset and ENC@offset + info[key] = [_marker, _fill_bytes, handler(fp)] + + sos_info = {} + encoded_data = bytearray() + _enc_start = fp.tell() + + while True: + _enc_key = ('ENC', _enc_start - 2) + prev_byte = fp.read(1) + if prev_byte == b'': + END_OF_FILE = True + break + elif prev_byte != b'\xFF': + encoded_data.extend(prev_byte) + continue + + # To get here next_byte must be 0xFF + # If the next byte is 0x00 then keep reading + # If the next byte is 0xFF then keep reading until + # a non-0xFF byte is found + # If the marker is a RST marker then keep reading + # Otherwise rewind to the start of the fill bytes and break + + next_byte = fp.read(1) + if next_byte == b'\x00': + # Skip padding bytes + # The previous byte wasn't added so do it now + encoded_data.extend(prev_byte) + #encoded_data.extend(next_byte) + continue + + # To get here next_byte must be non-padding (non 0x00) + # so we must be at the end of the encoded data + info[key][2].update({_enc_key : encoded_data}) + encoded_data = bytearray() + + # The number of 0xFF bytes before the marker + # i.e. 0xFF 0xFF 0xFF 0xD9 is 2 fill bytes + _sos_fill_bytes = 0 + # While we still have 0xFF bytes + while next_byte == b'\xFF': + _sos_fill_bytes += 1 + next_byte = fp.read(1) + + # Check to see if marker is RST_m + if next_byte in [b'\xD0', b'\xD1', b'\xD2', b'\xD3', + b'\xD4', b'\xD5', b'\xD6', b'\xD7']: + _sos_marker = unpack('>H', b'\xFF' + next_byte)[0] + _sos_marker, _, _ = MARKERS[_sos_marker] + _sos_key = (_sos_marker, fp.tell() - 2) + info[key][2].update({_sos_key : None}) + + _enc_start = fp.tell() + continue + + # End of the current scan, rewind and break + # Back up to the start of the 0xFF + # Currently position at first byte after marker + fp.seek(-2 - _sos_fill_bytes, 1) + break + + elif name is 'EOI': + info[key] = (_marker, _fill_bytes, {}) + break + + else: + if not END_OF_FILE: + print( + 'Unknown marker {} at offset {}' + .format(hex(_marker), fp.tell() - 2) + ) + raise NotImplementedError + else: + break + + return info diff --git a/pylibjpeg/tools/s10918/rep.py b/pylibjpeg/tools/s10918/rep.py new file mode 100644 index 0000000..502de88 --- /dev/null +++ b/pylibjpeg/tools/s10918/rep.py @@ -0,0 +1,430 @@ + + +from ._printers import PRINTERS + + +class JPEG(object): + """A representation of an ISO/IEC 10918-1 JPEG file. + + **Non-hierarchical** + + **DCT-based sequential** + 1: Baseline DCT + 2: Extended sequential DCT, Huffman, 8-bit + 3: Extended sequential DCT, arithmetic, 8-bit + 4: Extended sequential DCT, Huffman, 12-bit + 5: Extended sequential DCT, arithmetic, 12-bit + + **DCT-based progressive** + 6: Spectral selection, Huffman, 8-bit + 7: Spectral selection, arithmetic, 8-bit + 8: Spectral selection, Huffman, 12-bit + 9: Spectral seletion, arithmetic, 12-bit + 10: Full progression, Huffman, 8-bit + 11: Full progression, arithmetic, 8-bit + 12: Full progression, Huffman, 12-bit + 13: Full progression, arithmetic, 12-bit + + **Lossless** + 14: Lossless, Huffman, 2 to 16-bit + 15: Lossless, arithmetic, 2 to 16-bit + + **Hierarchical** + + **DCT-based sequential** + 16: Extended sequential DCT, Huffman, 8-bit + 17: Extended sequential DCT, arithmetic, 8-bit + 18: Extended sequential DCT, Huffman, 12-bit + 19: Extended sequential DCT, arithmetic, 12-bit + + **DCT-based progressive** + 20: Spectral selection, Huffman, 8-bit + 21: Spectral selection, arithmetic, 8-bit + 22: Spectral selection, Huffman, 12-bit + 23: Spectral selection, arithmetic, 12-bit + 24: Full progression, Huffman, 8-bit + 25: Full progression, arithmetic, 8-bit + 26: Full progression, Huffman, 12-bit + 27: Full progression, arithmetic, 12-bit + + **Lossless** + 28: Lossless, Huffman, 2 to 16-bit + 29: Lossless, arithmetic, 2 to 16-bit + + """ + def __init__(self, meta): + """Initialise a new JPEG. + + Parameters + ---------- + meta : dict + The parsed JPEG image. + """ + self.info = meta + + @property + def columns(self): + """Return the number of columns in the image as an int.""" + keys = self.get_keys('SOF') + if keys: + return self.info[keys[0]][2]['X'] + + raise ValueError( + "Unable to get the number of columns in the image as no SOFn " + "marker was found" + ) + + def _decode(self): + """Decode the JPEG image data in place. + + Raises + ------ + NotImplementedError + If the JPEG image data is of a type for which decoding is not + supported. + """ + if not self.is_decodable: + raise NotImplementedError( + "Unable to decode the JPEG image data as it's of a type " + "for which decoding is not supported" + ) + + if self.is_process1: + decoder = decode_baseline + #elif self.is_process2: + # decoder = decode_extended_8 + #elif self.is_process4: + # decoder = decode_extended_12 + #elif self.is_process14: + # decoder = decode_lossless + #elif self.is_process14_sv1: + # decoder = decode_lossless + + try: + self._array = decoder(self) + self._array_id = id(self._array) + except Exception as exc: + self._array = None + self._array_id = None + raise exc + + def get_keys(self, name): + """Return a list of keys with marker containing `name`.""" + return [mm for mm in self._keys if name in mm[0]] + + @property + def is_baseline(self): + """Return True if the JPEG is baseline, False otherwise. + + Baseline process + * DCT-based process + * Each component of the source image has 8-bit samples + * Sequential + * Huffman coding has up to 2 AC and 2 DC tables + * Decoders shall process scans with 1, 2, 3 and 4 components + * Interleaved and non-interleaved scans + + Non-hierarchical baseline processes are: + 1 + Hierarchical baseline processes are: + 16, 17, 20, 21, 24, 25. + """ + return 'SOF0' in self.markers + + @property + def is_extended(self): + """Return True if the JPEG is extended, False otherwise. + + Extended DCT-based processess + * DCT-based process + * Each component of the source image has 8- or 12-bit samples + * Sequential or progressive + * Huffman or arithmetic coding with up to 4 AC and 4 DC tables + * Decoders shall process scans with 1, 2, 3 and 4 components + * Interleaved and non-interleaved scans + + Non-hierarchical extended processes are: + 2, 4 + Hierarchical extended processes are: + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 + """ + extended_markers = ('SOF1', 'SOF9', 'SOF5', 'SOF13') + if [mm for mm in extended_markers if mm in self.markers]: + return True + + return False + + @property + def is_hierarchical(self): + """Return True if the JPEG is hierarchical, False otherwise. + + Hierarchical processess + * Multiple frames (non-differential and differential) + * Uses extended DCT-based or lossless processes + * Decoders shall process scans with 1, 2, 3 and 4 components + * Interleaved and non-interleaved scans + """ + return 'DHP' in self.markers + + @property + def is_lossless(self): + """Return True if the JPEG is lossless, False otherwise. + + Lossless processess + * Predictive process (not DCT-based) + * Each component of the source image P-bit samples (2 <= P <= 16) + * Sequential + * Huffman or arithmetic coding with up to 4 DC tables + * Decoders shall process scans with 1, 2, 3 and 4 components + * Interleaved and non-interleaved scans + + Non-hierarchical lossless processes are: + 14, 15 + Hierarchical lossless processes are: + 28, 29 + """ + lossless_markers = ('SOF3', 'SOF11') #, 'SOF7', 'SOF15') + if [mm for mm in lossless_markers if mm in self.markers]: + return True + + return False + + # TODO: Remove + @property + def is_process1(self): + """Return True if the JPEG is Process 1, False otherwise.""" + if not self.is_hierarchical and self.is_baseline: + return True + + return False + + # TODO: Remove + @property + def is_process2(self): + """Return True if the JPEG is Process 2, False otherwise.""" + try: + precision = self.precision + except ValueError: + return False + + if not self.is_hierarchical and self.is_extended and precision == 8: + return True + + return False + + # TODO: Remove + @property + def is_process4(self): + """Return True if the JPEG is Process 4, False otherwise.""" + try: + precision = self.precision + except ValueError: + return False + + if not self.is_hierarchical and self.is_extended and precision == 12: + return True + + return False + + # TODO: Remove + @property + def is_process14(self): + """Return True if the JPEG is Process 14, False otherwise.""" + if 'SOF3' not in self.markers: + return False + + if not self.is_hierarchical and self.is_lossless: + return True + + raise False + + # TODO: Remove + @property + def is_process14_sv1(self): + """Return True if the JPEG is Process 14 SV1, False otherwise. + + Returns + ------- + bool + True if JPEG is process 14, first-order prediction, selection + value 1, False otherwise. + """ + if 'SOF3' not in self.markers: + return False + + if self.is_hierarchical or not self.is_lossless: + return False + + if self.selection_value == 1: + return True + + return False + + @property + def is_sequential(self): + return not self.is_hierarchical + + @property + def is_spectral(self): + pass + + @property + def _keys(self): + """Return a list of the info keys, ordered by offset.""" + return sorted(self.info.keys(), key=lambda x: x[1]) + + @property + def markers(self): + """Return a list of the found JPEG markers, ordered by offset.""" + return [mm[0] for mm in self._keys] + + @property + def precision(self): + """Return the precision of the sample as an int.""" + keys = self.get_keys('SOF') + if keys: + return self.info[keys[0]][2]['P'] + + raise ValueError( + "Unable to get the sample precision of the image as no SOFn " + "marker was found" + ) + + @property + def process(self): + """Return the process number as :class:`int`.""" + prec = self.precision + process = None + + if self.is_baseline: + # Baseline sequential DCT, 8-bit + return 1 + + if self.is_extended: + # Extended sequential DCT + if self.is_huffman and prec == 8: + process = 2 + elif self.is_arithmetic and prec == 8: + process = 3 + elif self.is_huffman and prec == 12: + process = 4 + elif self.is_arithmetic and prec == 12: + process = 5 + elif self.is_spectral: + # Spectral selection only + if self.is_huffman and prec == 8: + process = 6 + elif self.is_arithmetic and prec == 8: + process = 7 + elif self.is_huffman and prec == 12: + process = 8 + elif self.is_arithmetic and prec == 12: + process = 9 + elif self.full_progression: + # Full progression + if self.is_huffman and prec == 8: + process = 10 + elif self.is_arithmetic and prec == 8: + process = 11 + elif self.is_huffman and prec == 12: + process = 12 + elif self.is_arithmetic and prec == 12: + process = 13 + elif self.is_lossless: + # Lossless + if self.is_huffman and 2 <= prec <= 16: + process = 14 + elif self.is_arithmetic and 2 <= prec <= 16: + process = 15 + + if process is None: + raise ValueError("Unable to determine the JPEG process") + + if self.is_sequential: + return process + elif self.is_hierarchical: + return process + 14 + + @property + def rows(self): + """Return the number of rows in the image as an int.""" + keys = self.get_keys('SOF') + if keys: + return self.info[keys[0]][2]['Y'] + + raise ValueError( + "Unable to get the number of rows in the image as no SOFn " + "marker was found" + ) + + @property + def samples(self): + """Return the number of components in the JPEG as an int.""" + keys = self.get_keys('SOF') + if keys: + return self.info[keys[0]][2]['Nf'] + + raise ValueError( + "Unable to get the number of components in the image as no SOFn " + "marker was found" + ) + + @property + def selection_value(self): + """Return the JPEG lossless selection value. + + Returns + ------- + int + The selection value for the lossless prediction (0-7). 0 shall + only be used for differential coding in the hierarchical mode of + operation. 1-3 are one-dimensional predictors and 4-7 are two- + dimensional predictors. + + Raises + ------ + ValueError + If the JPEG is not lossless. + """ + if not self.is_lossless: + raise ValueError( + "Selection value is only available for lossless JPEG" + ) + + sos_markers = [mm for mm in self._keys if 'SOS' in mm] + return self.info[sos_markers[0]][2]['Ss'] + + def __str__(self): + """""" + ss = [] + for marker, offset in self.info: + info = self.info[(marker, offset)] + printer = PRINTERS[marker[:3]] + ss.append(printer(marker, offset, info)) + + return '\n'.join(ss) + + @property + def uid(self): + """Return the DICOM UID corresponding to the JPEG. + + Returns + ------- + uid.UID + The DICOM transfer syntax UID corresponding to the JPEG. + + Raises + ------ + ValueError + If the JPEG doesn't correspond to a DICOM transfer syntax. + """ + if self.is_process1: + return JPEGBaseline + elif self.is_process2 or self.is_process4: + return JPEGExtended + elif self.is_process14_sv1: + return JPEGLossless + elif self.is_process14: + return JPEGLosslessP14 + + raise ValueError("JPEG doesn't correspond to a DICOM UID") diff --git a/pylibjpeg/tools/tests/__init__.py b/pylibjpeg/tools/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pylibjpeg/tools/tests/test_utils.py b/pylibjpeg/tools/tests/test_utils.py new file mode 100644 index 0000000..925375d --- /dev/null +++ b/pylibjpeg/tools/tests/test_utils.py @@ -0,0 +1,82 @@ +"""Unit tests for utils.py""" + +import pytest + +from pylibjpeg.tools.utils import get_bit, split_byte + + +class TestGetBit(object): + """Tests for utils.get_bit(byte, index).""" + def test_out_of_range_raises(self): + """Test than an invalid `index` value raises an exception.""" + msg = r"'index' must be between 0 and 7, inclusive" + with pytest.raises(ValueError, match=msg): + get_bit(b'\x00', -1) + + with pytest.raises(ValueError, match=msg): + get_bit(b'\x00', 8) + + def test_empty_byte_raises(self): + """Test that an empty `byte` value raises an exception.""" + msg = r"ord\(\) expected a character" + with pytest.raises(TypeError, match=msg): + get_bit(b'', 0) + + def test_index_correct(self): + """Test that the `index` returns the correct bit = 1.""" + ref_bytes = [ + b'\x01', b'\x02', b'\x04', b'\x08', + b'\x10', b'\x20', b'\x40', b'\x80' + ] + for ii in range(0, 8, -1): + assert 1 == get_bit(ref_bytes[ii], ii) + + def test_index_correct_inverse(self): + """Test that the `index` returns the correct bit = 0.""" + ref_bytes = [ + b'\xfe', b'\xfd', b'\xfb', b'\xf7', + b'\xef', b'\xdf', b'\xbf', b'\x7f' + ] + for ii in range(0, 8, -1): + assert 0 == get_bit(ref_bytes[ii], ii) + + def test_multiple_bytes(self): + """Test that only the bit value from the first byte is returned""" + ref_bytes = [ + b'\x01\xff', b'\x02\xff', b'\x04\xff', b'\x08\xff', + b'\x10\xff', b'\x20\xff', b'\x40\xff', b'\x80\xff' + ] + for ii in range(0, 8, -1): + assert 1 == get_bit(ref_bytes[ii], ii) + + def test_multiple_bytes_inverse(self): + """Test that only the bit value from the first byte is returned""" + ref_bytes = [ + b'\xfe\x00', b'\xfd\x00', b'\xfb\x00', b'\xf7\x00', + b'\xef\x00', b'\xdf\x00', b'\xbf\x00', b'\x7f\x00' + ] + for ii in range(0, 8, -1): + assert 0 == get_bit(ref_bytes[ii], ii) + + +class TestSplitByte(object): + """Tests for utils.split_byte(byte).""" + def test_empty_byte_raises(self): + """Test that an empty `byte` value raises an exception.""" + msg = r"ord\(\) expected a character" + with pytest.raises(TypeError, match=msg): + split_byte(b'') + + def test_splitting(self): + """Test splitting a byte.""" + ref = { + b'\x00' : ( 0, 0), + b'\x0f' : ( 0, 15), + b'\xf0' : (15, 0), + b'\x55' : ( 5, 5), + b'\xaa' : (10, 10), + b'\x18' : ( 1, 8), + b'\x81' : ( 8, 1), + } + for byte, out in ref.items(): + assert out == split_byte(byte) diff --git a/pylibjpeg/tools/utils.py b/pylibjpeg/tools/utils.py new file mode 100644 index 0000000..0fbe4b3 --- /dev/null +++ b/pylibjpeg/tools/utils.py @@ -0,0 +1,43 @@ +"""Utility functions.""" + + +def get_bit(byte, index): + """Return the value of the bit at `index` of `byte`. + + Parameters + ---------- + byte : bytes + The value to process. + index : int + The index of the bit to return, where index ``0`` is the most + significant bit and index ``7`` is the least significant. + + Returns + ------- + int + The value of the bit (0 or 1). + """ + byte = ord(byte[:1]) + if not (-1 < index < 8): + raise ValueError("'index' must be between 0 and 7, inclusive") + + return (byte >> (7 - index)) & 1 + + +def split_byte(byte): + """Return the 8-bit `byte` as two 4-bit unsigned integers. + + Parameters + ---------- + byte : bytes + The byte to split, if more than one byte is supplied only the first + will be split. + + Returns + ------- + 2-tuple of int + The (4 most significant, 4 least significant) bits of `byte` as ``(int, + int)``. + """ + byte = ord(byte[:1]) + return byte >> 4, 0b00001111 & byte From b529a84060d604088731c29f62051b1bff5522a6 Mon Sep 17 00:00:00 2001 From: scaramallion Date: Wed, 11 Mar 2020 12:11:31 +1100 Subject: [PATCH 3/4] Updates --- .travis.yml | 44 ++--- build_tools/travis/install.sh | 50 +----- pylibjpeg/__init__.py | 14 +- pylibjpeg/_config.py | 4 +- pylibjpeg/plugins.py | 205 +++++++++++++++--------- pylibjpeg/pydicom/pixel_data_handler.py | 49 ++++-- pylibjpeg/tests/test_plugins.py | 110 ++++++++++++- pylibjpeg/tests/test_pydicom.py | 56 +++++-- pylibjpeg/utils.py | 33 ++++ setup.py | 9 +- 10 files changed, 382 insertions(+), 192 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3799051..9d5e374 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,66 +6,52 @@ language: python matrix: include: - # OSX first because it takes a long time to complete before_install - - name: "Python 3.6, OSX + pydicom" - os: osx - language: generic - env: - - TEST_SUITE=osx - - TRAVIS_PYTHON_VERSION=3.6.8 - - INSTALL_LIBJPEG=true - # Windows - - name: "Python 3.6, Windows + pydicom" - os: windows - language: shell - env: - - TEST_SUITE=windows - - TRAVIS_PYTHON_VERSION=3.6.8 - - INSTALL_LIBJPEG=true - # Ubuntu + # No plugins + pydicom - name: "Python 3.6, Ubuntu" os: linux dist: bionic python: "3.6" env: - - TEST_SUITE=solo - - INSTALL_LIBJPEG=true + - INSTALL_PYDICOM=true + - INSTALL_LIBJPEG=false - name: "Python 3.7, Ubuntu" os: linux dist: bionic python: "3.7" env: - - TEST_SUITE=solo - - INSTALL_LIBJPEG=true + - INSTALL_PYDICOM=true + - INSTALL_LIBJPEG=false - name: "Python 3.8, Ubuntu" os: linux dist: bionic python: "3.8" env: - - TEST_SUITE=solo - - INSTALL_LIBJPEG=true - - name: "Python 3.6, Ubuntu + pydicom" + - INSTALL_PYDICOM=true + - INSTALL_LIBJPEG=false + # libjpeg + pydicom + - name: "Python 3.6, Ubuntu" os: linux dist: bionic python: "3.6" env: - - TEST_SUITE=pydicom + - INSTALL_PYDICOM=true - INSTALL_LIBJPEG=true - - name: "Python 3.7, Ubuntu + pydicom" + - name: "Python 3.7, Ubuntu" os: linux dist: bionic python: "3.7" env: - - TEST_SUITE=pydicom + - INSTALL_PYDICOM=true - INSTALL_LIBJPEG=true - - name: "Python 3.8, Ubuntu + pydicom" + - name: "Python 3.8, Ubuntu" os: linux dist: bionic python: "3.8" env: - - TEST_SUITE=pydicom + - INSTALL_PYDICOM=true - INSTALL_LIBJPEG=true + # Install dependencies and package install: - source build_tools/travis/install.sh diff --git a/build_tools/travis/install.sh b/build_tools/travis/install.sh index a0b2185..4c21e84 100644 --- a/build_tools/travis/install.sh +++ b/build_tools/travis/install.sh @@ -7,58 +7,22 @@ echo "Test suite: " $TEST_SUITE echo "Working directory: " $PWD echo "" -if [[ "$TEST_SUITE" == "pydicom" ]]; then - pip install pydicom pytest pytest-cov - python -c "import pydicom; print('pydicom version', pydicom.__version__)" -elif [[ "$TEST_SUITE" == 'osx' ]]; then - brew update - brew install openssl readline - pyenv install $TRAVIS_PYTHON_VERSION - brew outdated pyenv || brew upgrade pyenv - brew install pyenv-virtualenv - export PYENV_VERSION=$TRAVIS_PYTHON_VERSION - export PATH="$HOME/.pyenv/bin:${PATH}" - eval "$(pyenv init -)" - eval "$(pyenv virtualenv-init -)" - export PATH="/Users/travis/.pyenv/shims:${PATH}" - pyenv virtualenv venv - pyenv activate venv - pip install --upgrade pip - pip install pydicom pytest pytest-cov - python -c "import pydicom; print('pydicom version', pydicom.__version__)" -elif [[ "$TEST_SUITE" == 'conda' ]]; then - deactivate +pip install -U pip +pip install pytest pytest-cov - wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh; - bash miniconda.sh -b -p $HOME/miniconda - source "$HOME/miniconda/etc/profile.d/conda.sh" - hash -r - conda config --set always_yes yes --set changeps1 no - conda update -q conda - # Useful for debugging any issues with conda - conda info -a - # Replace dep1 dep2 ... with your dependencies - conda create -q -n test-environment python=$TRAVIS_PYTHON_VERSION pip - conda activate test-environment - conda install --yes nose pytest pytest-cov setuptools - conda install --yes -c conda-forge pydicom -elif [[ "$TEST_SUITE" == 'windows' ]]; then - choco install python --version $TRAVIS_PYTHON_VERSION - export PATH="/c/Python36:/c/Python36/Scripts:$PATH" # make this generic - python -m pip install --upgrade pip - python -m pip install pydicom pytest pytest-cov -else - pip install pytest pytest-cov +if [[ "$INSTALL_PYDICOM" == "true" ]]; then + pip install pydicom + python -c "import pydicom; print('pydicom version', pydicom.__version__)" fi # Install the test data python -m pip install git+git://github.com/pydicom/pylibjpeg-data +python -c "import data; print('data version', data.__version__)" # Install plugins if [[ "$INSTALL_LIBJPEG" == 'true' ]]; then python -m pip install git+git://github.com/pydicom/pylibjpeg-libjpeg + python -c "import libjpeg; print('libjpeg version', libjpeg.__version__)" fi - - python --version diff --git a/pylibjpeg/__init__.py b/pylibjpeg/__init__.py index 0a5c39f..81b4026 100644 --- a/pylibjpeg/__init__.py +++ b/pylibjpeg/__init__.py @@ -1,12 +1,12 @@ """Set package shortcuts.""" -import importlib import logging import sys -from ._config import PLUGINS + from ._version import __version__ -from .plugins import PluginManager +from ._config import PLUGINS +from .plugins import load_plugins # Setup default logging @@ -39,11 +39,13 @@ def debug_logger(): except ImportError: pass +load_plugins(PLUGINS) + +from .utils import add_handler + try: import pydicom + add_handler() LOGGER.debug('pydicom module loaded') except ImportError: pass - - -_plugin_manager = PluginManager(PLUGINS) diff --git a/pylibjpeg/_config.py b/pylibjpeg/_config.py index 156cd6d..f9e3012 100644 --- a/pylibjpeg/_config.py +++ b/pylibjpeg/_config.py @@ -1,4 +1,4 @@ """pylibjpeg configuration options.""" -# A list of plugin package import names to try and interface with -PLUGINS = ['libjpeg'] +# Plugin packages to try and interface with +PLUGINS = ["libjpeg", "openjpeg"] diff --git a/pylibjpeg/plugins.py b/pylibjpeg/plugins.py index ceea5b2..6038ffa 100644 --- a/pylibjpeg/plugins.py +++ b/pylibjpeg/plugins.py @@ -1,78 +1,131 @@ """Utilities for managing plugins.""" - -class PluginManager(object): - """The plugin manager.""" - def __init__(self, plugins): - # dict {str name: module object, ...} - self._plugins = {} - for pkg_name in plugins: - plugin = self.import_package(pkg_name) - if plugin and plugin not in self._plugins: - self._plugins[pkg_name] = plugin - - def add_plugin(self, plugin): - """Add a plugin.""" - raise NotImplementedError() - - def import_package(pkg): - """Return the plugin for a package or ``None`` if not importable.""" - raise NotImplementedError() - - @property - def plugins(self): - """Return a list of available and enabled plugins.""" - out = {} - for (pkg_name, plugin) in self._plugins: - if plugin.is_available and plugin.enabled: - out[pkg_name] = plugin - - return out - - def remove_plugin(self, plugin): - """Remove a plugin.""" - raise NotImplementedError() - - @property - def transfer_syntaxes(self): - """Return a list of DICOM Transfer Syntax UIDs supported by the - plugins. - - """ - uids = [] - for (pkg_name, plugin) in self.plugins: - uids += plugin.transfer_syntaxes - - return list(set(uids)) - - -class Plugin(object): - """Base class for plugins.""" - def __init__(self, meta, enabled=True): - """Create a new Plugin object.""" - self.meta = meta - self._enabled = enabled - self._uids = [] - self._is_available = True - - @property - def enabled(self): - """Returns ``True`` if the plugin is enabled, ``False`` otherwise.""" - return self._enabled - - @enabled.setter - def enabled(self, is_enabled): - """Enable or disable the plugin.""" - self._enabled = bool(is_enabled) - - @property - def is_available(self): - """Return ``True`` if the plugin is available for use, ``False`` - otherwise. - """ - return self._is_available - - @property - def transfer_syntaxes(self): - """Return a list of supported DICOM Transfer Syntax UIDs.""" - return self._uids +from importlib import import_module +import logging +import sys + +from pylibjpeg._config import PLUGINS + + +LOGGER = logging.getLogger(__name__) + + +def load_plugins(plugins): + """Load the `plugins` and add them to the namespace.""" + for plugin in plugins: + try: + LOGGER.debug("Importing {}".format(plugin)) + module = import_module(plugin) + except ImportError as exc: + LOGGER.debug("Failed to import {}".format(plugin)) + continue + + # Add successful imported modules to the namespace + globals()[plugin] = module + sys.modules['pylibjpeg.plugins.{}'.format(plugin)] = module + + +def get_plugin_coders(): + """Return the available plugin decoders and encoders. + + Returns + ------- + dict, dict + A ``dict`` containing the available (decoders, encoders) as + ``{plugin name : {UID : callable}}``. + """ + decoders = {} + encoders = {} + for name in get_plugins(): + decoders[name] = getattr(globals()[name], 'DICOM_DECODERS') + encoders[name] = getattr(globals()[name], 'DICOM_ENCODERS') + + return decoders, encoders + + +def get_plugins(as_objects=False): + """Return the available plugins. + + Returns + ------- + list of str + A list containing the names of the available plugins. + """ + return [nn for nn in PLUGINS if nn in globals()] + + +def get_transfer_syntaxes(decodable=False, encodable=False): + """Return a list of decodable or encodable *Transfer Syntax UIDs*. + + Parameters + ---------- + decodable : bool, optional + Return a list of decodable *Transfer Syntax UIDs*. + encodable : bool, optional + Return a list of encodable *Transfer Syntax UIDs*. + + Returns + ------- + list of str + A list containing unique *Transfer Syntax UIDs*. + """ + if not decodable and not encodable: + raise ValueError("Either 'decodable' or 'encodable' must be True") + + dec, enc = get_plugin_coders() + if decodable: + obj = dec + else: + obj = enc + + uids = [] + for name, uid_coder in obj.items(): + uids += uid_coder.keys() + + return list(set(uids)) + + +def get_decoder(uid): + """Return a callable function that can decode pixel data encoding using + the *Transfer Syntax UID* `uid`. + """ + decoders, _ = get_plugin_coders() + for name in decoders: + try: + return decoders[name][uid] + except KeyError: + pass + + msg = ( + "No decoder is available for the Transfer Syntax UID - '{}'" + .format(uid) + ) + raise NotImplementedError(msg) + + +def get_decoders(): + uids = get_transfer_syntaxes(decodable=True) + decoders = {} + dec, _ = get_plugin_coders() + for name, uid_coder in dec.items(): + decoders.update(uid_coder) + + return decoders + + +def get_encoder(uid): + """Return a callable function that can encode pixel data using + the *Transfer Syntax UID* `uid`. + """ + _, encoders = get_plugin_coders() + for name in encoders: + try: + return encoders[name][uid] + except KeyError: + pass + + msg = ( + "No encoder is available for the Transfer Syntax UID - '{}'" + .format(uid) + ) + raise NotImplementedError(msg) diff --git a/pylibjpeg/pydicom/pixel_data_handler.py b/pylibjpeg/pydicom/pixel_data_handler.py index 8722f6d..7386d4a 100644 --- a/pylibjpeg/pydicom/pixel_data_handler.py +++ b/pylibjpeg/pydicom/pixel_data_handler.py @@ -40,19 +40,45 @@ from pydicom.encaps import generate_pixel_data_frame from pydicom.pixel_data_handlers.util import pixel_dtype, get_expected_length +from pylibjpeg.plugins import get_decoders + +try: + import pylibjpeg.plugins.libjpeg + HAVE_LIBJPEG = True +except ImportError: + HAVE_LIBJPEG = False + +try: + import pylibjpeg.plugins.openjpeg + HAVE_OPENJPEG = True +except ImportError: + HAVE_OPENJPEG = False HANDLER_NAME = 'pylibjpeg' -# Set this dynamically based on unavailable plugins DEPENDENCIES = { 'numpy': ('http://www.numpy.org/', 'NumPy'), + 'libjpeg': ( + 'http://github.com/pydicom/pylibjpeg-libjpeg/', 'libjpeg plugin' + ), + 'openjpeg': ( + 'http://github.com/pydicom/pylibjpeg-openjpeg/', 'openjpeg plugin' + ), } -SUPPORTED_TRANSFER_SYNTAXES = [] -_DECODERS = {} + +_DECODERS = get_decoders() +SUPPORTED_TRANSFER_SYNTAXES = [ + '1.2.840.10008.1.2.4.50', + '1.2.840.10008.1.2.4.51', + '1.2.840.10008.1.2.4.57', + '1.2.840.10008.1.2.4.70', + '1.2.840.10008.1.2.4.80', + '1.2.840.10008.1.2.4.81' +] def is_available(): """Return ``True`` if the handler has its dependencies met.""" - return True + return HAVE_LIBJPEG or HAVE_OPENJPEG def supports_transfer_syntax(tsyntax): @@ -60,8 +86,8 @@ def supports_transfer_syntax(tsyntax): Parameters ---------- - tsyntax : uid.UID - The Transfer Syntax UID of the *Pixel Data* that is to be used with + tsyntax : pydicom.uid.UID + The *Transfer Syntax UID* of the *Pixel Data* that is to be used with the handler. """ return tsyntax in SUPPORTED_TRANSFER_SYNTAXES @@ -90,7 +116,7 @@ def get_pixeldata(ds): Parameters ---------- - ds : Dataset + ds : pydicom.dataset.Dataset The :class:`Dataset` containing an Image Pixel, Floating Point Image Pixel or Double Floating Point Image Pixel module and the *Pixel Data*, *Float Pixel Data* or *Double Float Pixel Data* to be @@ -101,7 +127,7 @@ def get_pixeldata(ds): Returns ------- - np.ndarray + numpy.ndarray The contents of (7FE0,0010) *Pixel Data* as a 1D array. Raises @@ -138,7 +164,8 @@ def get_pixeldata(ds): # Note: this does NOT include the trailing null byte for odd length data expected_len = get_expected_length(ds) if ds.PhotometricInterpretation == 'YBR_FULL_422': - # libjpeg has already resampled the pixel data, see PS3.3 C.7.6.3.1.2 + # Plugin should have already resampled the pixel data + # see PS3.3 C.7.6.3.1.2 expected_len = expected_len // 2 * 3 p_interp = ds.PhotometricInterpretation @@ -150,12 +177,14 @@ def get_pixeldata(ds): # The decoded data will be placed here arr = np.empty(expected_len, np.uint8) + decoder = _DECODERS[tsyntax] + # Generators for the encoded JPG image frame(s) and insertion offsets generate_frames = generate_pixel_data_frame(ds.PixelData, nr_frames) generate_offsets = range(0, expected_len, frame_len) for frame, offset in zip(generate_frames, generate_offsets): # Encoded JPG data to be sent to the decoder frame = np.frombuffer(frame, np.uint8) - arr[offset:offset + frame_len] = decode(frame, p_interp, reshape=False) + arr[offset:offset + frame_len] = decoder(frame, p_interp) return arr.view(pixel_dtype(ds)) diff --git a/pylibjpeg/tests/test_plugins.py b/pylibjpeg/tests/test_plugins.py index eaff405..a1222c3 100644 --- a/pylibjpeg/tests/test_plugins.py +++ b/pylibjpeg/tests/test_plugins.py @@ -6,9 +6,111 @@ import pytest -from pylibjpeg.plugins import PluginManager +from pylibjpeg.plugins import ( + get_plugin_coders, get_plugins, get_transfer_syntaxes, get_decoder, + get_encoder, get_decoders +) +# TODO: Switch this over to openjpeg +try: + import libjpeg + HAS_LIBJPEG = True +except ImportError: + HAS_LIBJPEG = False -class TestPluginManager(object): - """Tests for PluginManager.""" - pass +HAS_PLUGINS = get_plugins() != [] + + +@pytest.mark.skipif(HAS_PLUGINS, reason="Plugins available") +class TestNoPlugins(object): + """Tests for plugins without any available.""" + def test_check_plugins(self): + """Test check_plugins().""" + dec, enc = get_plugin_coders() + assert {} == dec + assert {} == enc + + def test_get_plugins(self): + """Test get_plugins().""" + assert [] == get_plugins() + + def test_get_transfer_syntaxes(self): + """Test get_plugins().""" + msg = r"Either 'decodable' or 'encodable' must be True" + with pytest.raises(ValueError, match=msg): + get_transfer_syntaxes() + + assert [] == get_transfer_syntaxes(decodable=True) + assert [] == get_transfer_syntaxes(encodable=True) + + def test_get_decoder_raises(self): + """Test get_decoder().""" + msg = r"No decoder is available for the Transfer Syntax UID - '1.2.3'" + with pytest.raises(NotImplementedError, match=msg): + get_decoder('1.2.3') + + def test_get_encoder_raises(self): + """Test get_encoder().""" + msg = r"No encoder is available for the Transfer Syntax UID - '1.2.3'" + with pytest.raises(NotImplementedError, match=msg): + get_encoder('1.2.3') + + def test_get_decoders(self): + """Test get_decoders().""" + assert {} == get_decoders() + + +@pytest.mark.skipif(not HAS_PLUGINS or not HAS_LIBJPEG, reason="No libjpeg") +class TestPlugins(object): + """Tests for plugins with a plugin available.""" + def test_check_plugins(self): + """Test check_plugins().""" + dec, enc = get_plugin_coders() + assert {} != dec + assert {} != enc + + def test_check_plugins_dec_only(self): + """Test check_plugins() with only a decoder plugin.""" + dec, enc = get_plugin_coders() + assert 'libjpeg' in enc + assert {} == enc['libjpeg'] + assert 'libjpeg' in dec + assert '1.2.840.10008.1.2.4.50' in dec['libjpeg'] + + def test_get_transfer_syntaxes(self): + """Test get_plugins().""" + msg = r"Either 'decodable' or 'encodable' must be True" + with pytest.raises(ValueError, match=msg): + get_transfer_syntaxes() + + reference = [ + '1.2.840.10008.1.2.4.50', + '1.2.840.10008.1.2.4.51', + '1.2.840.10008.1.2.4.57', + '1.2.840.10008.1.2.4.70', + '1.2.840.10008.1.2.4.80', + '1.2.840.10008.1.2.4.81', + ] + syntaxes = get_transfer_syntaxes(decodable=True) + for uid in syntaxes: + assert uid in reference + + assert [] == get_transfer_syntaxes(encodable=True) + + def test_get_decoder(self): + """Test get_decoder().""" + decoder = get_decoder('1.2.840.10008.1.2.4.50') + + def test_get_decoders(self): + """Test get_decoders().""" + reference = [ + '1.2.840.10008.1.2.4.50', + '1.2.840.10008.1.2.4.51', + '1.2.840.10008.1.2.4.57', + '1.2.840.10008.1.2.4.70', + '1.2.840.10008.1.2.4.80', + '1.2.840.10008.1.2.4.81', + ] + decoders = get_decoders() + for uid in reference: + assert uid in decoders diff --git a/pylibjpeg/tests/test_pydicom.py b/pylibjpeg/tests/test_pydicom.py index c77fa07..4bfc2ae 100644 --- a/pylibjpeg/tests/test_pydicom.py +++ b/pylibjpeg/tests/test_pydicom.py @@ -12,26 +12,50 @@ except ImportError: HAS_PYDICOM = False -from pylibjpeg import _plugin_manager +from pylibjpeg.plugins import get_plugins +from pylibjpeg.data import get_indexed_datasets -HAS_PLUGINS = False -if _plugin_manager.plugins: - HAS_PLUGINS = True +HAS_PLUGINS = get_plugins() != [] -@pytest.mark.skipif(not HAS_PYDICOM or HAS_PLUGINS) +@pytest.mark.skipif(not HAS_PYDICOM or HAS_PLUGINS, reason="Plugins available") class TestNoPlugins(object): """Test interactions with no plugins.""" - # Should basically just not mess up the usual pydicom behaviour - pass - - -@pytest.mark.skipif(not HAS_PYDICOM or not HAS_PLUGINS) + def test_pixel_array(self): + # Should basically just not mess up the usual pydicom behaviour + index = get_indexed_datasets('1.2.840.10008.1.2.4.50') + ds = index['JPEGBaseline_1s_1f_u_08_08.dcm']['ds'] + msg = ( + r"The following handlers are available to decode the pixel data " + r"however they are missing required dependencies: GDCM \(req. " + r"GDCM\), Pillow \(req. Pillow\), pylibjpeg \(req. libjpeg " + r"plugin, openjpeg plugin\)" + ) + with pytest.raises(RuntimeError, match=msg): + ds.pixel_array + + +@pytest.mark.skipif(not HAS_PYDICOM or not HAS_PLUGINS, reason="No plugins") class TestPlugins(object): """Test interaction with plugins.""" - # Simple tests to ensure plugins work as intended - pass - - -# May need pydicom to reload some data if dynamically changing -# available plugins + def test_pixel_array(self): + # Should basically just not mess up the usual pydicom behaviour + index = get_indexed_datasets('1.2.840.10008.1.2.4.50') + ds = index['JPEGBaseline_1s_1f_u_08_08.dcm']['ds'] + arr = ds.pixel_array + + assert arr.flags.writeable + assert 'uint8' == arr.dtype + assert (ds.Rows, ds.Columns) == arr.shape + + # Reference values from GDCM handler + assert 76 == arr[ 5, 50] + assert 167 == arr[15, 50] + assert 149 == arr[25, 50] + assert 203 == arr[35, 50] + assert 29 == arr[45, 50] + assert 142 == arr[55, 50] + assert 1 == arr[65, 50] + assert 64 == arr[75, 50] + assert 192 == arr[85, 50] + assert 255 == arr[95, 50] diff --git a/pylibjpeg/utils.py b/pylibjpeg/utils.py index e69de29..f193178 100644 --- a/pylibjpeg/utils.py +++ b/pylibjpeg/utils.py @@ -0,0 +1,33 @@ + +#try: +from .pydicom import pixel_data_handler as handler +#except ImportError: +# pass + + +def add_handler(): + """Add the pixel data handler to *pydicom*. + + Raises + ------ + ImportError + If *pydicom* is not available. + """ + import pydicom.config + + if handler not in pydicom.config.pixel_data_handlers: + pydicom.config.pixel_data_handlers.append(handler) + + +def remove_handler(): + """Remove the pixel data handler from *pydicom*. + + Raises + ------ + ImportError + If *pydicom* is not available. + """ + import pydicom.config + + if handler in pydicom.config.pixel_data_handlers: + pydicom.config.pixel_data_handlers.remove(handler) diff --git a/setup.py b/setup.py index c70a177..b069148 100644 --- a/setup.py +++ b/setup.py @@ -24,13 +24,9 @@ url = "https://github.com/pydicom/pylibjpeg", license = "MIT", keywords = ( - "dicom pydicom python medicalimaging radiotherapy oncology imaging " - "jpg jpeg pylibjpeg" + "dcm dicom pydicom python medicalimaging radiology radiotherapy " + "oncology imaging jpg jpeg jpg-ls jpeg-ls libjpeg pylibjpeg " ), - project_urls = { - # Might give it it's own docs eventually - 'Documentation' : 'https://pydicom.github.io/pydicom/' - }, classifiers = [ "License :: OSI Approved :: MIT License", "Intended Audience :: Developers", @@ -48,6 +44,7 @@ "Topic :: Software Development :: Libraries", ], packages = find_packages(), + install_requires = ['numpy'], include_package_data = True, zip_safe = False, python_requires = ">=3.6", From 5f763200e482395fb84086ef2459bcb40edf4f69 Mon Sep 17 00:00:00 2001 From: scaramallion Date: Wed, 11 Mar 2020 12:15:48 +1100 Subject: [PATCH 4/4] Remove test of pydicom --- .travis.yml | 6 +++--- pylibjpeg/tests/test_environment.py | 16 ---------------- 2 files changed, 3 insertions(+), 19 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9d5e374..be09865 100644 --- a/.travis.yml +++ b/.travis.yml @@ -29,21 +29,21 @@ matrix: - INSTALL_PYDICOM=true - INSTALL_LIBJPEG=false # libjpeg + pydicom - - name: "Python 3.6, Ubuntu" + - name: "Python 3.6, Ubuntu + libjpeg" os: linux dist: bionic python: "3.6" env: - INSTALL_PYDICOM=true - INSTALL_LIBJPEG=true - - name: "Python 3.7, Ubuntu" + - name: "Python 3.7, Ubuntu + libjpeg" os: linux dist: bionic python: "3.7" env: - INSTALL_PYDICOM=true - INSTALL_LIBJPEG=true - - name: "Python 3.8, Ubuntu" + - name: "Python 3.8, Ubuntu + libjpeg" os: linux dist: bionic python: "3.8" diff --git a/pylibjpeg/tests/test_environment.py b/pylibjpeg/tests/test_environment.py index 79ae398..5256f11 100644 --- a/pylibjpeg/tests/test_environment.py +++ b/pylibjpeg/tests/test_environment.py @@ -56,19 +56,3 @@ def test_python_version(self): version = tuple([int(vv) for vv in version.split('.')]) assert version[:2] == sys.version_info[:2] - - def test_pydicom(self): - """Test that pydicom is absent/present.""" - if not get_envar('TRAVIS_JOB_NAME'): - raise RuntimeError("No TRAVIS_JOB_NAME' envar has been set") - - if 'pydicom' in get_envar('TRAVIS_JOB_NAME'): - try: - import pydicom - except ImportError: - pytest.fail( - "TRAVIS_JOB_NAME includes pydicom but isn't importable" - ) - else: - with pytest.raises(ImportError): - import pydicom