From 7e6347486bad1f3b10659ebd7af188cdc2929ae3 Mon Sep 17 00:00:00 2001 From: NiLuJe <ninuje@gmail.com> Date: Fri, 24 May 2019 00:54:36 +0200 Subject: [PATCH] Port ImageMagick's OrderedDither algorithm, and use that instead of ImageOps' quantize to dither images to the eInk palette. It works much better for our intended purpose, and it's pretty fast. --- COPYRIGHT | 110 ++++++++++++++++++ setup/extensions.json | 2 +- src/calibre/devices/kobo/driver.py | 5 +- src/calibre/utils/imageops/imageops.h | 1 + src/calibre/utils/imageops/imageops.sip | 9 +- src/calibre/utils/imageops/ordered_dither.cpp | 93 +++++++++++++++ src/calibre/utils/img.py | 19 +-- 7 files changed, 227 insertions(+), 12 deletions(-) create mode 100644 src/calibre/utils/imageops/ordered_dither.cpp diff --git a/COPYRIGHT b/COPYRIGHT index 3ac5369ff7a4..b790d3190abf 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -399,6 +399,9 @@ Files: src/calibre/translations/msgfmt.py Copyright: Martin v. Loewis License: Python Software Foundation License +Files: src/calibre/utils/imageops/ordered_dither.cpp +Copyright: Copyright 1999-2019 ImageMagick Studio LLC +License: ImageMagick License BSD License (for all the BSD licensed code indicated above) ----------------------------------------------------------- @@ -581,3 +584,110 @@ whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. + +ImageMagick License (for all the ImageMagick licensed code indicated above) +----------------------------------------------------------- + +Before we get to the text of the license, lets just review what the license says in simple terms: + +It allows you to: + + * freely download and use ImageMagick software, in whole or in part, for personal, company internal, or commercial purposes; + * use ImageMagick software in packages or distributions that you create; + * link against a library under a different license; + * link code under a different license against a library under this license; + * merge code into a work under a different license; + * extend patent grants to any code using code under this license; + * and extend patent protection. + +It forbids you to: + + * redistribute any piece of ImageMagick-originated software without proper attribution; + * use any marks owned by ImageMagick Studio LLC in any way that might state or imply that ImageMagick Studio LLC endorses your distribution; + * use any marks owned by ImageMagick Studio LLC in any way that might state or imply that you created the ImageMagick software in question. + +It requires you to: + + * include a copy of the license in any redistribution you may make that includes ImageMagick software; + * provide clear attribution to ImageMagick Studio LLC for any distributions that include ImageMagick software. + +It does not require you to: + + * include the source of the ImageMagick software itself, or of any modifications you may have made to it, in any redistribution you may assemble that includes it; + * submit changes that you make to the software back to the ImageMagick Studio LLC (though such feedback is encouraged). + +A few other clarifications include: + + * ImageMagick is freely available without charge; + * you may include ImageMagick on a DVD as long as you comply with the terms of the license; + * you can give modified code away for free or sell it under the terms of the ImageMagick license or distribute the result under a different license, but you need to acknowledge the use of the ImageMagick software; + * the license is compatible with the GPL V3. + * when exporting the ImageMagick software, review its export classification. + +Terms and Conditions for Use, Reproduction, and Distribution + +The legally binding and authoritative terms and conditions for use, reproduction, and distribution of ImageMagick follow: + +Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization dedicated to making software imaging solutions freely available. + +1. Definitions. + +License shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +Legal Entity shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, control means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +You (or Your) shall mean an individual or Legal Entity exercising permissions granted by this License. + +Source form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +Object form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +Work shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +Derivative Works shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +Contribution shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as Not a Contribution. + +Contributor shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + * You must give any other recipients of the Work or Derivative Works a copy of this License; and + * You must cause any modified files to carry prominent notices stating that You changed the files; and + * You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + * If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +How to Apply the License to your Work + +To apply the ImageMagick License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information (don't include the brackets). The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the ImageMagick License (the "License"); you may not use + this file except in compliance with the License. You may obtain a copy + of the License at + + https://imagemagick.org/script/license.php + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + License for the specific language governing permissions and limitations + under the License. diff --git a/setup/extensions.json b/setup/extensions.json index a43568541dfe..106b8f8f06b4 100644 --- a/setup/extensions.json +++ b/setup/extensions.json @@ -139,7 +139,7 @@ }, { "name": "imageops", - "sources": "calibre/utils/imageops/imageops.cpp calibre/utils/imageops/quantize.cpp", + "sources": "calibre/utils/imageops/imageops.cpp calibre/utils/imageops/quantize.cpp calibre/utils/imageops/ordered_dither.cpp", "headers": "calibre/utils/imageops/imageops.h", "sip_files": "calibre/utils/imageops/imageops.sip", "inc_dirs": "calibre/utils/imageops" diff --git a/src/calibre/devices/kobo/driver.py b/src/calibre/devices/kobo/driver.py index 56a0b1c39596..b3d31f4376a6 100644 --- a/src/calibre/devices/kobo/driver.py +++ b/src/calibre/devices/kobo/driver.py @@ -3,7 +3,7 @@ from __future__ import absolute_import, division, print_function, unicode_literals __license__ = 'GPL v3' -__copyright__ = '2010-2018, Timothy Legge <timlegge@gmail.com>, Kovid Goyal <kovid@kovidgoyal.net> and David Forrester <davidfor@internode.on.net>' +__copyright__ = '2010-2019, Timothy Legge <timlegge@gmail.com>, Kovid Goyal <kovid@kovidgoyal.net> and David Forrester <davidfor@internode.on.net>' __docformat__ = 'restructuredtext en' ''' @@ -2651,7 +2651,8 @@ def _calculate_kobo_cover_size(self, library_size, kobo_size, expand, keep_cover # NOTE: Loosely based on Qt's QSize::scaled implementation if keep_cover_aspect: # NOTE: Py3k wouldn't need explicit casts to return a float - # NOTE: Unlike Qt, we round to avoid accumulating errors + # NOTE: Unlike Qt, we round to avoid accumulating errors, + # as ImageOps will then floor via fit_image aspect_ratio = library_size[0] / float(library_size[1]) rescaled_width = int(round(kobo_size[1] * aspect_ratio)) diff --git a/src/calibre/utils/imageops/imageops.h b/src/calibre/utils/imageops/imageops.h index e477eb8105c1..208cb6ef03eb 100644 --- a/src/calibre/utils/imageops/imageops.h +++ b/src/calibre/utils/imageops/imageops.h @@ -22,6 +22,7 @@ QImage quantize(const QImage &image, unsigned int maximum_colors, bool dither, c bool has_transparent_pixels(const QImage &image); QImage set_opacity(const QImage &image, double alpha); QImage texture_image(const QImage &image, const QImage &texturei); +QImage ordered_dither(const QImage &image); class ScopedGILRelease { public: diff --git a/src/calibre/utils/imageops/imageops.sip b/src/calibre/utils/imageops/imageops.sip index 686c81a2a4e2..d76c6b2a9910 100644 --- a/src/calibre/utils/imageops/imageops.sip +++ b/src/calibre/utils/imageops/imageops.sip @@ -15,7 +15,7 @@ } catch (std::out_of_range &exc) { PyErr_SetString(PyExc_ValueError, exc.what()); return NULL; \ } catch (std::bad_alloc &) { PyErr_NoMemory(); return NULL; \ } catch (std::exception &exc) { PyErr_SetString(PyExc_Exception, exc.what()); return NULL; \ - } catch (...) { PyErr_SetString(PyExc_RuntimeError, "unknown error"); return NULL;} + } catch (...) { PyErr_SetString(PyExc_RuntimeError, "unknown error"); return NULL;} %End QImage* remove_borders(const QImage &image, double fuzz); @@ -100,3 +100,10 @@ QImage texture_image(const QImage &image, const QImage &texturei); sipRes = new QImage(texture_image(*a0, *a1)); IMAGEOPS_SUFFIX %End + +QImage ordered_dither(const QImage &image); +%MethodCode + IMAGEOPS_PREFIX + sipRes = new QImage(ordered_dither(*a0)); + IMAGEOPS_SUFFIX +%End diff --git a/src/calibre/utils/imageops/ordered_dither.cpp b/src/calibre/utils/imageops/ordered_dither.cpp new file mode 100644 index 000000000000..abf9c46c60ce --- /dev/null +++ b/src/calibre/utils/imageops/ordered_dither.cpp @@ -0,0 +1,93 @@ +/* + * Copyright 1999-2019 ImageMagick Studio LLC + * + * Licensed under the ImageMagick License (the "License"); you may not use + * this file except in compliance with the License. You may obtain a copy + * of the License at + * + * https://imagemagick.org/script/license.php + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +#include "imageops.h" + +// Just in case, as I don't want to deal with MSVC madness... +#if defined _MSC_VER && _MSC_VER < 1700 +typedef unsigned __int8 uint8_t; +#define UINT8_MAX _UI8_MAX +typedef unsigned __int32 uint32_t; +#else +#include <cstdint> +#endif + +// Quantize an 8-bit color value down to a palette of 16 evenly spaced colors, using an ordered 8x8 dithering pattern. +// With a grayscale input, this happens to match the eInk palette perfectly ;). +// If the input is not grayscale, and the output fb is not grayscale either, +// this usually still happens to match the eInk palette after the EPDC's own quantization pass. +// c.f., https://en.wikipedia.org/wiki/Ordered_dithering +// & https://github.com/ImageMagick/ImageMagick/blob/ecfeac404e75f304004f0566557848c53030bad6/MagickCore/threshold.c#L1627 +// NOTE: As the references imply, this is straight from ImageMagick, +// with only minor simplifications to enforce Q8 & avoid fp maths. +static uint8_t + dither_o8x8(int x, int y, uint8_t v) +{ + // c.f., https://github.com/ImageMagick/ImageMagick/blob/ecfeac404e75f304004f0566557848c53030bad6/config/thresholds.xml#L107 + static const uint8_t threshold_map_o8x8[] = { 1, 49, 13, 61, 4, 52, 16, 64, 33, 17, 45, 29, 36, 20, 48, 32, + 9, 57, 5, 53, 12, 60, 8, 56, 41, 25, 37, 21, 44, 28, 40, 24, + 3, 51, 15, 63, 2, 50, 14, 62, 35, 19, 47, 31, 34, 18, 46, 30, + 11, 59, 7, 55, 10, 58, 6, 54, 43, 27, 39, 23, 42, 26, 38, 22 }; + + // Constants: + // Quantum = 8; Levels = 16; map Divisor = 65 + // QuantumRange = 0xFF + // QuantumScale = 1.0 / QuantumRange + // + // threshold = QuantumScale * v * ((L-1) * (D-1) + 1) + // NOTE: The initial computation of t (specifically, what we pass to DIV255) would overflow an uint8_t. + // With a Q8 input value, we're at no risk of ever underflowing, so, keep to unsigned maths. + // Technically, an uint16_t would be wide enough, but it gains us nothing, + // and requires a few explicit casts to make GCC happy ;). + uint32_t t = DIV255(v * ((15U << 6) + 1U)); + // level = t / (D-1); + uint32_t l = (t >> 6); + // t -= l * (D-1); + t = (t - (l << 6)); + + // map width & height = 8 + // c = ClampToQuantum((l+(t >= map[(x % mw) + mw * (y % mh)])) * QuantumRange / (L-1)); + uint32_t q = ((l + (t >= threshold_map_o8x8[(x & 7U) + 8U * (y & 7U)])) * 17); + // NOTE: We're doing unsigned maths, so, clamping is basically MIN(q, UINT8_MAX) ;). + // The only overflow we should ever catch should be for a few black (v = 0xFF) input pixels + // that get shifted to the next step (i.e., q = 272 (0xFF + 17)). + return (q > UINT8_MAX ? UINT8_MAX : reinterpret_cast<uint8_t>(q); +} + +QImage ordered_dither(const QImage &image) { // {{{ + ScopedGILRelease PyGILRelease; + QImage img = image; + QRgb *row = NULL, *pixel = NULL; + int y = 0, x = 0, width = img.width(), height = img.height(); + uint8_t gray = 0, dithered = 0; + + // We're running behind blend_image, so, we should only ever be fed RGB32 as input... + if (img.format() != QImage::Format_RGB32) { + img = img.convertToFormat(QImage::Format_RGB32); + if (img.isNull()) throw std::bad_alloc(); + } + + for (y = 0; y < height; y++) { + row = reinterpret_cast<QRgb*>(img.scanLine(y)); + for (x = 0, pixel = row; x < width; x++, pixel++) { + // We're running behind grayscale_image, so R = G = B + gray = qRed(*pixel); + dithered = dither_o8x8(x, y, gray); + *pixel = qRgb(dithered, dithered, dithered); + } + } + return img; +} // }}} diff --git a/src/calibre/utils/img.py b/src/calibre/utils/img.py index f60d24ddb04f..cf4b26a9d75b 100644 --- a/src/calibre/utils/img.py +++ b/src/calibre/utils/img.py @@ -1,6 +1,6 @@ #!/usr/bin/env python2 # vim:fileencoding=utf-8 -# License: GPLv3 Copyright: 2015-2018, Kovid Goyal <kovid at kovidgoyal.net> +# License: GPLv3 Copyright: 2015-2019, Kovid Goyal <kovid at kovidgoyal.net> from __future__ import absolute_import, division, print_function, unicode_literals @@ -232,15 +232,9 @@ def save_cover_data_to(data, path=None, bgcolor='#ffffff', resize_to=None, compr changed = True img = grayscale_image(img) if eink: - eink_cmap = ['#000000', '#111111', '#222222', '#333333', '#444444', '#555555', '#666666', '#777777', - '#888888', '#999999', '#AAAAAA', '#BBBBBB', '#CCCCCC', '#DDDDDD', '#EEEEEE', '#FFFFFF'] # NOTE: Keep in mind that JPG does NOT actually support indexed colors, so the JPG algorithm will then smush everything back into a 256c mess... # Thankfully, Nickel handles PNG just fine, and we generate smaller files to boot, because they're properly color indexed ;). - img = quantize_image(img, max_colors=16, dither=True, palette=eink_cmap) - ''' - # NOTE: Neither Grayscale8 nor Indexed8 actually do any kind of dithering?... :/. - img = img.convertToFormat(QImage.Format_Grayscale8, [QColor(x).rgb() for x in eink_cmap], Qt.AutoColor | Qt.DiffuseDither | Qt.ThresholdAlphaDither | Qt.PreferDither) - ''' + img = eink_dither_image(img) changed = True if path is None: return image_to_data(img, compression_quality, fmt) if changed else data @@ -466,6 +460,15 @@ def quantize_image(img, max_colors=256, dither=True, palette=''): palette = palette.split() return imageops.quantize(img, max_colors, dither, [QColor(x).rgb() for x in palette]) +def eink_dither_image(img): + ''' Dither the source image down to the eInk palette of 16 shades of grey, + using ImageMagick's OrderedDither algorithm. + ''' + img = image_from_data(img) + if img.hasAlphaChannel(): + img = blend_image(img) + return imageops.ordered_dither(img) + # }}} # Optimization of images {{{