mirror of
https://github.com/CloverHackyColor/CloverBootloader.git
synced 2024-11-25 11:55:28 +01:00
Optimize Theme ability for Clover.app
When this option is enabled all png images will be converted to PNG-8 (8 bit per pixel).
This commit is contained in:
parent
26b6f6079f
commit
286f7c643f
@ -36,6 +36,15 @@
|
||||
956090B7238C890600ACD7F7 /* Installer.xib in Resources */ = {isa = PBXBuildFile; fileRef = 956090B9238C890600ACD7F7 /* Installer.xib */; };
|
||||
95696B7B2401829800AFAD37 /* GengConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95696B7A2401829800AFAD37 /* GengConfig.swift */; };
|
||||
9569EC42238DD772003AD72C /* Settings.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9569EC44238DD772003AD72C /* Settings.xib */; };
|
||||
9580402D2413F63700F09F2C /* kmeans.c in Sources */ = {isa = PBXBuildFile; fileRef = 9580400A2413F63400F09F2C /* kmeans.c */; };
|
||||
9580402E2413F63700F09F2C /* blur.c in Sources */ = {isa = PBXBuildFile; fileRef = 9580400B2413F63400F09F2C /* blur.c */; };
|
||||
958040302413F63700F09F2C /* nearest.c in Sources */ = {isa = PBXBuildFile; fileRef = 958040132413F63400F09F2C /* nearest.c */; };
|
||||
958040312413F63700F09F2C /* libimagequant.c in Sources */ = {isa = PBXBuildFile; fileRef = 958040152413F63500F09F2C /* libimagequant.c */; };
|
||||
958040332413F63700F09F2C /* pam.c in Sources */ = {isa = PBXBuildFile; fileRef = 958040172413F63500F09F2C /* pam.c */; };
|
||||
958040372413F63700F09F2C /* mediancut.c in Sources */ = {isa = PBXBuildFile; fileRef = 9580401E2413F63600F09F2C /* mediancut.c */; };
|
||||
958040392413F63700F09F2C /* mempool.c in Sources */ = {isa = PBXBuildFile; fileRef = 958040232413F63600F09F2C /* mempool.c */; };
|
||||
9580403D2413F8CA00F09F2C /* lodepng.c in Sources */ = {isa = PBXBuildFile; fileRef = 9580403C2413F8C900F09F2C /* lodepng.c */; };
|
||||
958040402414070F00F09F2C /* PNG8Image.m in Sources */ = {isa = PBXBuildFile; fileRef = 9580403F2414070F00F09F2C /* PNG8Image.m */; };
|
||||
958861DA235F75FB00B64173 /* Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 958861D9235F75FB00B64173 /* Driver.swift */; };
|
||||
95C515222369BAF500E4A3A8 /* NVRAM.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95C515212369BAF500E4A3A8 /* NVRAM.swift */; };
|
||||
95C5152F236A0A7400E4A3A8 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95C5152E236A0A7400E4A3A8 /* SettingsView.swift */; };
|
||||
@ -327,6 +336,24 @@
|
||||
9569EC8C238DD7C6003AD72C /* tr */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = tr; path = tr.lproj/Settings.strings; sourceTree = "<group>"; };
|
||||
9569EC8E238DD7C8003AD72C /* uk */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = uk; path = uk.lproj/Settings.strings; sourceTree = "<group>"; };
|
||||
9569EC90238DD7CA003AD72C /* vi */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = vi; path = vi.lproj/Settings.strings; sourceTree = "<group>"; };
|
||||
9580400A2413F63400F09F2C /* kmeans.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = kmeans.c; path = "libimagequant-2.12.6/kmeans.c"; sourceTree = SOURCE_ROOT; };
|
||||
9580400B2413F63400F09F2C /* blur.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = blur.c; path = "libimagequant-2.12.6/blur.c"; sourceTree = SOURCE_ROOT; };
|
||||
958040132413F63400F09F2C /* nearest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = nearest.c; path = "libimagequant-2.12.6/nearest.c"; sourceTree = SOURCE_ROOT; };
|
||||
958040142413F63400F09F2C /* nearest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = nearest.h; path = "libimagequant-2.12.6/nearest.h"; sourceTree = SOURCE_ROOT; };
|
||||
958040152413F63500F09F2C /* libimagequant.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = libimagequant.c; path = "libimagequant-2.12.6/libimagequant.c"; sourceTree = SOURCE_ROOT; };
|
||||
958040172413F63500F09F2C /* pam.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = pam.c; path = "libimagequant-2.12.6/pam.c"; sourceTree = SOURCE_ROOT; };
|
||||
958040182413F63500F09F2C /* kmeans.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = kmeans.h; path = "libimagequant-2.12.6/kmeans.h"; sourceTree = SOURCE_ROOT; };
|
||||
9580401A2413F63500F09F2C /* mediancut.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = mediancut.h; path = "libimagequant-2.12.6/mediancut.h"; sourceTree = SOURCE_ROOT; };
|
||||
9580401D2413F63600F09F2C /* mempool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = mempool.h; path = "libimagequant-2.12.6/mempool.h"; sourceTree = SOURCE_ROOT; };
|
||||
9580401E2413F63600F09F2C /* mediancut.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = mediancut.c; path = "libimagequant-2.12.6/mediancut.c"; sourceTree = SOURCE_ROOT; };
|
||||
9580401F2413F63600F09F2C /* libimagequant.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = libimagequant.h; path = "libimagequant-2.12.6/libimagequant.h"; sourceTree = SOURCE_ROOT; };
|
||||
958040202413F63600F09F2C /* blur.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = blur.h; path = "libimagequant-2.12.6/blur.h"; sourceTree = SOURCE_ROOT; };
|
||||
958040212413F63600F09F2C /* pam.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = pam.h; path = "libimagequant-2.12.6/pam.h"; sourceTree = SOURCE_ROOT; };
|
||||
958040232413F63600F09F2C /* mempool.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = mempool.c; path = "libimagequant-2.12.6/mempool.c"; sourceTree = SOURCE_ROOT; };
|
||||
9580403B2413F86A00F09F2C /* lodepng.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = lodepng.h; sourceTree = "<group>"; };
|
||||
9580403C2413F8C900F09F2C /* lodepng.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lodepng.c; sourceTree = "<group>"; };
|
||||
9580403E2414070F00F09F2C /* PNG8Image.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PNG8Image.h; sourceTree = "<group>"; };
|
||||
9580403F2414070F00F09F2C /* PNG8Image.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PNG8Image.m; sourceTree = "<group>"; };
|
||||
958861D9235F75FB00B64173 /* Driver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Driver.swift; sourceTree = "<group>"; };
|
||||
95C515212369BAF500E4A3A8 /* NVRAM.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NVRAM.swift; sourceTree = "<group>"; };
|
||||
95C5152E236A0A7400E4A3A8 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
|
||||
@ -433,6 +460,29 @@
|
||||
path = ThemeManager;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
95803FFB2413F58B00F09F2C /* libimagequant */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
9580400B2413F63400F09F2C /* blur.c */,
|
||||
958040202413F63600F09F2C /* blur.h */,
|
||||
9580400A2413F63400F09F2C /* kmeans.c */,
|
||||
958040182413F63500F09F2C /* kmeans.h */,
|
||||
958040152413F63500F09F2C /* libimagequant.c */,
|
||||
9580401F2413F63600F09F2C /* libimagequant.h */,
|
||||
9580401E2413F63600F09F2C /* mediancut.c */,
|
||||
9580401A2413F63500F09F2C /* mediancut.h */,
|
||||
958040232413F63600F09F2C /* mempool.c */,
|
||||
9580401D2413F63600F09F2C /* mempool.h */,
|
||||
958040132413F63400F09F2C /* nearest.c */,
|
||||
958040142413F63400F09F2C /* nearest.h */,
|
||||
958040172413F63500F09F2C /* pam.c */,
|
||||
958040212413F63600F09F2C /* pam.h */,
|
||||
9580403B2413F86A00F09F2C /* lodepng.h */,
|
||||
9580403C2413F8C900F09F2C /* lodepng.c */,
|
||||
);
|
||||
path = libimagequant;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
95C51578236B21AE00E4A3A8 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@ -468,6 +518,7 @@
|
||||
95E68AC8235B862F002B37A5 /* Clover */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
95803FFB2413F58B00F09F2C /* libimagequant */,
|
||||
952EB6A824018B2400BEB0F8 /* GfxUtil */,
|
||||
955BEE1123C6B43C00425AB0 /* ThemeManager */,
|
||||
95E68AC9235B862F002B37A5 /* AppDelegate.swift */,
|
||||
@ -495,9 +546,11 @@
|
||||
954DECD423899F5F006A9876 /* Bootmanager.png */,
|
||||
95E68AD2235B8632002B37A5 /* Info.plist */,
|
||||
95E68AD3235B8632002B37A5 /* Clover.entitlements */,
|
||||
954FCFD023917A8A00C9273C /* Clover-Bridging-Header.h */,
|
||||
954FCFD72391818300C9273C /* NSWindowFix.h */,
|
||||
954FCFD82391818300C9273C /* NSWindowFix.m */,
|
||||
954FCFD023917A8A00C9273C /* Clover-Bridging-Header.h */,
|
||||
9580403E2414070F00F09F2C /* PNG8Image.h */,
|
||||
9580403F2414070F00F09F2C /* PNG8Image.m */,
|
||||
);
|
||||
path = Clover;
|
||||
sourceTree = "<group>";
|
||||
@ -743,19 +796,28 @@
|
||||
files = (
|
||||
95E68AE5235B89D9002B37A5 /* Installer.swift in Sources */,
|
||||
952EB6B124018B4500BEB0F8 /* efidevp.c in Sources */,
|
||||
958040312413F63700F09F2C /* libimagequant.c in Sources */,
|
||||
95E68AE1235B86A1002B37A5 /* Shared.swift in Sources */,
|
||||
95E68ACC235B862F002B37A5 /* ViewController.swift in Sources */,
|
||||
95E68AE2235B86A1002B37A5 /* Disks.swift in Sources */,
|
||||
954FCFD92391818300C9273C /* NSWindowFix.m in Sources */,
|
||||
9580403D2413F8CA00F09F2C /* lodepng.c in Sources */,
|
||||
958040302413F63700F09F2C /* nearest.c in Sources */,
|
||||
958040372413F63700F09F2C /* mediancut.c in Sources */,
|
||||
95E68ADF235B86A1002B37A5 /* Releases.swift in Sources */,
|
||||
954BBE99238196EE0032425F /* Locale.swift in Sources */,
|
||||
95E68ACA235B862F002B37A5 /* AppDelegate.swift in Sources */,
|
||||
955BEE1523C6B49C00425AB0 /* ThemeView.swift in Sources */,
|
||||
958861DA235F75FB00B64173 /* Driver.swift in Sources */,
|
||||
958040402414070F00F09F2C /* PNG8Image.m in Sources */,
|
||||
95E68AE3235B86A1002B37A5 /* bdmesg.swift in Sources */,
|
||||
9580402E2413F63700F09F2C /* blur.c in Sources */,
|
||||
95C5152F236A0A7400E4A3A8 /* SettingsView.swift in Sources */,
|
||||
9555AF28238EFDAD00108C33 /* DriversCollection.swift in Sources */,
|
||||
952EB6AF24018B4500BEB0F8 /* gfxutil.c in Sources */,
|
||||
9580402D2413F63700F09F2C /* kmeans.c in Sources */,
|
||||
958040392413F63700F09F2C /* mempool.c in Sources */,
|
||||
958040332413F63700F09F2C /* pam.c in Sources */,
|
||||
953BC20323720C0A0039755D /* FixedWidthViews.swift in Sources */,
|
||||
95696B7B2401829800AFAD37 /* GengConfig.swift in Sources */,
|
||||
95E50076238ABA56002F3869 /* Tasks.swift in Sources */,
|
||||
@ -1103,6 +1165,7 @@
|
||||
LIBRARY_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"$(PROJECT_DIR)/Clover/Frameworks",
|
||||
"$(PROJECT_DIR)/Clover/Library",
|
||||
);
|
||||
MARKETING_VERSION = 1.16;
|
||||
OTHER_LDFLAGS = "";
|
||||
@ -1147,6 +1210,7 @@
|
||||
LIBRARY_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"$(PROJECT_DIR)/Clover/Frameworks",
|
||||
"$(PROJECT_DIR)/Clover/Library",
|
||||
);
|
||||
MARKETING_VERSION = 1.16;
|
||||
OTHER_LDFLAGS = "";
|
||||
|
@ -19,5 +19,7 @@
|
||||
#endif
|
||||
|
||||
#import "NSWindowFix.h"
|
||||
#import "PNG8Image.h"
|
||||
#import "gfxutil.h"
|
||||
#import "efidevp.h"
|
||||
|
||||
|
20
CloverApp/Clover/PNG8Image.h
Normal file
20
CloverApp/Clover/PNG8Image.h
Normal file
@ -0,0 +1,20 @@
|
||||
//
|
||||
// PNG8Image.h
|
||||
// Clover
|
||||
//
|
||||
// Created by vector sigma on 07/03/2020.
|
||||
// Copyright © 2020 CloverHackyColor. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#include "lodepng.h"
|
||||
#import "libimagequant.h"
|
||||
|
||||
//NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface PNG8Image : NSImage
|
||||
- (nullable NSData *)png8ImageDataAtPath:(NSString *_Nonnull)imagePath;
|
||||
|
||||
@end
|
||||
|
||||
//NS_ASSUME_NONNULL_END
|
84
CloverApp/Clover/PNG8Image.m
Normal file
84
CloverApp/Clover/PNG8Image.m
Normal file
@ -0,0 +1,84 @@
|
||||
//
|
||||
// PNG8Image.m
|
||||
// Clover
|
||||
//
|
||||
// Created by vector sigma on 07/03/2020.
|
||||
// Copyright © 2020 CloverHackyColor. All rights reserved.
|
||||
//
|
||||
|
||||
#import "PNG8Image.h"
|
||||
|
||||
@implementation PNG8Image
|
||||
- (nullable NSData *)png8ImageDataAtPath:(NSString *_Nonnull)imagePath {
|
||||
// Load PNG file and decode it as raw RGBA pixels
|
||||
// This uses lodepng library for PNG reading (not part of libimagequant)
|
||||
const char *input_png_file_path = [imagePath UTF8String];
|
||||
unsigned int width, height;
|
||||
unsigned char *raw_rgba_pixels;
|
||||
unsigned int status = lodepng_decode32_file(&raw_rgba_pixels, &width, &height, input_png_file_path);
|
||||
if (status) {
|
||||
NSLog(@"Can't load %s: %s\n", input_png_file_path, lodepng_error_text(status));
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Use libimagequant to make a palette for the RGBA pixels
|
||||
|
||||
liq_attr *handle = liq_attr_create();
|
||||
liq_image *input_image = liq_image_create_rgba(handle, raw_rgba_pixels, width, height, 0);
|
||||
// You could set more options here, like liq_set_quality
|
||||
liq_result *quantization_result;
|
||||
if (liq_image_quantize(input_image, handle, &quantization_result) != LIQ_OK) {
|
||||
NSLog(@"Quantization failed\n");
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Use libimagequant to make new image pixels from the palette
|
||||
|
||||
size_t pixels_size = width * height;
|
||||
unsigned char *raw_8bit_pixels = malloc(pixels_size);
|
||||
liq_set_dithering_level(quantization_result, 1.0);
|
||||
|
||||
liq_write_remapped_image(quantization_result, input_image, raw_8bit_pixels, pixels_size);
|
||||
const liq_palette *palette = liq_get_palette(quantization_result);
|
||||
|
||||
// Save converted pixels as a PNG file
|
||||
// This uses lodepng library for PNG writing (not part of libimagequant)
|
||||
|
||||
LodePNGState state;
|
||||
lodepng_state_init(&state);
|
||||
state.info_raw.colortype = LCT_PALETTE;
|
||||
state.info_raw.bitdepth = 8;
|
||||
state.info_png.color.colortype = LCT_PALETTE;
|
||||
state.info_png.color.bitdepth = 8;
|
||||
|
||||
for(int i=0; i < palette->count; i++) {
|
||||
lodepng_palette_add(&state.info_png.color, palette->entries[i].r, palette->entries[i].g, palette->entries[i].b, palette->entries[i].a);
|
||||
lodepng_palette_add(&state.info_raw, palette->entries[i].r, palette->entries[i].g, palette->entries[i].b, palette->entries[i].a);
|
||||
}
|
||||
|
||||
unsigned char *output_file_data;
|
||||
size_t output_file_size;
|
||||
unsigned int out_status = lodepng_encode(&output_file_data, &output_file_size, raw_8bit_pixels, width, height, &state);
|
||||
if (out_status) {
|
||||
NSLog(@"Can't encode image: %s\n", lodepng_error_text(out_status));
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSData *data = [NSData dataWithBytes: output_file_data length: output_file_size];
|
||||
NSImage *convertedImage = [[NSImage alloc] initWithData:data];
|
||||
if (convertedImage == nil) {
|
||||
NSLog(@"Can't convert data to NSImage\n");
|
||||
return nil;
|
||||
}
|
||||
|
||||
|
||||
liq_result_destroy(quantization_result); // Must be freed only after you're done using the palette
|
||||
liq_image_destroy(input_image);
|
||||
liq_attr_destroy(handle);
|
||||
|
||||
free(raw_8bit_pixels);
|
||||
lodepng_state_cleanup(&state);
|
||||
|
||||
return data;
|
||||
}
|
||||
@end
|
@ -17,6 +17,8 @@ let kLaunchPlistPath = "/Library/LaunchDaemons/com.slice.CloverDaemonNew.plist"
|
||||
let gHelperID : CFString = "org.slice.CloverRunAtLogin" as CFString
|
||||
let kRunAtLogin = "runAtLogin"
|
||||
|
||||
let kOptimizeTheme = "OptimizeTheme"
|
||||
|
||||
// MARK: File Manager
|
||||
let fm = FileManager.default
|
||||
|
||||
|
@ -473,5 +473,22 @@ final class ThemeManager: NSObject, URLSessionDataDelegate {
|
||||
public func exist(theme: String) -> Bool {
|
||||
return fm.fileExists(atPath: "\(self.themeManagerIndexDir)/Themes/\(theme).plist")
|
||||
}
|
||||
|
||||
public func optimizeTheme(at path: String) {
|
||||
let enumerator = fm.enumerator(atPath: path)
|
||||
while let file = enumerator?.nextObject() as? String {
|
||||
let fullPath = path.addPath(file)
|
||||
if file.fileExtension == "png" || file.fileExtension == "icns" {
|
||||
if let data = PNG8Image().png8ImageData(atPath: fullPath) {
|
||||
//print(file)
|
||||
do {
|
||||
try data.write(to: URL(fileURLWithPath: fullPath))
|
||||
} catch {
|
||||
print(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -186,6 +186,17 @@
|
||||
<action selector="unInstallPressed:" target="ClZ-60-myJ" id="tVl-6l-eul"/>
|
||||
</connections>
|
||||
</button>
|
||||
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="PtQ-Pf-Nip">
|
||||
<rect key="frame" x="162" y="22" width="202" height="18"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
|
||||
<buttonCell key="cell" type="check" title="optimize" bezelStyle="regularSquare" imagePosition="left" alignment="left" inset="2" id="Sop-mp-zDW">
|
||||
<behavior key="behavior" changeContents="YES" doesNotDimImage="YES" lightByContents="YES"/>
|
||||
<font key="font" metaFont="system"/>
|
||||
</buttonCell>
|
||||
<connections>
|
||||
<action selector="optimizeThemePressed:" target="ClZ-60-myJ" id="eFv-na-WZg"/>
|
||||
</connections>
|
||||
</button>
|
||||
</subviews>
|
||||
</view>
|
||||
<connections>
|
||||
@ -205,6 +216,7 @@
|
||||
<outlet property="installButton" destination="11W-vh-mqt" id="uVA-cy-LtI"/>
|
||||
<outlet property="installedThemesCheckBox" destination="qNn-1b-hdX" id="7cy-kq-gen"/>
|
||||
<outlet property="nameBox" destination="1Be-Yl-lqT" id="STE-Aj-xum"/>
|
||||
<outlet property="optimizeButton" destination="PtQ-Pf-Nip" id="4pd-Tf-UDz"/>
|
||||
<outlet property="sidebar" destination="ydq-wg-aj2" id="dMd-2Y-AFt"/>
|
||||
<outlet property="spinner" destination="tiZ-sK-mNx" id="jY2-rJ-ECs"/>
|
||||
<outlet property="targetPop" destination="bLz-we-3A0" id="EcP-hC-Wbm"/>
|
||||
|
@ -37,7 +37,9 @@ NSTableViewDelegate, NSTableViewDataSource, WebFrameLoadDelegate, WebUIDelegate
|
||||
@IBOutlet var spinner : NSProgressIndicator!
|
||||
@IBOutlet var installButton : NSButton!
|
||||
@IBOutlet var unistallButton : NSButton!
|
||||
@IBOutlet var optimizeButton : NSButton!
|
||||
|
||||
var isPngTheme : Bool = false
|
||||
var loaded : Bool = false
|
||||
var showInstalled : Bool = false
|
||||
|
||||
@ -210,6 +212,10 @@ NSTableViewDelegate, NSTableViewDataSource, WebFrameLoadDelegate, WebUIDelegate
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func optimizeThemePressed(_ sender: NSButton!) {
|
||||
UDs.set((sender.state == .on), forKey: kOptimizeTheme)
|
||||
}
|
||||
|
||||
func showNoThemes() {
|
||||
self.webView.mainFrame.loadHTMLString(
|
||||
"""
|
||||
@ -363,6 +369,9 @@ NSTableViewDelegate, NSTableViewDataSource, WebFrameLoadDelegate, WebUIDelegate
|
||||
completion: { (path) in
|
||||
|
||||
if let themePath = path {
|
||||
if self.optimizeButton.state == .on {
|
||||
self.manager?.optimizeTheme(at: themePath)
|
||||
}
|
||||
try? fm.removeItem(atPath: themeDest)
|
||||
do {
|
||||
try fm.moveItem(atPath: themePath, toPath: themeDest)
|
||||
@ -457,6 +466,9 @@ NSTableViewDelegate, NSTableViewDataSource, WebFrameLoadDelegate, WebUIDelegate
|
||||
}
|
||||
|
||||
func tableViewSelectionDidChange(_ notification: Notification) {
|
||||
self.isPngTheme = false
|
||||
self.optimizeButton.isEnabled = false
|
||||
self.optimizeButton.state = .off
|
||||
let sr = self.sidebar.selectedRow
|
||||
if sr >= 0 {
|
||||
if let v = self.sidebar.view(atColumn: 0, row: sr, makeIfNecessary: false) as? ThemeView {
|
||||
@ -526,10 +538,13 @@ NSTableViewDelegate, NSTableViewDataSource, WebFrameLoadDelegate, WebUIDelegate
|
||||
self.infoField.stringValue = "\(description ?? "?"), v\(version ?? "?")"
|
||||
} else {
|
||||
// get theme.plist
|
||||
self.isPngTheme = true
|
||||
let plistPath = "\((path as NSString).deletingLastPathComponent)/theme.plist"
|
||||
let plist = NSDictionary(contentsOfFile: plistPath)
|
||||
self.authorField.stringValue = (plist?.object(forKey: "Author") as? String) ?? ""
|
||||
self.infoField.stringValue = (plist?.object(forKey: "Description") as? String) ?? ""
|
||||
self.optimizeButton.isEnabled = self.installButton.isEnabled && self.isPngTheme
|
||||
self.optimizeButton.state = UDs.bool(forKey: kOptimizeTheme) ? .on : .off
|
||||
}
|
||||
}
|
||||
}
|
||||
|
65
CloverApp/Clover/libimagequant/CHANGELOG
Normal file
65
CloverApp/Clover/libimagequant/CHANGELOG
Normal file
@ -0,0 +1,65 @@
|
||||
version 2.12
|
||||
------------
|
||||
- new liq_histogram_add_fixed_color()
|
||||
- faster for large/complex images
|
||||
- workarounds for Microsoft's outdated C compiler
|
||||
|
||||
version 2.11
|
||||
------------
|
||||
- new liq_image_set_background() for high-quality remapping of GIF frames
|
||||
- new liq_image_set_importance_map() for controlling which parts of the image get more palette colors
|
||||
- improved OpenMP support
|
||||
|
||||
version 2.10
|
||||
-----------
|
||||
- supports building with Rust/Cargo
|
||||
|
||||
version 2.9
|
||||
-----------
|
||||
- new liq_histogram_add_colors()
|
||||
|
||||
version 2.8
|
||||
-----------
|
||||
- standalone version
|
||||
- added Java interface (JNI)
|
||||
- new API for remapping multiple images to a single shared palette
|
||||
|
||||
version 2.7
|
||||
-----------
|
||||
- improved dithering of saturated and semitransparent colors
|
||||
- libimagequant reports detailed progress and supports aborting of operations via callbacks
|
||||
- fixed order of log output when using openmp
|
||||
|
||||
version 2.5
|
||||
-----------
|
||||
- replaced color search algorithm with vantage point tree, which is much faster and more reliable
|
||||
- deprecated IE6 workaround
|
||||
- warn when compiled without color profile support
|
||||
- improved support for predefined colors in libimagequant
|
||||
|
||||
version 2.4
|
||||
-----------
|
||||
- fixed remapping of bright colors when dithering
|
||||
- added libimagequant API to add fixed preset colors to the palette
|
||||
|
||||
version 2.3
|
||||
-----------
|
||||
- added ./configure script for better support of Intel C compiler and dependencies [thanks to pdknsk]
|
||||
- tweaked quality metric to better estimate quality of images with large solid backgrounds [thanks to Rolf Timmermans]
|
||||
- avoid applying quality setting to images that use palette already
|
||||
|
||||
version 2.2
|
||||
-----------
|
||||
- OpenMP acceleration
|
||||
- improved support for Intel C Compiler, speedup in 32-bit GCC, and some workarounds for Visual Studio's incomplete C support
|
||||
|
||||
version 2.1
|
||||
-----------
|
||||
- option to generate posterized output (for use with 16-bit textures)
|
||||
|
||||
version 2.0
|
||||
-----------
|
||||
- refactored codebase into pngquant and standalone libimagequant
|
||||
- reduced memory usage by further 30% (and more for very large images)
|
||||
- less precise remapping improving speed by 25% in higher speed settings
|
||||
- fixed regression in dithering of alpha channel
|
74
CloverApp/Clover/libimagequant/CODE_OF_CONDUCT.md
Normal file
74
CloverApp/Clover/libimagequant/CODE_OF_CONDUCT.md
Normal file
@ -0,0 +1,74 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, gender identity and expression, level of experience,
|
||||
nationality, personal appearance, race, religion, or sexual identity and
|
||||
orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at kornel@geekhood.net. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at [http://contributor-covenant.org/version/1/4][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/4/
|
26
CloverApp/Clover/libimagequant/CONTRIBUTING.md
Normal file
26
CloverApp/Clover/libimagequant/CONTRIBUTING.md
Normal file
@ -0,0 +1,26 @@
|
||||
|
||||
Thank you for contributing! pngquant and libimagequant are licensed under multiple
|
||||
licenses, so to make things clear, I'm accepting contributions as licensed under
|
||||
the BSD 2-clause license:
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
641
CloverApp/Clover/libimagequant/COPYRIGHT
Normal file
641
CloverApp/Clover/libimagequant/COPYRIGHT
Normal file
@ -0,0 +1,641 @@
|
||||
|
||||
libimagequant is derived from code by Jef Poskanzer and Greg Roelofs
|
||||
licensed under pngquant's original license (at the end of this file),
|
||||
and contains extensive changes and additions by Kornel Lesiński
|
||||
licensed under GPL v3 or later.
|
||||
|
||||
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||
|
||||
libimagequant © 2009-2018 by Kornel Lesiński.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||
|
||||
© 1989, 1991 by Jef Poskanzer.
|
||||
© 1997, 2000, 2002 by Greg Roelofs.
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted, provided
|
||||
that the above copyright notice appear in all copies and that both that
|
||||
copyright notice and this permission notice appear in supporting
|
||||
documentation. This software is provided "as is" without express or
|
||||
implied warranty.
|
39
CloverApp/Clover/libimagequant/Cargo.toml
Normal file
39
CloverApp/Clover/libimagequant/Cargo.toml
Normal file
@ -0,0 +1,39 @@
|
||||
# libimagequant is a pure C library.
|
||||
# Rust/Cargo is entirely optional. You can also use ./configure && make
|
||||
[package]
|
||||
version = "2.12.6"
|
||||
authors = ["Kornel Lesiński <kornel@pngquant.org>"]
|
||||
build = "rust-sys/build.rs"
|
||||
categories = ["external-ffi-bindings"]
|
||||
homepage = "https://pngquant.org/lib"
|
||||
include = ["COPYRIGHT", "rust-sys/*", "*.c", "*.h", "README.md", "Cargo.toml"]
|
||||
keywords = ["pngquant"]
|
||||
license = "GPL-3.0+"
|
||||
links = "imagequant"
|
||||
name = "imagequant-sys"
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/ImageOptim/libimagequant"
|
||||
description = "Statically linked C part of imagequant library powering tools such as pngquant.\n\nThis library is dual-licensed like pngquant: either GPL or a commercial license. See website for details: https://pngquant.org"
|
||||
edition = "2018"
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.0.38"
|
||||
|
||||
[dependencies]
|
||||
rgb = "0.8.13"
|
||||
|
||||
[dependencies.openmp-sys]
|
||||
optional = true
|
||||
version = "0.1.5"
|
||||
|
||||
[features]
|
||||
default = ["sse"]
|
||||
openmp = ["openmp-sys"]
|
||||
openmp-static = ["openmp", "openmp-sys/static"]
|
||||
sse = []
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "staticlib", "lib"]
|
||||
name = "imagequant_sys"
|
||||
path = "rust-sys/libimagequant.rs"
|
||||
doctest = false
|
139
CloverApp/Clover/libimagequant/Makefile
Normal file
139
CloverApp/Clover/libimagequant/Makefile
Normal file
@ -0,0 +1,139 @@
|
||||
-include config.mk
|
||||
|
||||
STATICLIB=libimagequant.a
|
||||
SHAREDLIB=libimagequant.$(SOLIBSUFFIX)
|
||||
SOVER=0
|
||||
ifeq ($(SOLIBSUFFIX),dylib)
|
||||
SHAREDLIBVER=libimagequant.$(SOVER).$(SOLIBSUFFIX)
|
||||
FIX_INSTALL_NAME=install_name_tool -id $(LIBDIR)/$(SHAREDLIBVER) $(DESTDIR)$(LIBDIR)/$(SHAREDLIBVER)
|
||||
else
|
||||
SHAREDLIBVER=libimagequant.$(SOLIBSUFFIX).$(SOVER)
|
||||
FIX_INSTALL_NAME=
|
||||
endif
|
||||
|
||||
JNILIB=libimagequant.jnilib
|
||||
DLL=imagequant.dll
|
||||
DLLIMP=imagequant_dll.a
|
||||
DLLDEF=imagequant_dll.def
|
||||
JNIDLL=libimagequant.dll
|
||||
JNIDLLIMP=libimagequant_dll.a
|
||||
JNIDLLDEF=libimagequant_dll.def
|
||||
|
||||
OBJS = pam.o mediancut.o blur.o mempool.o kmeans.o nearest.o libimagequant.o
|
||||
SHAREDOBJS = $(subst .o,.lo,$(OBJS))
|
||||
|
||||
JAVACLASSES = org/pngquant/LiqObject.class org/pngquant/PngQuant.class org/pngquant/Image.class org/pngquant/Result.class
|
||||
JAVAHEADERS = $(JAVACLASSES:.class=.h)
|
||||
JAVAINCLUDE = -I'$(JAVA_HOME)/include' -I'$(JAVA_HOME)/include/linux' -I'$(JAVA_HOME)/include/win32' -I'$(JAVA_HOME)/include/darwin'
|
||||
|
||||
DISTFILES = $(OBJS:.o=.c) *.h README.md CHANGELOG COPYRIGHT Makefile configure imagequant.pc.in
|
||||
TARNAME = libimagequant-$(VERSION)
|
||||
TARFILE = $(TARNAME)-src.tar.bz2
|
||||
PKGCONFIG = imagequant.pc
|
||||
|
||||
all: static shared
|
||||
|
||||
static: $(STATICLIB)
|
||||
|
||||
shared: $(SHAREDLIB)
|
||||
|
||||
dll:
|
||||
$(MAKE) CFLAGS="$(CFLAGS) -DIMAGEQUANT_EXPORTS" $(DLL)
|
||||
|
||||
java: $(JNILIB)
|
||||
|
||||
java-dll:
|
||||
$(MAKE) CFLAGS="$(CFLAGS) -DIMAGEQUANT_EXPORTS" $(JNIDLL)
|
||||
|
||||
$(DLL) $(DLLIMP): $(OBJS)
|
||||
$(CC) -fPIC -shared -o $(DLL) $^ $(LDFLAGS) -Wl,--out-implib,$(DLLIMP),--output-def,$(DLLDEF)
|
||||
|
||||
$(STATICLIB): $(OBJS)
|
||||
$(AR) $(ARFLAGS) $@ $^
|
||||
|
||||
$(SHAREDOBJS):
|
||||
$(CC) -fPIC $(CFLAGS) -c $(@:.lo=.c) -o $@
|
||||
|
||||
libimagequant.so: $(SHAREDOBJS)
|
||||
$(CC) -shared -Wl,-soname,$(SHAREDLIBVER) -o $(SHAREDLIBVER) $^ $(LDFLAGS)
|
||||
ln -fs $(SHAREDLIBVER) $(SHAREDLIB)
|
||||
|
||||
libimagequant.dylib: $(SHAREDOBJS)
|
||||
$(CC) -shared -o $(SHAREDLIBVER) $^ $(LDFLAGS)
|
||||
ln -fs $(SHAREDLIBVER) $(SHAREDLIB)
|
||||
|
||||
$(OBJS): $(wildcard *.h) config.mk
|
||||
|
||||
$(JNILIB): $(JAVAHEADERS) $(STATICLIB) org/pngquant/PngQuant.c
|
||||
$(CC) -g $(CFLAGS) $(LDFLAGS) $(JAVAINCLUDE) -shared -o $@ org/pngquant/PngQuant.c $(STATICLIB)
|
||||
|
||||
$(JNIDLL) $(JNIDLLIMP): $(JAVAHEADERS) $(OBJS) org/pngquant/PngQuant.c
|
||||
$(CC) -fPIC -shared -I. $(JAVAINCLUDE) -o $(JNIDLL) $^ $(LDFLAGS) -Wl,--out-implib,$(JNIDLLIMP),--output-def,$(JNIDLLDEF)
|
||||
|
||||
$(JAVACLASSES): %.class: %.java
|
||||
javac $<
|
||||
|
||||
$(JAVAHEADERS): %.h: %.class
|
||||
javah -o $@ $(subst /,., $(patsubst %.class,%,$<)) && touch $@
|
||||
|
||||
dist: $(TARFILE) cargo
|
||||
|
||||
$(TARFILE): $(DISTFILES)
|
||||
rm -rf $(TARFILE) $(TARNAME)
|
||||
mkdir $(TARNAME)
|
||||
cp $(DISTFILES) $(TARNAME)
|
||||
tar -cjf $(TARFILE) --numeric-owner --exclude='._*' $(TARNAME)
|
||||
rm -rf $(TARNAME)
|
||||
-shasum $(TARFILE)
|
||||
|
||||
cargo:
|
||||
rm -rf msvc-dist
|
||||
git clone . -b msvc msvc-dist
|
||||
rm -rf msvc-dist/Cargo.toml msvc-dist/org msvc-dist/rust msvc-dist/README.md msvc-dist/COPYRIGHT
|
||||
cargo test
|
||||
|
||||
example: example.c lodepng.h lodepng.c $(STATICLIB)
|
||||
$(CC) -g $(CFLAGS) -Wall example.c $(STATICLIB) -o example
|
||||
|
||||
lodepng.h:
|
||||
curl -o lodepng.h -L https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.h
|
||||
|
||||
lodepng.c:
|
||||
curl -o lodepng.c -L https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.cpp
|
||||
|
||||
clean:
|
||||
rm -f $(OBJS) $(SHAREDOBJS) $(SHAREDLIBVER) $(SHAREDLIB) $(STATICLIB) $(TARFILE) $(DLL) '$(DLLIMP)' '$(DLLDEF)'
|
||||
rm -f $(JAVAHEADERS) $(JAVACLASSES) $(JNILIB) example
|
||||
|
||||
distclean: clean
|
||||
rm -f config.mk
|
||||
rm -f imagequant.pc
|
||||
|
||||
install: all $(PKGCONFIG)
|
||||
install -d $(DESTDIR)$(LIBDIR)
|
||||
install -d $(DESTDIR)$(PKGCONFIGDIR)
|
||||
install -d $(DESTDIR)$(INCLUDEDIR)
|
||||
install -m 644 $(STATICLIB) $(DESTDIR)$(LIBDIR)/$(STATICLIB)
|
||||
install -m 644 $(SHAREDLIBVER) $(DESTDIR)$(LIBDIR)/$(SHAREDLIBVER)
|
||||
ln -sf $(SHAREDLIBVER) $(DESTDIR)$(LIBDIR)/$(SHAREDLIB)
|
||||
install -m 644 $(PKGCONFIG) $(DESTDIR)$(PKGCONFIGDIR)/$(PKGCONFIG)
|
||||
install -m 644 libimagequant.h $(DESTDIR)$(INCLUDEDIR)/libimagequant.h
|
||||
$(FIX_INSTALL_NAME)
|
||||
|
||||
uninstall:
|
||||
rm -f $(DESTDIR)$(LIBDIR)/$(STATICLIB)
|
||||
rm -f $(DESTDIR)$(LIBDIR)/$(SHAREDLIBVER)
|
||||
rm -f $(DESTDIR)$(LIBDIR)/$(SHAREDLIB)
|
||||
rm -f $(DESTDIR)$(PKGCONFIGDIR)/$(PKGCONFIG)
|
||||
rm -f $(DESTDIR)$(INCLUDEDIR)/libimagequant.h
|
||||
|
||||
config.mk:
|
||||
ifeq ($(filter %clean %distclean, $(MAKECMDGOALS)), )
|
||||
./configure
|
||||
endif
|
||||
|
||||
$(PKGCONFIG): config.mk
|
||||
sed 's|PREFIX|$(PREFIX)|;s|VERSION|$(VERSION)|' < imagequant.pc.in > $(PKGCONFIG)
|
||||
|
||||
.PHONY: all static shared clean dist distclean dll java cargo
|
||||
.DELETE_ON_ERROR:
|
679
CloverApp/Clover/libimagequant/README.md
Normal file
679
CloverApp/Clover/libimagequant/README.md
Normal file
@ -0,0 +1,679 @@
|
||||
# libimagequant—Image Quantization Library
|
||||
|
||||
Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images.
|
||||
It's powering [pngquant2](https://pngquant.org).
|
||||
|
||||
## License
|
||||
|
||||
Libimagequant is dual-licensed:
|
||||
|
||||
* For Free/Libre Open Source Software it's available under GPL v3 or later with additional [copyright notices](https://raw.github.com/ImageOptim/libimagequant/master/COPYRIGHT) for older parts of the code.
|
||||
* For use in closed-source software, AppStore distribution, and other non-GPL uses, you can [obtain a commercial license](https://supso.org/projects/pngquant). Feel free to ask kornel@pngquant.org for details and custom licensing terms if you need them.
|
||||
|
||||
## Download
|
||||
|
||||
The [library](https://pngquant.org/lib) is currently a part of the [pngquant2 project](https://pngquant.org). [Repository](https://github.com/ImageOptim/libimagequant).
|
||||
|
||||
## Compiling and Linking
|
||||
|
||||
The library can be linked with ANSI C, C++, [C#](https://github.com/ImageOptim/libimagequant/blob/master/libimagequant.cs), [Rust](https://github.com/pornel/libimagequant-rust), [Java](https://github.com/ImageOptim/libimagequant/tree/master/org/pngquant) and [Golang](https://github.com/larrabee/go-imagequant) programs. It has no external dependencies.
|
||||
|
||||
To build on Unix-like systems run:
|
||||
|
||||
make static
|
||||
|
||||
it will create `libimagequant.a` which you can link with your program.
|
||||
|
||||
gcc yourprogram.c /path/to/libimagequant.a
|
||||
|
||||
On BSD, use `gmake` (GNU make) rather than the native `make`.
|
||||
|
||||
Alternatively you can compile the library with your program simply by including all `.c` files (and define `NDEBUG` to get a fast version):
|
||||
|
||||
gcc -std=c99 -O3 -DNDEBUG libimagequant/*.c yourprogram.c
|
||||
|
||||
### Building for use in Rust programs
|
||||
|
||||
In [Rust](https://www.rust-lang.org/) you can use Cargo to build the library. Add [`imagequant`](https://crates.io/crates/imagequant) to dependencies of the Rust program. You can also use `cargo build` in [`imagequant-sys`](https://crates.io/crates/imagequant-sys) to build `libimagequant.a` for any C-compatible language.
|
||||
|
||||
### Building for Java JNI
|
||||
|
||||
To build Java JNI interface, ensure `JAVA_HOME` is set to your JDK directory, and run:
|
||||
|
||||
# export JAVA_HOME=$(locate include/jni.h) # you may need to set JAVA_HOME first
|
||||
make java
|
||||
|
||||
It will create `libimagequant.jnilib` and classes in `org/pngquant/`.
|
||||
|
||||
On Windows run `make java-dll` and it'll create `libimagequant.dll` instead.
|
||||
|
||||
### Compiling on Windows/Visual Studio
|
||||
|
||||
The library can be compiled with any C compiler that has at least basic support for C99 (GCC, clang, ICC, C++ Builder, even Tiny C Compiler), but Visual Studio 2012 and older are not up to date with the 1999 C standard. There are 2 options for using `libimagequant` on Windows:
|
||||
|
||||
* Use Visual Studio **2015** and an [MSVC-compatible branch of the library](https://github.com/ImageOptim/libimagequant/tree/msvc)
|
||||
* Or use GCC from [MinGW](http://www.mingw.org) or [MSYS2](http://www.msys2.org/). Use GCC to build `libimagequant.a` (using the instructions above for Unix) and add it along with `libgcc.a` (shipped with the MinGW compiler) to your VC project.
|
||||
|
||||
### Building as shared library
|
||||
|
||||
To build on Unix-like systems run:
|
||||
|
||||
./configure --prefix=/usr
|
||||
make libimagequant.so
|
||||
|
||||
To install on Unix-like systems run:
|
||||
|
||||
make install
|
||||
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
The basic flow is:
|
||||
|
||||
1. Create attributes object and configure the library.
|
||||
2. Create image object from RGBA pixels or data source.
|
||||
3. Perform quantization (generate palette).
|
||||
4. Store remapped image and final palette.
|
||||
5. Free memory.
|
||||
|
||||
Please note that libimagequant only handles raw uncompressed arrays of pixels in memory and is completely independent of any file format.
|
||||
|
||||
<p>
|
||||
/* See example.c for the full code! */
|
||||
|
||||
#include "libimagequant.h"
|
||||
|
||||
liq_attr *attr = liq_attr_create();
|
||||
liq_image *image = liq_image_create_rgba(attr, example_bitmap_rgba, width, height, 0);
|
||||
liq_result *res;
|
||||
liq_image_quantize(image, attr, &res);
|
||||
|
||||
liq_write_remapped_image(res, image, example_bitmap_8bpp, example_bitmap_size);
|
||||
const liq_palette *pal = liq_get_palette(res);
|
||||
|
||||
// Save the image and the palette now.
|
||||
for(int i=0; i < pal->count; i++) {
|
||||
example_copy_palette_entry(pal->entries[i]);
|
||||
}
|
||||
// You'll need a PNG library to write to a file.
|
||||
example_write_image(example_bitmap_8bpp);
|
||||
|
||||
liq_result_destroy(res);
|
||||
liq_image_destroy(image);
|
||||
liq_attr_destroy(attr);
|
||||
|
||||
Functions returning `liq_error` return `LIQ_OK` (`0`) on success and non-zero on error.
|
||||
|
||||
It's safe to pass `NULL` to any function accepting `liq_attr`, `liq_image`, `liq_result` (in that case the error code `LIQ_INVALID_POINTER` will be returned). These objects can be reused multiple times.
|
||||
|
||||
There are 3 ways to create image object for quantization:
|
||||
|
||||
* `liq_image_create_rgba()` for simple, contiguous RGBA pixel arrays (width×height×4 bytes large bitmap).
|
||||
* `liq_image_create_rgba_rows()` for non-contiguous RGBA pixel arrays (that have padding between rows or reverse order, e.g. BMP).
|
||||
* `liq_image_create_custom()` for RGB, ABGR, YUV and all other formats that can be converted on-the-fly to RGBA (you have to supply the conversion function).
|
||||
|
||||
Note that "image" here means raw uncompressed pixels. If you have a compressed image file, such as PNG, you must use another library (e.g. libpng or lodepng) to decode it first.
|
||||
|
||||
You'll find full example code in "example.c" file in the library source directory.
|
||||
|
||||
## Functions
|
||||
|
||||
----
|
||||
|
||||
liq_attr* liq_attr_create(void);
|
||||
|
||||
Returns object that will hold initial settings (attributes) for the library. The object should be freed using `liq_attr_destroy()` after it's no longer needed.
|
||||
|
||||
Returns `NULL` in the unlikely case that the library cannot run on the current machine (e.g. the library has been compiled for SSE-capable x86 CPU and run on VIA C3 CPU).
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_set_max_colors(liq_attr* attr, int colors);
|
||||
|
||||
Specifies maximum number of colors to use. The default is 256. Instead of setting a fixed limit it's better to use `liq_set_quality()`.
|
||||
|
||||
The first argument is attributes object from `liq_attr_create()`.
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if number of colors is outside the range 2-256.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_max_colors(liq_attr* attr);
|
||||
|
||||
Returns the value set by `liq_set_max_colors()`.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_set_quality(liq_attr* attr, int minimum, int maximum);
|
||||
|
||||
Quality is in range `0` (worst) to `100` (best) and values are analoguous to JPEG quality (i.e. `80` is usually good enough).
|
||||
|
||||
Quantization will attempt to use the lowest number of colors needed to achieve `maximum` quality. `maximum` value of `100` is the default and means conversion as good as possible.
|
||||
|
||||
If it's not possible to convert the image with at least `minimum` quality (i.e. 256 colors is not enough to meet the minimum quality), then `liq_image_quantize()` will fail. The default minimum is `0` (proceeds regardless of quality).
|
||||
|
||||
Quality measures how well the generated palette fits image given to `liq_image_quantize()`. If a different image is remapped with `liq_write_remapped_image()` then actual quality may be different.
|
||||
|
||||
Regardless of the quality settings the number of colors won't exceed the maximum (see `liq_set_max_colors()`).
|
||||
|
||||
The first argument is attributes object from `liq_attr_create()`.
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if target is lower than minimum or any of them is outside the 0-100 range.
|
||||
Returns `LIQ_INVALID_POINTER` if `attr` appears to be invalid.
|
||||
|
||||
liq_attr *attr = liq_attr_create();
|
||||
liq_set_quality(attr, 50, 80); // use quality 80 if possible. Give up if quality drops below 50.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_min_quality(liq_attr* attr);
|
||||
|
||||
Returns the lower bound set by `liq_set_quality()`.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_max_quality(liq_attr* attr);
|
||||
|
||||
Returns the upper bound set by `liq_set_quality()`.
|
||||
|
||||
----
|
||||
|
||||
liq_image *liq_image_create_rgba(liq_attr *attr, void* pixels, int width, int height, double gamma);
|
||||
|
||||
Creates an object that represents the image pixels to be used for quantization and remapping. The pixel array must be contiguous run of RGBA pixels (alpha is the last component, 0 = transparent, 255 = opaque).
|
||||
|
||||
The first argument is attributes object from `liq_attr_create()`. The same `attr` object should be used for the entire process, from creation of images to quantization.
|
||||
|
||||
The `pixels` array must not be modified or freed until this object is freed with `liq_image_destroy()`. See also `liq_image_set_memory_ownership()`.
|
||||
|
||||
`width` and `height` are dimensions in pixels. An image 10x10 pixel large will need a 400-byte array.
|
||||
|
||||
If the `gamma` argument is `0`, then the default of 1/2.2 [gamma](https://en.wikipedia.org/wiki/Gamma_correction) is assumed, which is good for most sRGB images.
|
||||
Otherwise `gamma` must be > 0 and < 1, e.g. `0.45455` (1/2.2) or `0.55555` (1/1.8). Generated palette will use the same gamma unless `liq_set_output_gamma()` is used. If `liq_set_output_gamma` is not used, then it only affects whether brighter or darker areas of the image will get more palette colors allocated.
|
||||
|
||||
Returns `NULL` on failure, e.g. if `pixels` is `NULL` or `width`/`height` is <= 0.
|
||||
|
||||
----
|
||||
|
||||
liq_image *liq_image_create_rgba_rows(liq_attr *attr, void* rows[], int width, int height, double gamma);
|
||||
|
||||
Same as `liq_image_create_rgba()`, but takes an array of pointers to rows of pixels. This allows defining images with reversed rows (like in BMP), "stride" different than width or using only fragment of a larger bitmap, etc.
|
||||
|
||||
The `rows` array must have at least `height` elements, and each row must be at least `width` RGBA pixels wide.
|
||||
|
||||
unsigned char *bitmap = …;
|
||||
void *rows = malloc(height * sizeof(void*));
|
||||
int bytes_per_row = width * 4 + padding; // stride
|
||||
for(int i=0; i < height; i++) {
|
||||
rows[i] = bitmap + i * bytes_per_row;
|
||||
}
|
||||
liq_image *img = liq_image_create_rgba_rows(attr, rows, width, height, 0);
|
||||
// …
|
||||
liq_image_destroy(img);
|
||||
free(rows);
|
||||
|
||||
The row pointers and pixels must not be modified or freed until this object is freed with `liq_image_destroy()` (you can change that with `liq_image_set_memory_ownership()`).
|
||||
|
||||
See also `liq_image_create_rgba()` and `liq_image_create_custom()`.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_image_quantize(liq_image *const input_image, liq_attr *const attr, liq_result **out_result);
|
||||
|
||||
Performs quantization (palette generation) based on settings in `attr` (from `liq_attr_create()`) and pixels of the image.
|
||||
|
||||
Returns `LIQ_OK` if quantization succeeds and sets `liq_result` pointer in `out_result`. The last argument is used for receiving the `result` object:
|
||||
|
||||
liq_result *result;
|
||||
if (LIQ_OK == liq_image_quantize(img, attr, &result)) { // Note &result
|
||||
// result pointer is valid here
|
||||
}
|
||||
|
||||
Returns `LIQ_QUALITY_TOO_LOW` if quantization fails due to limit set in `liq_set_quality()`.
|
||||
|
||||
See `liq_write_remapped_image()`.
|
||||
|
||||
If you want to generate one palette for multiple images at once, see `liq_histogram_create()`.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_set_dithering_level(liq_result *res, float dither_level);
|
||||
|
||||
Enables/disables dithering in `liq_write_remapped_image()`. Dithering level must be between `0` and `1` (inclusive). Dithering level `0` enables fast non-dithered remapping. Otherwise a variation of Floyd-Steinberg error diffusion is used.
|
||||
|
||||
Precision of the dithering algorithm depends on the speed setting, see `liq_set_speed()`.
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if the dithering level is outside the 0-1 range.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_write_remapped_image(liq_result *result, liq_image *input_image, void *buffer, size_t buffer_size);
|
||||
|
||||
Remaps the image to palette and writes its pixels to the given buffer, 1 pixel per byte.
|
||||
|
||||
The buffer must be large enough to fit the entire image, i.e. width×height bytes large. For safety, pass the size of the buffer as `buffer_size`.
|
||||
|
||||
For best performance call `liq_get_palette()` *after* this function, as palette is improved during remapping (except when `liq_histogram_quantize()` is used).
|
||||
|
||||
Returns `LIQ_BUFFER_TOO_SMALL` if given size of the buffer is not enough to fit the entire image.
|
||||
|
||||
int buffer_size = width*height;
|
||||
char *buffer = malloc(buffer_size);
|
||||
if (LIQ_OK == liq_write_remapped_image(result, input_image, buffer, buffer_size)) {
|
||||
liq_palette *pal = liq_get_palette(result);
|
||||
// save image
|
||||
}
|
||||
|
||||
See `liq_get_palette()`.
|
||||
|
||||
The buffer is assumed to be contiguous, with rows ordered from top to bottom, and no gaps between rows. If you need to write rows with padding or upside-down order, then use `liq_write_remapped_image_rows()`.
|
||||
|
||||
Please note that it only writes raw uncompressed pixels to memory. It does not perform any PNG compression. If you'd like to create a PNG file then you need to pass the raw pixel data to another library, e.g. libpng or lodepng. See `rwpng.c` in `pngquant` project for an example how to do that.
|
||||
|
||||
----
|
||||
|
||||
const liq_palette *liq_get_palette(liq_result *result);
|
||||
|
||||
Returns pointer to palette optimized for image that has been quantized or remapped (final refinements are applied to the palette during remapping).
|
||||
|
||||
It's valid to call this method before remapping, if you don't plan to remap any images or want to use same palette for multiple images.
|
||||
|
||||
`liq_palette->count` contains number of colors (up to 256), `liq_palette->entries[n]` contains RGBA value for nth palette color.
|
||||
|
||||
The palette is **temporary and read-only**. You must copy the palette elsewhere *before* calling `liq_result_destroy()`.
|
||||
|
||||
Returns `NULL` on error.
|
||||
|
||||
----
|
||||
|
||||
void liq_attr_destroy(liq_attr *);
|
||||
void liq_image_destroy(liq_image *);
|
||||
void liq_result_destroy(liq_result *);
|
||||
void liq_histogram_destroy(liq_histogram *);
|
||||
|
||||
Releases memory owned by the given object. Object must not be used any more after it has been freed.
|
||||
|
||||
Freeing `liq_result` also frees any `liq_palette` obtained from it.
|
||||
|
||||
## Advanced Functions
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_set_speed(liq_attr* attr, int speed);
|
||||
|
||||
Higher speed levels disable expensive algorithms and reduce quantization precision. The default speed is `4`. Speed `1` gives marginally better quality at significant CPU cost. Speed `10` has usually 5% lower quality, but is 8 times faster than the default.
|
||||
|
||||
High speeds combined with `liq_set_quality()` will use more colors than necessary and will be less likely to meet minimum required quality.
|
||||
|
||||
<table><caption>Features dependent on speed</caption>
|
||||
<tr><th>Noise-sensitive dithering</th><td>speed 1 to 5</td></tr>
|
||||
<tr><th>Forced posterization</th><td>8-10 or if image has more than million colors</td></tr>
|
||||
<tr><th>Quantization error known</th><td>1-7 or if minimum quality is set</td></tr>
|
||||
<tr><th>Additional quantization techniques</th><td>1-6</td></tr>
|
||||
</table>
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if the speed is outside the 1-10 range.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_speed(liq_attr* attr);
|
||||
|
||||
Returns the value set by `liq_set_speed()`.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_set_min_opacity(liq_attr* attr, int min);
|
||||
|
||||
Alpha values higher than this will be rounded to opaque. This is a workaround for Internet Explorer 6, but because this browser is not used any more, this option is deprecated and will be removed. The default is `255` (no change).
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if the value is outside the 0-255 range.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_min_opacity(liq_attr* attr);
|
||||
|
||||
Returns the value set by `liq_set_min_opacity()`.
|
||||
|
||||
----
|
||||
|
||||
liq_set_min_posterization(liq_attr* attr, int bits);
|
||||
|
||||
Ignores given number of least significant bits in all channels, posterizing image to `2^bits` levels. `0` gives full quality. Use `2` for VGA or 16-bit RGB565 displays, `4` if image is going to be output on a RGB444/RGBA4444 display (e.g. low-quality textures on Android).
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if the value is outside the 0-4 range.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_min_posterization(liq_attr* attr);
|
||||
|
||||
Returns the value set by `liq_set_min_posterization()`.
|
||||
|
||||
----
|
||||
|
||||
liq_set_last_index_transparent(liq_attr* attr, int is_last);
|
||||
|
||||
`0` (default) makes alpha colors sorted before opaque colors. Non-`0` mixes colors together except completely transparent color, which is moved to the end of the palette. This is a workaround for programs that blindly assume the last palette entry is transparent.
|
||||
|
||||
----
|
||||
|
||||
liq_image *liq_image_create_custom(liq_attr *attr, liq_image_get_rgba_row_callback *row_callback, void *user_info, int width, int height, double gamma);
|
||||
|
||||
<p>
|
||||
|
||||
void image_get_rgba_row_callback(liq_color row_out[], int row_index, int width, void *user_info) {
|
||||
for(int column_index=0; column_index < width; column_index++) {
|
||||
row_out[column_index] = /* generate pixel at (row_index, column_index) */;
|
||||
}
|
||||
}
|
||||
|
||||
Creates image object that will use callback to read image data. This allows on-the-fly conversion of images that are not in the RGBA color space.
|
||||
|
||||
`user_info` value will be passed to the callback. It may be useful for storing pointer to program's internal representation of the image.
|
||||
|
||||
The callback must read/generate `row_index`-th row and write its RGBA pixels to the `row_out` array. Row `width` is given for convenience and will always equal to image width.
|
||||
|
||||
The callback will be called multiple times for each row. Quantization and remapping require at least two full passes over image data, so caching of callback's work makes no sense — in such case it's better to convert entire image and use `liq_image_create_rgba()` instead.
|
||||
|
||||
To use RGB image:
|
||||
|
||||
void rgb_to_rgba_callback(liq_color row_out[], int row_index, int width, void *user_info) {
|
||||
unsigned char *rgb_row = ((unsigned char *)user_info) + 3*width*row_index;
|
||||
|
||||
for(int i=0; i < width; i++) {
|
||||
row_out[i].r = rgb_row[i*3];
|
||||
row_out[i].g = rgb_row[i*3+1];
|
||||
row_out[i].b = rgb_row[i*3+2];
|
||||
row_out[i].a = 255;
|
||||
}
|
||||
}
|
||||
liq_image *img = liq_image_create_custom(attr, rgb_to_rgba_callback, rgb_bitmap, width, height, 0);
|
||||
|
||||
The library doesn't support RGB bitmaps "natively", because supporting only single format allows compiler to inline more code, 4-byte pixel alignment is faster, and SSE instructions operate on 4 values at once, so alpha support is almost free.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_image_set_memory_ownership(liq_image *image, int ownership_flags);
|
||||
|
||||
Passes ownership of image pixel data and/or its rows array to the `liq_image` object, so you don't have to free it yourself. Memory owned by the object will be freed at its discretion with `free` function specified in `liq_attr_create_with_allocator()` (by default it's stdlib's `free()`).
|
||||
|
||||
* `LIQ_OWN_PIXELS` makes pixel array owned by the object. The pixels will be freed automatically at any point when it's no longer needed. If you set this flag you must **not** free the pixel array yourself. If the image has been created with `liq_image_create_rgba_rows()` then the starting address of the array of pixels is assumed to be the lowest address of any row.
|
||||
|
||||
* `LIQ_OWN_ROWS` makes array of row pointers (but not the pixels pointed by these rows) owned by the object. Rows will be freed when object is deallocated. If you set this flag you must **not** free the rows array yourself. This flag is valid only if the object has been created with `liq_image_create_rgba_rows()`.
|
||||
|
||||
These flags can be combined with binary *or*, i.e. `LIQ_OWN_PIXELS | LIQ_OWN_ROWS`.
|
||||
|
||||
This function must not be used if the image has been created with `liq_image_create_custom()`.
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if invalid flags are specified or the image object only takes pixels from a callback.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_image_set_background(liq_image *image, liq_image *background_image);
|
||||
|
||||
Analyze and remap this image with assumption that it will be always presented exactly on top of this background.
|
||||
|
||||
When this image is remapped to a palette with a fully transparent color (use `liq_image_add_fixed_color()` to ensure this) pixels that are better represented by the background than the palette will be made transparent. This function can be used to improve quality of animated GIFs by setting previous animation frame as the background.
|
||||
|
||||
This function takes full ownership of the background image, so you should **not** free the background object. It will be freed automatically together with the foreground image.
|
||||
|
||||
Returns `LIQ_BUFFER_TOO_SMALL` if the background image has a different size than the foreground.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_image_set_importance_map(liq_image *image, unsigned char map[], size_t buffer_size, liq_ownership ownership);
|
||||
|
||||
Impotance map controls which areas of the image get more palette colors. Pixels corresponding to 0 values in the map are completely ignored. The higher the value the more weight is placed on the given pixel, giving it higher chance of influencing the final palette.
|
||||
|
||||
The map is one byte per pixel and must have the same size as the image (width×height bytes). `buffer_size` argument is used to double-check that.
|
||||
|
||||
If the `ownership` is `LIQ_COPY_PIXELS` then the `map` content be copied immediately (it's up to you to ensure the `map` memory is freed).
|
||||
|
||||
If the `ownership` is `LIQ_OWN_PIXELS` then the `map` memory will be owned by the image and will be freed automatically when the image is freed. If a custom allocator has been set using `liq_attr_create_with_allocator()`, the `map` must be allocated using the same allocator.
|
||||
|
||||
Returns `LIQ_INVALID_POINTER` if any pointer is `NULL`, `LIQ_BUFFER_TOO_SMALL` if the `buffer_size` does not match the image size, and `LIQ_UNSUPPORTED` if `ownership` isn't a valid value.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_write_remapped_image_rows(liq_result *result, liq_image *input_image, unsigned char **row_pointers);
|
||||
|
||||
Similar to `liq_write_remapped_image()`. Writes remapped image, at 1 byte per pixel, to each row pointed by `row_pointers` array. The array must have at least as many elements as height of the image, and each row must have at least as many bytes as width of the image. Rows must not overlap.
|
||||
|
||||
For best performance call `liq_get_palette()` *after* this function, as remapping may change the palette (except when `liq_histogram_quantize()` is used).
|
||||
|
||||
Returns `LIQ_INVALID_POINTER` if `result` or `input_image` is `NULL`.
|
||||
|
||||
----
|
||||
|
||||
double liq_get_quantization_error(liq_result *result);
|
||||
|
||||
Returns mean square error of quantization (square of difference between pixel values in the source image and its remapped version). Alpha channel, gamma correction and approximate importance of pixels is taken into account, so the result isn't exactly the mean square error of all channels.
|
||||
|
||||
For most images MSE 1-5 is excellent. 7-10 is OK. 20-30 will have noticeable errors. 100 is awful.
|
||||
|
||||
This function may return `-1` if the value is not available (this happens when a high speed has been requested, the image hasn't been remapped yet, and quality limit hasn't been set, see `liq_set_speed()` and `liq_set_quality()`). The value is not updated when multiple images are remapped, it applies only to the image used in `liq_image_quantize()` or the first image that has been remapped. See `liq_get_remapping_error()`.
|
||||
|
||||
----
|
||||
|
||||
double liq_get_remapping_error(liq_result *result);
|
||||
|
||||
Returns mean square error of last remapping done (square of difference between pixel values in the remapped image and its remapped version). Alpha channel and gamma correction are taken into account, so the result isn't exactly the mean square error of all channels.
|
||||
|
||||
This function may return `-1` if the value is not available (this happens when a high speed has been requested or the image hasn't been remapped yet).
|
||||
|
||||
----
|
||||
|
||||
double liq_get_quantization_quality(liq_result *result);
|
||||
|
||||
Analoguous to `liq_get_quantization_error()`, but returns quantization error as quality value in the same 0-100 range that is used by `liq_set_quality()`.
|
||||
|
||||
It may return `-1` if the value is not available (see note in `liq_get_quantization_error()`).
|
||||
|
||||
This function can be used to add upper limit to quality options presented to the user, e.g.
|
||||
|
||||
liq_attr *attr = liq_attr_create();
|
||||
liq_image *img = liq_image_create_rgba(…);
|
||||
liq_result *res;
|
||||
liq_image_quantize(img, attr, &res);
|
||||
int max_attainable_quality = liq_get_quantization_quality(res);
|
||||
printf("Please select quality between 0 and %d: ", max_attainable_quality);
|
||||
int user_selected_quality = prompt();
|
||||
if (user_selected_quality < max_attainable_quality) {
|
||||
liq_set_quality(user_selected_quality, 0);
|
||||
liq_result_destroy(res);
|
||||
liq_image_quantize(img, attr, &res);
|
||||
}
|
||||
liq_write_remapped_image(…);
|
||||
|
||||
----
|
||||
|
||||
double liq_get_remapping_quality(liq_result *result);
|
||||
|
||||
Analoguous to `liq_get_remapping_error()`, but returns quantization error as quality value in the same 0-100 range that is used by `liq_set_quality()`.
|
||||
|
||||
----
|
||||
|
||||
void liq_set_log_callback(liq_attr*, liq_log_callback_function*, void *user_info);
|
||||
|
||||
<p>
|
||||
|
||||
void log_callback_function(const liq_attr*, const char *message, void *user_info) {}
|
||||
|
||||
----
|
||||
|
||||
void liq_set_log_flush_callback(liq_attr*, liq_log_flush_callback_function*, void *user_info);
|
||||
<p>
|
||||
|
||||
void log_flush_callback_function(const liq_attr*, void *user_info) {}
|
||||
|
||||
Sets up callback function to be called when the library reports status or errors. The callback must not call any library functions.
|
||||
|
||||
`user_info` value will be passed through to the callback. It can be `NULL`.
|
||||
|
||||
`NULL` callback clears the current callback.
|
||||
|
||||
In the log callback the `message` is a zero-terminated string containing informative message to output. It is valid only until the callback returns, so you must copy it.
|
||||
|
||||
`liq_set_log_flush_callback()` sets up callback function that will be called after the last log callback, which can be used to flush buffers and free resources used by the log callback.
|
||||
|
||||
----
|
||||
|
||||
void liq_set_progress_callback(liq_attr*, liq_progress_callback_function*, void *user_info);
|
||||
void liq_result_set_progress_callback(liq_result*, liq_progress_callback_function*, void *user_info);
|
||||
|
||||
<p>
|
||||
|
||||
int progress_callback_function(const liq_attr*, float progress_percent, void *user_info) {}
|
||||
|
||||
Sets up callback function to be called while the library is processing images. The callback may abort processing by returning `0`.
|
||||
|
||||
Setting callback to `NULL` clears the current callback. `liq_set_progress_callback` is for quantization progress, and `liq_result_set_progress_callback` is for remapping progress (currently only dithered remapping reports progress).
|
||||
|
||||
`user_info` value will be passed through to the callback. It can be `NULL`.
|
||||
|
||||
The callback must not call any library functions.
|
||||
|
||||
`progress_percent` is a value between 0 and 100 that estimates how much of the current task has been done.
|
||||
|
||||
The callback should return `1` to continue the operation, and `0` to abort current operation.
|
||||
|
||||
----
|
||||
|
||||
liq_attr* liq_attr_create_with_allocator(void* (*malloc)(size_t), void (*free)(void*));
|
||||
|
||||
Same as `liq_attr_create`, but uses given `malloc` and `free` replacements to allocate all memory used by the library.
|
||||
|
||||
The `malloc` function must return 16-byte aligned memory on x86 (and on other architectures memory aligned for `double` and pointers). Conversely, if your stdlib's `malloc` doesn't return appropriately aligned memory, you should use this function to provide aligned replacements.
|
||||
|
||||
----
|
||||
|
||||
liq_attr* liq_attr_copy(liq_attr *orig);
|
||||
|
||||
Creates an independent copy of `liq_attr`. The copy should also be freed using `liq_attr_destroy()`.
|
||||
|
||||
---
|
||||
|
||||
liq_error liq_set_output_gamma(liq_result* res, double gamma);
|
||||
|
||||
Sets gamma correction for generated palette and remapped image. Must be > 0 and < 1, e.g. `0.45455` for gamma 1/2.2 in PNG images. By default output gamma is same as gamma of the input image.
|
||||
|
||||
----
|
||||
|
||||
int liq_image_get_width(const liq_image *img);
|
||||
int liq_image_get_height(const liq_image *img);
|
||||
double liq_get_output_gamma(const liq_result *result);
|
||||
|
||||
Getters for `width`, `height` and `gamma` of the input image.
|
||||
|
||||
If the input is invalid, these all return -1.
|
||||
|
||||
---
|
||||
|
||||
liq_error liq_image_add_fixed_color(liq_image* img, liq_color color);
|
||||
liq_error liq_histogram_add_fixed_color(liq_histogram* hist, liq_color color, double gamma);
|
||||
|
||||
Reserves a color in the output palette created from this image. It behaves as if the given color was used in the image and was very important.
|
||||
|
||||
RGB values of `liq_color` are assumed to have the same gamma as the image. For the histogram function, the `gamma` can be `0` (see `liq_image_create_rgba()`).
|
||||
|
||||
It must be called before the image is quantized.
|
||||
|
||||
Returns error if more than 256 colors are added. If image is quantized to fewer colors than the number of fixed colors added, then excess fixed colors will be ignored.
|
||||
|
||||
For histograms see also a more flexible `liq_histogram_add_colors()`.
|
||||
|
||||
---
|
||||
|
||||
int liq_version();
|
||||
|
||||
Returns version of the library as an integer. Same as `LIQ_VERSION`. Human-readable version is defined as `LIQ_VERSION_STRING`.
|
||||
|
||||
## Multiple images with the same palette
|
||||
|
||||
It's possible to efficiently generate a single palette that is optimal for multiple images, e.g. for an APNG animation. This is done by collecting statistics of images in a `liq_histogram` object.
|
||||
|
||||
liq_attr *attr = liq_attr_create();
|
||||
liq_histogram *hist = liq_histogram_create(attr);
|
||||
|
||||
liq_image *image1 = liq_image_create_rgba(attr, example_bitmap_rgba1, width, height, 0);
|
||||
liq_histogram_add_image(hist, attr, image1);
|
||||
|
||||
liq_image *image2 = liq_image_create_rgba(attr, example_bitmap_rgba2, width, height, 0);
|
||||
liq_histogram_add_image(hist, attr, image2);
|
||||
|
||||
liq_result *result;
|
||||
liq_error err = liq_histogram_quantize(attr, hist, &result);
|
||||
if (LIQ_OK == err) {
|
||||
// result will contain shared palette best for both image1 and image2
|
||||
}
|
||||
|
||||
---
|
||||
|
||||
liq_histogram *liq_histogram_create(liq_attr *attr);
|
||||
|
||||
Creates histogram object that will be used to collect color statistics from multiple images. It must be freed using `liq_histogram_destroy()`.
|
||||
|
||||
All options should be set on `attr` before the histogram object is created. Options changed later may not have effect.
|
||||
|
||||
---
|
||||
|
||||
liq_error liq_histogram_add_image(liq_histogram *hist, liq_attr *attr, liq_image* image);
|
||||
|
||||
"Learns" colors from the image, which will be later used to generate the palette.
|
||||
|
||||
After the image is added to the histogram it may be freed to save memory (but it's more efficient to keep the image object if it's going to be used for remapping).
|
||||
|
||||
Fixed colors added to the image are also added to the histogram. If total number of fixed colors exceeds 256, this function will fail with `LIQ_BUFFER_TOO_SMALL`.
|
||||
|
||||
---
|
||||
|
||||
liq_error liq_histogram_add_colors(liq_histogram *hist, liq_attr *attr, liq_histogram_entry entries[], int num_entries, double gamma);
|
||||
|
||||
Alternative to `liq_histogram_add_image()`. Intead of counting colors in an image, it directly takes an array of colors and their counts (see `liq_histogram_entry` in `libimagequant.h`). This function is only useful if you already have a histogram of the image from another source.
|
||||
|
||||
For description of gamma, see `liq_image_create_rgba()`.
|
||||
|
||||
---
|
||||
|
||||
liq_error liq_histogram_quantize(liq_histogram *const hist, liq_attr *const attr, liq_result **out_result);
|
||||
|
||||
Generates palette from the histogram. On success returns `LIQ_OK` and writes `liq_result*` pointer to `out_result`. Use it as follows:
|
||||
|
||||
liq_result *result;
|
||||
liq_error err = liq_histogram_quantize(attr, hist, &result);
|
||||
if (LIQ_OK == err) {
|
||||
// Use result here to remap and get palette
|
||||
}
|
||||
|
||||
Returns `LIQ_QUALITY_TOO_LOW` if the palette is worse than limit set in `liq_set_quality()`. One histogram object can be quantized only once.
|
||||
|
||||
Palette generated using this function won't be improved during remapping. If you're generating palette for only one image, it's better to use `liq_image_quantize()`.
|
||||
|
||||
## Working with GIF
|
||||
|
||||
The library can generate palettes for GIF images. To ensure correct transparency is used you need to preprocess the image yourself and replace alpha values other than 0 or 255 with one of these.
|
||||
|
||||
For animated GIFs see `liq_image_set_background()` which remaps images for GIF's "keep" frame disposal method. See [gif.ski](https://gif.ski).
|
||||
|
||||
## Multithreading
|
||||
|
||||
The library is stateless and doesn't use any global or thread-local storage. It doesn't use any locks.
|
||||
|
||||
* Different threads can perform unrelated quantizations/remappings at the same time (e.g. each thread working on a different image).
|
||||
* The same `liq_attr`, `liq_result`, etc. can be accessed from different threads, but not at the same time (e.g. you can create `liq_attr` in one thread and free it in another).
|
||||
|
||||
The library needs to sort unique colors present in the image. Although the sorting algorithm does few things to make stack usage minimal in typical cases, there is no guarantee against extremely degenerate cases, so threads should have automatically growing stack.
|
||||
|
||||
### OpenMP
|
||||
|
||||
The library will parallelize some operations if compiled with OpenMP.
|
||||
|
||||
You must not increase number of maximum threads after `liq_image` has been created, as it allocates some per-thread buffers.
|
||||
|
||||
Callback of `liq_image_create_custom()` may be called from different threads at the same time.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
Thanks to Irfan Skiljan for helping test the first version of the library.
|
||||
|
||||
The library is developed by [Kornel Lesiński](mailto:%20kornel@pngquant.org).
|
132
CloverApp/Clover/libimagequant/blur.c
Normal file
132
CloverApp/Clover/libimagequant/blur.c
Normal file
@ -0,0 +1,132 @@
|
||||
/*
|
||||
© 2011-2015 by Kornel Lesiński.
|
||||
|
||||
This file is part of libimagequant.
|
||||
|
||||
libimagequant is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
libimagequant is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with libimagequant. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "pam.h"
|
||||
#include "blur.h"
|
||||
|
||||
/*
|
||||
Blurs image horizontally (width 2*size+1) and writes it transposed to dst (called twice gives 2d blur)
|
||||
*/
|
||||
static void transposing_1d_blur(unsigned char *restrict src, unsigned char *restrict dst, unsigned int width, unsigned int height, const unsigned int size)
|
||||
{
|
||||
assert(size > 0);
|
||||
|
||||
for(unsigned int j=0; j < height; j++) {
|
||||
unsigned char *restrict row = src + j*width;
|
||||
|
||||
// accumulate sum for pixels outside line
|
||||
unsigned int sum;
|
||||
sum = row[0]*size;
|
||||
for(unsigned int i=0; i < size; i++) {
|
||||
sum += row[i];
|
||||
}
|
||||
|
||||
// blur with left side outside line
|
||||
for(unsigned int i=0; i < size; i++) {
|
||||
sum -= row[0];
|
||||
sum += row[i+size];
|
||||
|
||||
dst[i*height + j] = sum / (size*2);
|
||||
}
|
||||
|
||||
for(unsigned int i=size; i < width-size; i++) {
|
||||
sum -= row[i-size];
|
||||
sum += row[i+size];
|
||||
|
||||
dst[i*height + j] = sum / (size*2);
|
||||
}
|
||||
|
||||
// blur with right side outside line
|
||||
for(unsigned int i=width-size; i < width; i++) {
|
||||
sum -= row[i-size];
|
||||
sum += row[width-1];
|
||||
|
||||
dst[i*height + j] = sum / (size*2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks maximum of neighboring pixels (blur + lighten)
|
||||
*/
|
||||
LIQ_PRIVATE void liq_max3(unsigned char *src, unsigned char *dst, unsigned int width, unsigned int height)
|
||||
{
|
||||
for(unsigned int j=0; j < height; j++) {
|
||||
const unsigned char *row = src + j*width,
|
||||
*prevrow = src + (j > 1 ? j-1 : 0)*width,
|
||||
*nextrow = src + MIN(height-1,j+1)*width;
|
||||
|
||||
unsigned char prev,curr=row[0],next=row[0];
|
||||
|
||||
for(unsigned int i=0; i < width-1; i++) {
|
||||
prev=curr;
|
||||
curr=next;
|
||||
next=row[i+1];
|
||||
|
||||
unsigned char t1 = MAX(prev,next);
|
||||
unsigned char t2 = MAX(nextrow[i],prevrow[i]);
|
||||
*dst++ = MAX(curr,MAX(t1,t2));
|
||||
}
|
||||
unsigned char t1 = MAX(curr,next);
|
||||
unsigned char t2 = MAX(nextrow[width-1],prevrow[width-1]);
|
||||
*dst++ = MAX(t1,t2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks minimum of neighboring pixels (blur + darken)
|
||||
*/
|
||||
LIQ_PRIVATE void liq_min3(unsigned char *src, unsigned char *dst, unsigned int width, unsigned int height)
|
||||
{
|
||||
for(unsigned int j=0; j < height; j++) {
|
||||
const unsigned char *row = src + j*width,
|
||||
*prevrow = src + (j > 1 ? j-1 : 0)*width,
|
||||
*nextrow = src + MIN(height-1,j+1)*width;
|
||||
|
||||
unsigned char prev,curr=row[0],next=row[0];
|
||||
|
||||
for(unsigned int i=0; i < width-1; i++) {
|
||||
prev=curr;
|
||||
curr=next;
|
||||
next=row[i+1];
|
||||
|
||||
unsigned char t1 = MIN(prev,next);
|
||||
unsigned char t2 = MIN(nextrow[i],prevrow[i]);
|
||||
*dst++ = MIN(curr,MIN(t1,t2));
|
||||
}
|
||||
unsigned char t1 = MIN(curr,next);
|
||||
unsigned char t2 = MIN(nextrow[width-1],prevrow[width-1]);
|
||||
*dst++ = MIN(t1,t2);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Filters src image and saves it to dst, overwriting tmp in the process.
|
||||
Image must be width*height pixels high. Size controls radius of box blur.
|
||||
*/
|
||||
LIQ_PRIVATE void liq_blur(unsigned char *src, unsigned char *tmp, unsigned char *dst, unsigned int width, unsigned int height, unsigned int size)
|
||||
{
|
||||
assert(size > 0);
|
||||
if (width < 2*size+1 || height < 2*size+1) {
|
||||
return;
|
||||
}
|
||||
transposing_1d_blur(src, tmp, width, height, size);
|
||||
transposing_1d_blur(tmp, dst, height, width, size);
|
||||
}
|
8
CloverApp/Clover/libimagequant/blur.h
Normal file
8
CloverApp/Clover/libimagequant/blur.h
Normal file
@ -0,0 +1,8 @@
|
||||
#ifndef BLUR_H
|
||||
#define BLUR_H
|
||||
|
||||
LIQ_PRIVATE void liq_blur(unsigned char *src, unsigned char *tmp, unsigned char *dst, unsigned int width, unsigned int height, unsigned int size);
|
||||
LIQ_PRIVATE void liq_max3(unsigned char *src, unsigned char *dst, unsigned int width, unsigned int height);
|
||||
LIQ_PRIVATE void liq_min3(unsigned char *src, unsigned char *dst, unsigned int width, unsigned int height);
|
||||
|
||||
#endif
|
12
CloverApp/Clover/libimagequant/config.mk
Normal file
12
CloverApp/Clover/libimagequant/config.mk
Normal file
@ -0,0 +1,12 @@
|
||||
|
||||
# auto-generated by configure
|
||||
PREFIX = /usr/local
|
||||
LIBDIR = /usr/local/lib
|
||||
INCLUDEDIR = /usr/local/include
|
||||
PKGCONFIGDIR = /usr/local/lib/pkgconfig
|
||||
VERSION = 2.12.6
|
||||
CC = gcc
|
||||
CFLAGS = -fno-math-errno -funroll-loops -fomit-frame-pointer -Wall -std=c99 -I. -O3 -DNDEBUG -DUSE_SSE=1 -msse -mfpmath=sse -Wno-unknown-pragmas -mmacosx-version-min=10.7
|
||||
LDFLAGS = -mmacosx-version-min=10.7 -lm
|
||||
SOLIBSUFFIX = dylib
|
||||
|
276
CloverApp/Clover/libimagequant/configure
vendored
Executable file
276
CloverApp/Clover/libimagequant/configure
vendored
Executable file
@ -0,0 +1,276 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
CONFIG="config.mk"
|
||||
PREFIX="/usr/local"
|
||||
LIBDIR="$PREFIX/lib"
|
||||
INCLUDEDIR="$PREFIX/include"
|
||||
PKGCONFIGDIR="$LIBDIR/pkgconfig"
|
||||
VERSION=$(grep LIQ_VERSION_STRING libimagequant.h | grep -Eo "2\.[0-9.]+")
|
||||
|
||||
DEBUG=
|
||||
QUIET=0
|
||||
SSE=auto
|
||||
OPENMP=
|
||||
EXTRA_CFLAGS=
|
||||
EXTRA_LDFLAGS=
|
||||
|
||||
# make gcc default compiler unless CC is already set
|
||||
CC=${CC:-gcc}
|
||||
|
||||
help() {
|
||||
printf "%4s %s\n" "" "$1"
|
||||
}
|
||||
|
||||
for i in "$@"; do
|
||||
case $i in
|
||||
--help|-h)
|
||||
echo
|
||||
help "--prefix=<dir> installation directory [$PREFIX]"
|
||||
help "--libdir=<dir> installation directory [$LIBDIR]"
|
||||
help "--includedir=<dir> installation directory [$INCLUDEDIR]"
|
||||
help "--pkgconfigdir=<dir> installation directory [$PKGCONFIGDIR]"
|
||||
help "--extra-cflags=<flags> append to CFLAGS"
|
||||
help "--extra-ldflags=<flags> append to LDFLAGS"
|
||||
echo
|
||||
help "--enable-debug"
|
||||
help "--enable-sse/--disable-sse enable/disable SSE instructions"
|
||||
echo
|
||||
help "--with-openmp=static compile with multicore support"
|
||||
echo
|
||||
help "CC=<compiler> use given compiler command"
|
||||
help "CFLAGS=<flags> pass options to the compiler"
|
||||
help "LDFLAGS=<flags> pass options to the linker"
|
||||
echo
|
||||
exit 0
|
||||
;;
|
||||
# Can be set before or after configure. Latter overrides former.
|
||||
CC=*)
|
||||
CC=${i#*=}
|
||||
;;
|
||||
CFLAGS=*)
|
||||
CFLAGS=${i#*=}
|
||||
;;
|
||||
LDFLAGS=*)
|
||||
LDFLAGS=${i#*=}
|
||||
;;
|
||||
--enable-debug)
|
||||
DEBUG=1
|
||||
;;
|
||||
--enable-sse)
|
||||
SSE=1
|
||||
;;
|
||||
--disable-sse)
|
||||
SSE=0
|
||||
;;
|
||||
--quiet)
|
||||
QUIET=1
|
||||
;;
|
||||
'')
|
||||
# allows a bash quirk
|
||||
;;
|
||||
--with-openmp)
|
||||
OPENMP=1
|
||||
;;
|
||||
--with-openmp=static)
|
||||
OPENMP=static
|
||||
;;
|
||||
--prefix=*)
|
||||
PREFIX=${i#*=}
|
||||
LIBDIR="$PREFIX/lib"
|
||||
INCLUDEDIR="$PREFIX/include"
|
||||
PKGCONFIGDIR="$LIBDIR/pkgconfig"
|
||||
;;
|
||||
--libdir=*)
|
||||
LIBDIR=${i#*=}
|
||||
PKGCONFIGDIR="$LIBDIR/pkgconfig"
|
||||
;;
|
||||
--includedir=*)
|
||||
INCLUDEDIR=${i#*=}
|
||||
;;
|
||||
--pkgconfigdir=*)
|
||||
PKGCONFIGDIR=${i#*=}
|
||||
;;
|
||||
# can be used multiple times or in quotes to set multiple flags
|
||||
--extra-cflags=*)
|
||||
EXTRA_CFLAGS="$EXTRA_CFLAGS ${i#*=}"
|
||||
;;
|
||||
--extra-ldflags=*)
|
||||
EXTRA_LDFLAGS="$EXTRA_LDFLAGS ${i#*=}"
|
||||
;;
|
||||
*)
|
||||
echo "warning: unknown switch '${i%%=*}' (see $0 --help for the list)"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# If someone runs sudo make install as very first command, and configure later,
|
||||
# $CONFIG cannot be overwritten, and must be deleted before continuing.
|
||||
if [[ -f "$CONFIG" && ! -w "$CONFIG" ]]; then
|
||||
echo "Cannot overwrite file $CONFIG! Please delete it."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cflags() {
|
||||
CFLAGS="$CFLAGS $1"
|
||||
}
|
||||
|
||||
lflags() {
|
||||
LDFLAGS="$LDFLAGS $1"
|
||||
}
|
||||
|
||||
status() {
|
||||
if [ "$QUIET" -ne 1 ]; then
|
||||
printf "%10s: %s\n" "$1" "$2"
|
||||
fi
|
||||
}
|
||||
|
||||
# Append to CFLAGS if compiler supports flag, with optional prerequisite.
|
||||
# Fails on errors and warnings.
|
||||
conditional_cflags() {
|
||||
if [ -z "$(echo | "$CC" -xc -S -o /dev/null $2 $1 - 2>&1)" ]; then
|
||||
cflags "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
error() {
|
||||
status "$1" "error ... $2"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [ "$QUIET" -ne 1 ]; then
|
||||
echo
|
||||
fi
|
||||
|
||||
echo > pngquant-gcccheck.c "int main(){}"
|
||||
if ! "$CC" -std=c99 -o pngquant-gcccheck pngquant-gcccheck.c; then
|
||||
rm -f pngquant-gcccheck pngquant-gcccheck.c
|
||||
error "Compiler" "$CC failed to compile anything (make sure it's installed and supports C99)"
|
||||
fi
|
||||
rm -f pngquant-gcccheck pngquant-gcccheck.c
|
||||
|
||||
status "Compiler" "$CC"
|
||||
|
||||
# init flags
|
||||
CFLAGS=${CFLAGS:--fno-math-errno -funroll-loops -fomit-frame-pointer -Wall}
|
||||
cflags "-std=c99 -I."
|
||||
|
||||
# DEBUG
|
||||
if [ -z "$DEBUG" ]; then
|
||||
cflags "-O3 -DNDEBUG"
|
||||
status "Debug" "no"
|
||||
else
|
||||
cflags "-O1 -g -DDEBUG"
|
||||
status "Debug" "yes"
|
||||
fi
|
||||
|
||||
# SSE
|
||||
if [ "$SSE" = 'auto' ]; then
|
||||
SSE=0
|
||||
if type uname > /dev/null; then
|
||||
if [[ "$(uname -m)" =~ "amd64" || "$(uname -m)" =~ "x86_64" ||
|
||||
"$(grep -E -m1 "^flags" /proc/cpuinfo)" =~ "sse" ]]; then
|
||||
SSE=1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$SSE" -eq 1 ]; then
|
||||
status "SSE" "yes"
|
||||
cflags "-DUSE_SSE=1"
|
||||
cflags "-msse"
|
||||
# Silence a later ICC warning due to -msse working slightly different.
|
||||
conditional_cflags "-wd10121"
|
||||
# Must be set explicitly for GCC on x86_32. Other compilers imply it.
|
||||
conditional_cflags "-mfpmath=sse" "-msse"
|
||||
elif [ "$SSE" -eq 0 ]; then
|
||||
status "SSE" "no"
|
||||
cflags "-DUSE_SSE=0"
|
||||
fi
|
||||
|
||||
# OpenMP
|
||||
if [ -n "$OPENMP" ]; then
|
||||
if [ "static" = "$OPENMP" ]; then
|
||||
OPENMPFLAGS="-static-libgcc -Bstatic -fopenmp -Bdynamic"
|
||||
else
|
||||
OPENMPFLAGS="-fopenmp"
|
||||
fi
|
||||
if [[ "$("$CC" -xc -E $OPENMPFLAGS <(echo "#ifdef _OPENMP
|
||||
#include <omp.h>
|
||||
#endif") 2>&1)" =~ "omp_get_thread_num" ]]; then
|
||||
cflags "$OPENMPFLAGS"
|
||||
lflags "$OPENMPFLAGS"
|
||||
status "OpenMP" "yes"
|
||||
else
|
||||
error "OpenMP" "not supported by compiler (please install a compiler that supports OpenMP (e.g. gcc) and specify it with the CC= argument)"
|
||||
fi
|
||||
else
|
||||
# silence warnings about omp pragmas
|
||||
cflags "-Wno-unknown-pragmas"
|
||||
conditional_cflags "-wd3180" # ICC
|
||||
status "OpenMP" "no"
|
||||
fi
|
||||
|
||||
# Cocoa
|
||||
if [[ "$OSTYPE" =~ "darwin" ]]; then
|
||||
cflags "-mmacosx-version-min=10.7"
|
||||
lflags "-mmacosx-version-min=10.7"
|
||||
fi
|
||||
|
||||
if [[ "$OSTYPE" =~ "darwin" ]]; then
|
||||
SOLIBSUFFIX=dylib
|
||||
|
||||
# Search Developer SDK paths, since Apple seems to have dropped the standard Unixy ones
|
||||
XCODE_CMD="xcode-select"
|
||||
XCODE_PATH=$($XCODE_CMD -p)
|
||||
DIRS+=("$XCODE_PATH/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include $XCODE_PATH/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/lib")
|
||||
DIRS+=("$XCODE_PATH/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/usr/include $XCODE_PATH/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/usr/lib")
|
||||
elif [[ "$OSTYPE" =~ "msys" ]]; then
|
||||
SOLIBSUFFIX=dll
|
||||
else
|
||||
SOLIBSUFFIX=so
|
||||
fi
|
||||
|
||||
if [ "$QUIET" -ne 1 ]; then
|
||||
echo
|
||||
fi
|
||||
|
||||
# As of GCC 4.5, 387 fp math is significantly slower in C99 mode without this.
|
||||
# Note: CPUs without SSE2 use 387 for doubles, even when SSE fp math is set.
|
||||
conditional_cflags "-fexcess-precision=fast"
|
||||
|
||||
# Intel C++ Compiler
|
||||
|
||||
# ICC does usually only produce fast(er) code when it can optimize to the full
|
||||
# capabilites of the (Intel) CPU. This is equivalent to -march=native for GCC.
|
||||
conditional_cflags "-xHOST"
|
||||
|
||||
# Disable unsafe fp optimizations and enforce fp precision as set in the source.
|
||||
conditional_cflags "-fp-model source"
|
||||
|
||||
# Silence a gold linker warning about string misalignment.
|
||||
conditional_cflags "-falign-stack=maintain-16-byte"
|
||||
|
||||
lflags "-lm" # Ubuntu requires this library last, issue #38
|
||||
|
||||
if [ -n "$EXTRA_CFLAGS" ]; then
|
||||
cflags "$EXTRA_CFLAGS"
|
||||
fi
|
||||
|
||||
if [ -n "$EXTRA_LDFLAGS" ]; then
|
||||
lflags "$EXTRA_LDFLAGS"
|
||||
fi
|
||||
|
||||
# Overwrite previous configuration.
|
||||
echo "
|
||||
# auto-generated by configure
|
||||
PREFIX = $PREFIX
|
||||
LIBDIR = $LIBDIR
|
||||
INCLUDEDIR = $INCLUDEDIR
|
||||
PKGCONFIGDIR = $PKGCONFIGDIR
|
||||
VERSION = $VERSION
|
||||
CC = $CC
|
||||
CFLAGS = $CFLAGS
|
||||
LDFLAGS = $LDFLAGS
|
||||
SOLIBSUFFIX = $SOLIBSUFFIX
|
||||
" > "$CONFIG"
|
115
CloverApp/Clover/libimagequant/example.c
Normal file
115
CloverApp/Clover/libimagequant/example.c
Normal file
@ -0,0 +1,115 @@
|
||||
/**
|
||||
|
||||
This is an example how to write your own simple pngquant using libimagequant.
|
||||
|
||||
libimagequant works with any PNG library. This example uses lodepng, because it's easier to use than libpng.
|
||||
|
||||
To run this example, run these commands in the library directory:
|
||||
|
||||
make example
|
||||
./example /path/to/some_file.png
|
||||
|
||||
On "manually":
|
||||
|
||||
1. Get lodepng.c (download lodepng.cpp and rename it) and lodepng.h
|
||||
from http://lodev.org/lodepng/ and put them in this directry
|
||||
|
||||
2. Compile libimagequant (see README.md)
|
||||
|
||||
3. Compile and run the example:
|
||||
|
||||
gcc -O3 example.c libimagequant.a -o example
|
||||
./example truecolor_file.png
|
||||
|
||||
|
||||
This example code can be freely copied under CC0 (public domain) license.
|
||||
*/
|
||||
|
||||
#include "lodepng.h" // Get it from https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.h
|
||||
#include "lodepng.c" // Get it from https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.cpp and rename
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "libimagequant.h"
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc < 2) {
|
||||
fprintf(stderr, "Please specify a path to a PNG file\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
const char *input_png_file_path = argv[1];
|
||||
|
||||
// Load PNG file and decode it as raw RGBA pixels
|
||||
// This uses lodepng library for PNG reading (not part of libimagequant)
|
||||
|
||||
unsigned int width, height;
|
||||
unsigned char *raw_rgba_pixels;
|
||||
unsigned int status = lodepng_decode32_file(&raw_rgba_pixels, &width, &height, input_png_file_path);
|
||||
if (status) {
|
||||
fprintf(stderr, "Can't load %s: %s\n", input_png_file_path, lodepng_error_text(status));
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
// Use libimagequant to make a palette for the RGBA pixels
|
||||
|
||||
liq_attr *handle = liq_attr_create();
|
||||
liq_image *input_image = liq_image_create_rgba(handle, raw_rgba_pixels, width, height, 0);
|
||||
// You could set more options here, like liq_set_quality
|
||||
liq_result *quantization_result;
|
||||
if (liq_image_quantize(input_image, handle, &quantization_result) != LIQ_OK) {
|
||||
fprintf(stderr, "Quantization failed\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
// Use libimagequant to make new image pixels from the palette
|
||||
|
||||
size_t pixels_size = width * height;
|
||||
unsigned char *raw_8bit_pixels = malloc(pixels_size);
|
||||
liq_set_dithering_level(quantization_result, 1.0);
|
||||
|
||||
liq_write_remapped_image(quantization_result, input_image, raw_8bit_pixels, pixels_size);
|
||||
const liq_palette *palette = liq_get_palette(quantization_result);
|
||||
|
||||
// Save converted pixels as a PNG file
|
||||
// This uses lodepng library for PNG writing (not part of libimagequant)
|
||||
|
||||
LodePNGState state;
|
||||
lodepng_state_init(&state);
|
||||
state.info_raw.colortype = LCT_PALETTE;
|
||||
state.info_raw.bitdepth = 8;
|
||||
state.info_png.color.colortype = LCT_PALETTE;
|
||||
state.info_png.color.bitdepth = 8;
|
||||
|
||||
for(int i=0; i < palette->count; i++) {
|
||||
lodepng_palette_add(&state.info_png.color, palette->entries[i].r, palette->entries[i].g, palette->entries[i].b, palette->entries[i].a);
|
||||
lodepng_palette_add(&state.info_raw, palette->entries[i].r, palette->entries[i].g, palette->entries[i].b, palette->entries[i].a);
|
||||
}
|
||||
|
||||
unsigned char *output_file_data;
|
||||
size_t output_file_size;
|
||||
unsigned int out_status = lodepng_encode(&output_file_data, &output_file_size, raw_8bit_pixels, width, height, &state);
|
||||
if (out_status) {
|
||||
fprintf(stderr, "Can't encode image: %s\n", lodepng_error_text(out_status));
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
const char *output_png_file_path = "quantized_example.png";
|
||||
FILE *fp = fopen(output_png_file_path, "wb");
|
||||
if (!fp) {
|
||||
fprintf(stderr, "Unable to write to %s\n", output_png_file_path);
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
fwrite(output_file_data, 1, output_file_size, fp);
|
||||
fclose(fp);
|
||||
|
||||
printf("Written %s\n", output_png_file_path);
|
||||
|
||||
// Done. Free memory.
|
||||
|
||||
liq_result_destroy(quantization_result); // Must be freed only after you're done using the palette
|
||||
liq_image_destroy(input_image);
|
||||
liq_attr_destroy(handle);
|
||||
|
||||
free(raw_8bit_pixels);
|
||||
lodepng_state_cleanup(&state);
|
||||
}
|
10
CloverApp/Clover/libimagequant/imagequant.pc.in
Normal file
10
CloverApp/Clover/libimagequant/imagequant.pc.in
Normal file
@ -0,0 +1,10 @@
|
||||
prefix=PREFIX
|
||||
includedir=${prefix}/include
|
||||
libdir=${prefix}/lib
|
||||
|
||||
Name: imagequant
|
||||
Description: Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images.
|
||||
URL: https://pngquant.org/lib/
|
||||
Version: VERSION
|
||||
Libs: -L${libdir} -limagequant
|
||||
Cflags: -I${includedir}
|
98
CloverApp/Clover/libimagequant/kmeans.c
Normal file
98
CloverApp/Clover/libimagequant/kmeans.c
Normal file
@ -0,0 +1,98 @@
|
||||
/*
|
||||
** © 2011-2016 by Kornel Lesiński.
|
||||
** See COPYRIGHT file for license.
|
||||
*/
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "pam.h"
|
||||
#include "kmeans.h"
|
||||
#include "nearest.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifdef _OPENMP
|
||||
#include <omp.h>
|
||||
#else
|
||||
#define omp_get_max_threads() 1
|
||||
#define omp_get_thread_num() 0
|
||||
#endif
|
||||
|
||||
/*
|
||||
* K-Means iteration: new palette color is computed from weighted average of colors that map to that palette entry.
|
||||
*/
|
||||
LIQ_PRIVATE void kmeans_init(const colormap *map, const unsigned int max_threads, kmeans_state average_color[])
|
||||
{
|
||||
memset(average_color, 0, sizeof(average_color[0])*(KMEANS_CACHE_LINE_GAP+map->colors)*max_threads);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void kmeans_update_color(const f_pixel acolor, const float value, const colormap *map, unsigned int match, const unsigned int thread, kmeans_state average_color[])
|
||||
{
|
||||
match += thread * (KMEANS_CACHE_LINE_GAP+map->colors);
|
||||
average_color[match].a += acolor.a * value;
|
||||
average_color[match].r += acolor.r * value;
|
||||
average_color[match].g += acolor.g * value;
|
||||
average_color[match].b += acolor.b * value;
|
||||
average_color[match].total += value;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void kmeans_finalize(colormap *map, const unsigned int max_threads, const kmeans_state average_color[])
|
||||
{
|
||||
for (unsigned int i=0; i < map->colors; i++) {
|
||||
double a=0, r=0, g=0, b=0, total=0;
|
||||
|
||||
// Aggregate results from all threads
|
||||
for(unsigned int t=0; t < max_threads; t++) {
|
||||
const unsigned int offset = (KMEANS_CACHE_LINE_GAP+map->colors) * t + i;
|
||||
|
||||
a += average_color[offset].a;
|
||||
r += average_color[offset].r;
|
||||
g += average_color[offset].g;
|
||||
b += average_color[offset].b;
|
||||
total += average_color[offset].total;
|
||||
}
|
||||
|
||||
if (total && !map->palette[i].fixed) {
|
||||
map->palette[i].acolor = (f_pixel){
|
||||
.a = a / total,
|
||||
.r = r / total,
|
||||
.g = g / total,
|
||||
.b = b / total,
|
||||
};
|
||||
map->palette[i].popularity = total;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LIQ_PRIVATE double kmeans_do_iteration(histogram *hist, colormap *const map, kmeans_callback callback)
|
||||
{
|
||||
const unsigned int max_threads = omp_get_max_threads();
|
||||
LIQ_ARRAY(kmeans_state, average_color, (KMEANS_CACHE_LINE_GAP+map->colors) * max_threads);
|
||||
kmeans_init(map, max_threads, average_color);
|
||||
struct nearest_map *const n = nearest_init(map);
|
||||
hist_item *const achv = hist->achv;
|
||||
const int hist_size = hist->size;
|
||||
|
||||
double total_diff=0;
|
||||
#if __GNUC__ >= 9
|
||||
#pragma omp parallel for if (hist_size > 2000) \
|
||||
schedule(static) default(none) shared(achv,average_color,callback,hist_size,map,n) reduction(+:total_diff)
|
||||
#else
|
||||
#pragma omp parallel for if (hist_size > 2000) \
|
||||
schedule(static) default(none) shared(average_color,callback) reduction(+:total_diff)
|
||||
#endif
|
||||
for(int j=0; j < hist_size; j++) {
|
||||
float diff;
|
||||
unsigned int match = nearest_search(n, &achv[j].acolor, achv[j].tmp.likely_colormap_index, &diff);
|
||||
achv[j].tmp.likely_colormap_index = match;
|
||||
total_diff += diff * achv[j].perceptual_weight;
|
||||
|
||||
kmeans_update_color(achv[j].acolor, achv[j].perceptual_weight, map, match, omp_get_thread_num(), average_color);
|
||||
|
||||
if (callback) callback(&achv[j], diff);
|
||||
}
|
||||
|
||||
nearest_free(n);
|
||||
kmeans_finalize(map, max_threads, average_color);
|
||||
|
||||
return total_diff / hist->total_perceptual_weight;
|
||||
}
|
19
CloverApp/Clover/libimagequant/kmeans.h
Normal file
19
CloverApp/Clover/libimagequant/kmeans.h
Normal file
@ -0,0 +1,19 @@
|
||||
|
||||
#ifndef KMEANS_H
|
||||
#define KMEANS_H
|
||||
|
||||
// Spread memory touched by different threads at least 64B apart which I assume is the cache line size. This should avoid memory write contention.
|
||||
#define KMEANS_CACHE_LINE_GAP ((64+sizeof(kmeans_state)-1)/sizeof(kmeans_state))
|
||||
|
||||
typedef struct {
|
||||
double a, r, g, b, total;
|
||||
} kmeans_state;
|
||||
|
||||
typedef void (*kmeans_callback)(hist_item *item, float diff);
|
||||
|
||||
LIQ_PRIVATE void kmeans_init(const colormap *map, const unsigned int max_threads, kmeans_state state[]);
|
||||
LIQ_PRIVATE void kmeans_update_color(const f_pixel acolor, const float value, const colormap *map, unsigned int match, const unsigned int thread, kmeans_state average_color[]);
|
||||
LIQ_PRIVATE void kmeans_finalize(colormap *map, const unsigned int max_threads, const kmeans_state state[]);
|
||||
LIQ_PRIVATE double kmeans_do_iteration(histogram *hist, colormap *const map, kmeans_callback callback);
|
||||
|
||||
#endif
|
@ -0,0 +1,232 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 50;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
5F65D41723A04D7B003E3A5B /* nearest.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41023A04D7B003E3A5B /* nearest.c */; };
|
||||
5F65D41823A04D7B003E3A5B /* pam.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41123A04D7B003E3A5B /* pam.c */; };
|
||||
5F65D41923A04D7B003E3A5B /* mempool.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41223A04D7B003E3A5B /* mempool.c */; };
|
||||
5F65D41A23A04D7B003E3A5B /* mediancut.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41323A04D7B003E3A5B /* mediancut.c */; };
|
||||
5F65D41B23A04D7B003E3A5B /* kmeans.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41423A04D7B003E3A5B /* kmeans.c */; };
|
||||
5F65D41C23A04D7B003E3A5B /* libimagequant.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41523A04D7B003E3A5B /* libimagequant.c */; };
|
||||
5F65D41D23A04D7B003E3A5B /* blur.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41623A04D7B003E3A5B /* blur.c */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
5FB37C7723A04C7300942532 /* CopyFiles */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = "include/$(PRODUCT_NAME)";
|
||||
dstSubfolderSpec = 16;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
5F65D41023A04D7B003E3A5B /* nearest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = nearest.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41123A04D7B003E3A5B /* pam.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = pam.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41223A04D7B003E3A5B /* mempool.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mempool.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41323A04D7B003E3A5B /* mediancut.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mediancut.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41423A04D7B003E3A5B /* kmeans.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = kmeans.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41523A04D7B003E3A5B /* libimagequant.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = libimagequant.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41623A04D7B003E3A5B /* blur.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = blur.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41E23A04D93003E3A5B /* libimagequant.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = libimagequant.h; sourceTree = SOURCE_ROOT; };
|
||||
5FB37C7923A04C7300942532 /* libimagequant.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libimagequant.a; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
5FB37C7623A04C7300942532 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
5FB37C7023A04C7300942532 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5FB37C7B23A04C7300942532 /* imagequant */,
|
||||
5FB37C7A23A04C7300942532 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5FB37C7A23A04C7300942532 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5FB37C7923A04C7300942532 /* libimagequant.a */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5FB37C7B23A04C7300942532 /* imagequant */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5F65D41E23A04D93003E3A5B /* libimagequant.h */,
|
||||
5F65D41623A04D7B003E3A5B /* blur.c */,
|
||||
5F65D41423A04D7B003E3A5B /* kmeans.c */,
|
||||
5F65D41523A04D7B003E3A5B /* libimagequant.c */,
|
||||
5F65D41323A04D7B003E3A5B /* mediancut.c */,
|
||||
5F65D41223A04D7B003E3A5B /* mempool.c */,
|
||||
5F65D41023A04D7B003E3A5B /* nearest.c */,
|
||||
5F65D41123A04D7B003E3A5B /* pam.c */,
|
||||
);
|
||||
path = imagequant;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
5FB37C7823A04C7300942532 /* imagequant */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 5FB37C8223A04C7300942532 /* Build configuration list for PBXNativeTarget "imagequant" */;
|
||||
buildPhases = (
|
||||
5FB37C7523A04C7300942532 /* Sources */,
|
||||
5FB37C7623A04C7300942532 /* Frameworks */,
|
||||
5FB37C7723A04C7300942532 /* CopyFiles */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = imagequant;
|
||||
productName = imagequant;
|
||||
productReference = 5FB37C7923A04C7300942532 /* libimagequant.a */;
|
||||
productType = "com.apple.product-type.library.static";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
5FB37C7123A04C7300942532 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastUpgradeCheck = 1120;
|
||||
ORGANIZATIONNAME = "ImageOptim Ltd.";
|
||||
TargetAttributes = {
|
||||
5FB37C7823A04C7300942532 = {
|
||||
CreatedOnToolsVersion = 11.2;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 5FB37C7423A04C7300942532 /* Build configuration list for PBXProject "libimagequant-ios" */;
|
||||
compatibilityVersion = "Xcode 9.3";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = 5FB37C7023A04C7300942532;
|
||||
productRefGroup = 5FB37C7A23A04C7300942532 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
5FB37C7823A04C7300942532 /* imagequant */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
5FB37C7523A04C7300942532 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5F65D41B23A04D7B003E3A5B /* kmeans.c in Sources */,
|
||||
5F65D41923A04D7B003E3A5B /* mempool.c in Sources */,
|
||||
5F65D41823A04D7B003E3A5B /* pam.c in Sources */,
|
||||
5F65D41C23A04D7B003E3A5B /* libimagequant.c in Sources */,
|
||||
5F65D41A23A04D7B003E3A5B /* mediancut.c in Sources */,
|
||||
5F65D41723A04D7B003E3A5B /* nearest.c in Sources */,
|
||||
5F65D41D23A04D7B003E3A5B /* blur.c in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
5FB37C8023A04C7300942532 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
5FB37C8123A04C7300942532 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = "NDEBUG=1";
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
|
||||
SDKROOT = iphoneos;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
5FB37C8323A04C7300942532 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
5FB37C8423A04C7300942532 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
5FB37C7423A04C7300942532 /* Build configuration list for PBXProject "libimagequant-ios" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
5FB37C8023A04C7300942532 /* Debug */,
|
||||
5FB37C8123A04C7300942532 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
5FB37C8223A04C7300942532 /* Build configuration list for PBXNativeTarget "imagequant" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
5FB37C8323A04C7300942532 /* Debug */,
|
||||
5FB37C8423A04C7300942532 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 5FB37C7123A04C7300942532 /* Project object */;
|
||||
}
|
@ -0,0 +1,223 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 50;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
5FF4F4CD23A04EF500A3FFB5 /* libimagequant.h in Headers */ = {isa = PBXBuildFile; fileRef = 5FF4F4C523A04EF500A3FFB5 /* libimagequant.h */; };
|
||||
5FF4F4CE23A04EF500A3FFB5 /* libimagequant.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4C623A04EF500A3FFB5 /* libimagequant.c */; };
|
||||
5FF4F4CF23A04EF500A3FFB5 /* kmeans.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4C723A04EF500A3FFB5 /* kmeans.c */; };
|
||||
5FF4F4D023A04EF500A3FFB5 /* blur.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4C823A04EF500A3FFB5 /* blur.c */; };
|
||||
5FF4F4D123A04EF500A3FFB5 /* mempool.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4C923A04EF500A3FFB5 /* mempool.c */; };
|
||||
5FF4F4D223A04EF500A3FFB5 /* nearest.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4CA23A04EF500A3FFB5 /* nearest.c */; };
|
||||
5FF4F4D323A04EF500A3FFB5 /* pam.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4CB23A04EF500A3FFB5 /* pam.c */; };
|
||||
5FF4F4D423A04EF500A3FFB5 /* mediancut.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4CC23A04EF500A3FFB5 /* mediancut.c */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
5FF4F4BE23A04ED500A3FFB5 /* libimagequant.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libimagequant.a; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
5FF4F4C523A04EF500A3FFB5 /* libimagequant.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = libimagequant.h; path = ../../www/pngquant/lib/libimagequant.h; sourceTree = "<group>"; };
|
||||
5FF4F4C623A04EF500A3FFB5 /* libimagequant.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = libimagequant.c; path = ../../www/pngquant/lib/libimagequant.c; sourceTree = "<group>"; };
|
||||
5FF4F4C723A04EF500A3FFB5 /* kmeans.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = kmeans.c; path = ../../www/pngquant/lib/kmeans.c; sourceTree = "<group>"; };
|
||||
5FF4F4C823A04EF500A3FFB5 /* blur.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = blur.c; path = ../../www/pngquant/lib/blur.c; sourceTree = "<group>"; };
|
||||
5FF4F4C923A04EF500A3FFB5 /* mempool.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = mempool.c; path = ../../www/pngquant/lib/mempool.c; sourceTree = "<group>"; };
|
||||
5FF4F4CA23A04EF500A3FFB5 /* nearest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = nearest.c; path = ../../www/pngquant/lib/nearest.c; sourceTree = "<group>"; };
|
||||
5FF4F4CB23A04EF500A3FFB5 /* pam.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = pam.c; path = ../../www/pngquant/lib/pam.c; sourceTree = "<group>"; };
|
||||
5FF4F4CC23A04EF500A3FFB5 /* mediancut.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = mediancut.c; path = ../../www/pngquant/lib/mediancut.c; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
5FF4F4BC23A04ED500A3FFB5 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
5FF4F4B523A04ED500A3FFB5 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5FF4F4C823A04EF500A3FFB5 /* blur.c */,
|
||||
5FF4F4C723A04EF500A3FFB5 /* kmeans.c */,
|
||||
5FF4F4C623A04EF500A3FFB5 /* libimagequant.c */,
|
||||
5FF4F4C523A04EF500A3FFB5 /* libimagequant.h */,
|
||||
5FF4F4CC23A04EF500A3FFB5 /* mediancut.c */,
|
||||
5FF4F4C923A04EF500A3FFB5 /* mempool.c */,
|
||||
5FF4F4CA23A04EF500A3FFB5 /* nearest.c */,
|
||||
5FF4F4CB23A04EF500A3FFB5 /* pam.c */,
|
||||
5FF4F4BF23A04ED500A3FFB5 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5FF4F4BF23A04ED500A3FFB5 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5FF4F4BE23A04ED500A3FFB5 /* libimagequant.a */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXHeadersBuildPhase section */
|
||||
5FF4F4BA23A04ED500A3FFB5 /* Headers */ = {
|
||||
isa = PBXHeadersBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5FF4F4CD23A04EF500A3FFB5 /* libimagequant.h in Headers */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXHeadersBuildPhase section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
5FF4F4BD23A04ED500A3FFB5 /* imagequant */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 5FF4F4C223A04ED500A3FFB5 /* Build configuration list for PBXNativeTarget "imagequant" */;
|
||||
buildPhases = (
|
||||
5FF4F4BA23A04ED500A3FFB5 /* Headers */,
|
||||
5FF4F4BB23A04ED500A3FFB5 /* Sources */,
|
||||
5FF4F4BC23A04ED500A3FFB5 /* Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = imagequant;
|
||||
productName = imagequant;
|
||||
productReference = 5FF4F4BE23A04ED500A3FFB5 /* libimagequant.a */;
|
||||
productType = "com.apple.product-type.library.static";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
5FF4F4B623A04ED500A3FFB5 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastUpgradeCheck = 1120;
|
||||
ORGANIZATIONNAME = "ImageOptim Ltd.";
|
||||
TargetAttributes = {
|
||||
5FF4F4BD23A04ED500A3FFB5 = {
|
||||
CreatedOnToolsVersion = 11.2;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 5FF4F4B923A04ED500A3FFB5 /* Build configuration list for PBXProject "imagequant" */;
|
||||
compatibilityVersion = "Xcode 9.3";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = 5FF4F4B523A04ED500A3FFB5;
|
||||
productRefGroup = 5FF4F4BF23A04ED500A3FFB5 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
5FF4F4BD23A04ED500A3FFB5 /* imagequant */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
5FF4F4BB23A04ED500A3FFB5 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5FF4F4D323A04EF500A3FFB5 /* pam.c in Sources */,
|
||||
5FF4F4D023A04EF500A3FFB5 /* blur.c in Sources */,
|
||||
5FF4F4D223A04EF500A3FFB5 /* nearest.c in Sources */,
|
||||
5FF4F4CF23A04EF500A3FFB5 /* kmeans.c in Sources */,
|
||||
5FF4F4CE23A04EF500A3FFB5 /* libimagequant.c in Sources */,
|
||||
5FF4F4D423A04EF500A3FFB5 /* mediancut.c in Sources */,
|
||||
5FF4F4D123A04EF500A3FFB5 /* mempool.c in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
5FF4F4C023A04ED500A3FFB5 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = macosx;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
5FF4F4C123A04ED500A3FFB5 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = "NDEBUG=1";
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
SDKROOT = macosx;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
5FF4F4C323A04ED500A3FFB5 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
EXECUTABLE_PREFIX = lib;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
5FF4F4C423A04ED500A3FFB5 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
EXECUTABLE_PREFIX = lib;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
5FF4F4B923A04ED500A3FFB5 /* Build configuration list for PBXProject "imagequant" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
5FF4F4C023A04ED500A3FFB5 /* Debug */,
|
||||
5FF4F4C123A04ED500A3FFB5 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
5FF4F4C223A04ED500A3FFB5 /* Build configuration list for PBXNativeTarget "imagequant" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
5FF4F4C323A04ED500A3FFB5 /* Debug */,
|
||||
5FF4F4C423A04ED500A3FFB5 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 5FF4F4B623A04ED500A3FFB5 /* Project object */;
|
||||
}
|
2164
CloverApp/Clover/libimagequant/libimagequant.c
Normal file
2164
CloverApp/Clover/libimagequant/libimagequant.c
Normal file
File diff suppressed because it is too large
Load Diff
164
CloverApp/Clover/libimagequant/libimagequant.cs
Normal file
164
CloverApp/Clover/libimagequant/libimagequant.cs
Normal file
@ -0,0 +1,164 @@
|
||||
/*
|
||||
This is an example demonstrating use of libimagequant from C#.
|
||||
|
||||
This example code can be freely copied under CC0 (public domain) license.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct liq_color
|
||||
{
|
||||
public byte r, g, b, a;
|
||||
};
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct liq_palette
|
||||
{
|
||||
public int count;
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
|
||||
public liq_color[] entries;
|
||||
};
|
||||
|
||||
enum liq_error
|
||||
{
|
||||
LIQ_OK = 0,
|
||||
LIQ_QUALITY_TOO_LOW = 99,
|
||||
LIQ_VALUE_OUT_OF_RANGE = 100,
|
||||
LIQ_OUT_OF_MEMORY,
|
||||
LIQ_ABORTED,
|
||||
LIQ_BITMAP_NOT_AVAILABLE,
|
||||
LIQ_BUFFER_TOO_SMALL,
|
||||
LIQ_INVALID_POINTER,
|
||||
};
|
||||
|
||||
namespace liq
|
||||
{
|
||||
using liq_attr_ptr = IntPtr;
|
||||
using liq_image_ptr = IntPtr;
|
||||
using liq_result_ptr = IntPtr;
|
||||
using size_t = UIntPtr;
|
||||
|
||||
class Liq
|
||||
{
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_attr_ptr liq_attr_create();
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_attr_ptr liq_attr_copy(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern void liq_attr_destroy(liq_attr_ptr attr);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_max_colors(liq_attr_ptr attr, int colors);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_max_colors(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_speed(liq_attr_ptr attr, int speed);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_speed(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_min_opacity(liq_attr_ptr attr, int min);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_min_opacity(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_min_posterization(liq_attr_ptr attr, int bits);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_min_posterization(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_quality(liq_attr_ptr attr, int minimum, int maximum);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_min_quality(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_max_quality(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern void liq_set_last_index_transparent(liq_attr_ptr attr, int is_last);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_image_ptr liq_image_create_rgba(liq_attr_ptr attr, [In, MarshalAs(UnmanagedType.LPArray)] byte[] bitmap, int width, int height, double gamma);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_image_set_memory_ownership(liq_image_ptr image, int ownership_flags);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_image_add_fixed_color(liq_image_ptr img, liq_color color);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_image_get_width(liq_image_ptr img);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_image_get_height(liq_image_ptr img);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern void liq_image_destroy(liq_image_ptr img);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_result_ptr liq_quantize_image(liq_attr_ptr attr, liq_image_ptr input_image);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_dithering_level(liq_result_ptr res, float dither_level);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_output_gamma(liq_result_ptr res, double gamma);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern double liq_get_output_gamma(liq_result_ptr res);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern IntPtr liq_get_palette(liq_result_ptr res);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_write_remapped_image(liq_result_ptr res, liq_image_ptr input_image, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] buffer, size_t buffer_size);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern double liq_get_quantization_error(liq_result_ptr res);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_quantization_quality(liq_result_ptr res);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern double liq_get_remapping_error(liq_result_ptr res);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_remapping_quality(liq_result_ptr res);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern void liq_result_destroy(liq_result_ptr res);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_version();
|
||||
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Console.WriteLine("library version: {0}", liq_version());
|
||||
|
||||
int width = 3;
|
||||
int height = 1;
|
||||
|
||||
var attr = liq_attr_create();
|
||||
if (attr == IntPtr.Zero) throw new Exception("can't create attr");
|
||||
|
||||
byte[] bitmap = { // R, G, B, A, R, G, B, A, ...
|
||||
111, 222, 33, 255,
|
||||
255, 0, 255, 255,
|
||||
255, 0, 255, 255,
|
||||
};
|
||||
var img = liq_image_create_rgba(attr, bitmap, width, height, 0);
|
||||
if (img == IntPtr.Zero) throw new Exception("can't create image");
|
||||
|
||||
var res = liq_quantize_image(attr, img);
|
||||
if (res == IntPtr.Zero) throw new Exception("can't quantize image");
|
||||
|
||||
var buffer_size = width * height;
|
||||
var remapped = new byte[buffer_size];
|
||||
|
||||
var err = liq_write_remapped_image(res, img, remapped, (UIntPtr)buffer_size);
|
||||
if (err != liq_error.LIQ_OK)
|
||||
{
|
||||
throw new Exception("remapping error");
|
||||
}
|
||||
|
||||
Console.WriteLine("first pixel is {0}th palette entry", remapped[0]);
|
||||
|
||||
liq_palette pal = (liq_palette)Marshal.PtrToStructure(liq_get_palette(res), typeof(liq_palette));
|
||||
|
||||
Console.WriteLine("palette entries: {0}; red of first entry: {1}", pal.count, pal.entries[0].r);
|
||||
|
||||
liq_image_destroy(img);
|
||||
liq_result_destroy(res);
|
||||
liq_attr_destroy(attr);
|
||||
}
|
||||
}
|
||||
}
|
151
CloverApp/Clover/libimagequant/libimagequant.h
Normal file
151
CloverApp/Clover/libimagequant/libimagequant.h
Normal file
@ -0,0 +1,151 @@
|
||||
/*
|
||||
* https://pngquant.org
|
||||
*/
|
||||
|
||||
#ifndef LIBIMAGEQUANT_H
|
||||
#define LIBIMAGEQUANT_H
|
||||
|
||||
#ifdef IMAGEQUANT_EXPORTS
|
||||
#define LIQ_EXPORT __declspec(dllexport)
|
||||
#endif
|
||||
|
||||
#ifndef LIQ_EXPORT
|
||||
#define LIQ_EXPORT extern
|
||||
#endif
|
||||
|
||||
#define LIQ_VERSION 21206
|
||||
#define LIQ_VERSION_STRING "2.12.6"
|
||||
|
||||
#ifndef LIQ_PRIVATE
|
||||
#if defined(__GNUC__) || defined (__llvm__)
|
||||
#define LIQ_PRIVATE __attribute__((visibility("hidden")))
|
||||
#define LIQ_NONNULL __attribute__((nonnull))
|
||||
#define LIQ_USERESULT __attribute__((warn_unused_result))
|
||||
#else
|
||||
#define LIQ_PRIVATE
|
||||
#define LIQ_NONNULL
|
||||
#define LIQ_USERESULT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
typedef struct liq_attr liq_attr;
|
||||
typedef struct liq_image liq_image;
|
||||
typedef struct liq_result liq_result;
|
||||
typedef struct liq_histogram liq_histogram;
|
||||
|
||||
typedef struct liq_color {
|
||||
unsigned char r, g, b, a;
|
||||
} liq_color;
|
||||
|
||||
typedef struct liq_palette {
|
||||
unsigned int count;
|
||||
liq_color entries[256];
|
||||
} liq_palette;
|
||||
|
||||
typedef enum liq_error {
|
||||
LIQ_OK = 0,
|
||||
LIQ_QUALITY_TOO_LOW = 99,
|
||||
LIQ_VALUE_OUT_OF_RANGE = 100,
|
||||
LIQ_OUT_OF_MEMORY,
|
||||
LIQ_ABORTED,
|
||||
LIQ_BITMAP_NOT_AVAILABLE,
|
||||
LIQ_BUFFER_TOO_SMALL,
|
||||
LIQ_INVALID_POINTER,
|
||||
LIQ_UNSUPPORTED,
|
||||
} liq_error;
|
||||
|
||||
enum liq_ownership {
|
||||
LIQ_OWN_ROWS=4,
|
||||
LIQ_OWN_PIXELS=8,
|
||||
LIQ_COPY_PIXELS=16,
|
||||
};
|
||||
|
||||
typedef struct liq_histogram_entry {
|
||||
liq_color color;
|
||||
unsigned int count;
|
||||
} liq_histogram_entry;
|
||||
|
||||
LIQ_EXPORT LIQ_USERESULT liq_attr* liq_attr_create(void);
|
||||
LIQ_EXPORT LIQ_USERESULT liq_attr* liq_attr_create_with_allocator(void* (*malloc)(size_t), void (*free)(void*));
|
||||
LIQ_EXPORT LIQ_USERESULT liq_attr* liq_attr_copy(const liq_attr *orig) LIQ_NONNULL;
|
||||
LIQ_EXPORT void liq_attr_destroy(liq_attr *attr) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT LIQ_USERESULT liq_histogram* liq_histogram_create(const liq_attr* attr);
|
||||
LIQ_EXPORT liq_error liq_histogram_add_image(liq_histogram *hist, const liq_attr *attr, liq_image* image) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_histogram_add_colors(liq_histogram *hist, const liq_attr *attr, const liq_histogram_entry entries[], int num_entries, double gamma) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_histogram_add_fixed_color(liq_histogram *hist, liq_color color, double gamma) LIQ_NONNULL;
|
||||
LIQ_EXPORT void liq_histogram_destroy(liq_histogram *hist) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT liq_error liq_set_max_colors(liq_attr* attr, int colors) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_max_colors(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_set_speed(liq_attr* attr, int speed) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_speed(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_set_min_opacity(liq_attr* attr, int min) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_min_opacity(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_set_min_posterization(liq_attr* attr, int bits) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_min_posterization(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_set_quality(liq_attr* attr, int minimum, int maximum) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_min_quality(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_max_quality(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT void liq_set_last_index_transparent(liq_attr* attr, int is_last) LIQ_NONNULL;
|
||||
|
||||
typedef void liq_log_callback_function(const liq_attr*, const char *message, void* user_info);
|
||||
typedef void liq_log_flush_callback_function(const liq_attr*, void* user_info);
|
||||
LIQ_EXPORT void liq_set_log_callback(liq_attr*, liq_log_callback_function*, void* user_info);
|
||||
LIQ_EXPORT void liq_set_log_flush_callback(liq_attr*, liq_log_flush_callback_function*, void* user_info);
|
||||
|
||||
typedef int liq_progress_callback_function(float progress_percent, void* user_info);
|
||||
LIQ_EXPORT void liq_attr_set_progress_callback(liq_attr*, liq_progress_callback_function*, void* user_info);
|
||||
LIQ_EXPORT void liq_result_set_progress_callback(liq_result*, liq_progress_callback_function*, void* user_info);
|
||||
|
||||
// The rows and their data are not modified. The type of `rows` is non-const only due to a bug in C's typesystem design.
|
||||
LIQ_EXPORT LIQ_USERESULT liq_image *liq_image_create_rgba_rows(const liq_attr *attr, void *const rows[], int width, int height, double gamma) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT liq_image *liq_image_create_rgba(const liq_attr *attr, const void *bitmap, int width, int height, double gamma) LIQ_NONNULL;
|
||||
|
||||
typedef void liq_image_get_rgba_row_callback(liq_color row_out[], int row, int width, void* user_info);
|
||||
LIQ_EXPORT LIQ_USERESULT liq_image *liq_image_create_custom(const liq_attr *attr, liq_image_get_rgba_row_callback *row_callback, void* user_info, int width, int height, double gamma);
|
||||
|
||||
LIQ_EXPORT liq_error liq_image_set_memory_ownership(liq_image *image, int ownership_flags) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_image_set_background(liq_image *img, liq_image *background_image) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_image_set_importance_map(liq_image *img, unsigned char buffer[], size_t buffer_size, enum liq_ownership memory_handling) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_image_add_fixed_color(liq_image *img, liq_color color) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_image_get_width(const liq_image *img) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_image_get_height(const liq_image *img) LIQ_NONNULL;
|
||||
LIQ_EXPORT void liq_image_destroy(liq_image *img) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT LIQ_USERESULT liq_error liq_histogram_quantize(liq_histogram *const input_hist, liq_attr *const options, liq_result **result_output) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT liq_error liq_image_quantize(liq_image *const input_image, liq_attr *const options, liq_result **result_output) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT liq_error liq_set_dithering_level(liq_result *res, float dither_level) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_set_output_gamma(liq_result* res, double gamma) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT double liq_get_output_gamma(const liq_result *result) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT LIQ_USERESULT const liq_palette *liq_get_palette(liq_result *result) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT liq_error liq_write_remapped_image(liq_result *result, liq_image *input_image, void *buffer, size_t buffer_size) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_write_remapped_image_rows(liq_result *result, liq_image *input_image, unsigned char **row_pointers) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT double liq_get_quantization_error(const liq_result *result) LIQ_NONNULL;
|
||||
LIQ_EXPORT int liq_get_quantization_quality(const liq_result *result) LIQ_NONNULL;
|
||||
LIQ_EXPORT double liq_get_remapping_error(const liq_result *result) LIQ_NONNULL;
|
||||
LIQ_EXPORT int liq_get_remapping_quality(const liq_result *result) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT void liq_result_destroy(liq_result *) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT int liq_version(void);
|
||||
|
||||
|
||||
// Deprecated
|
||||
LIQ_EXPORT LIQ_USERESULT liq_result *liq_quantize_image(liq_attr *options, liq_image *input_image) LIQ_NONNULL;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
6406
CloverApp/Clover/libimagequant/lodepng.c
Normal file
6406
CloverApp/Clover/libimagequant/lodepng.c
Normal file
File diff suppressed because it is too large
Load Diff
1945
CloverApp/Clover/libimagequant/lodepng.h
Normal file
1945
CloverApp/Clover/libimagequant/lodepng.h
Normal file
File diff suppressed because it is too large
Load Diff
464
CloverApp/Clover/libimagequant/mediancut.c
Normal file
464
CloverApp/Clover/libimagequant/mediancut.c
Normal file
@ -0,0 +1,464 @@
|
||||
/*
|
||||
** © 2009-2018 by Kornel Lesiński.
|
||||
** © 1989, 1991 by Jef Poskanzer.
|
||||
** © 1997, 2000, 2002 by Greg Roelofs; based on an idea by Stefan Schneider.
|
||||
**
|
||||
** See COPYRIGHT file for license.
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "pam.h"
|
||||
#include "mediancut.h"
|
||||
|
||||
#define index_of_channel(ch) (offsetof(f_pixel,ch)/sizeof(float))
|
||||
|
||||
static f_pixel averagepixels(unsigned int clrs, const hist_item achv[]);
|
||||
|
||||
struct box {
|
||||
f_pixel color;
|
||||
f_pixel variance;
|
||||
double sum, total_error, max_error;
|
||||
unsigned int ind;
|
||||
unsigned int colors;
|
||||
};
|
||||
|
||||
ALWAYS_INLINE static double variance_diff(double val, const double good_enough);
|
||||
inline static double variance_diff(double val, const double good_enough)
|
||||
{
|
||||
val *= val;
|
||||
if (val < good_enough*good_enough) return val*0.25;
|
||||
return val;
|
||||
}
|
||||
|
||||
/** Weighted per-channel variance of the box. It's used to decide which channel to split by */
|
||||
static f_pixel box_variance(const hist_item achv[], const struct box *box)
|
||||
{
|
||||
f_pixel mean = box->color;
|
||||
double variancea=0, variancer=0, varianceg=0, varianceb=0;
|
||||
|
||||
for(unsigned int i = 0; i < box->colors; ++i) {
|
||||
const f_pixel px = achv[box->ind + i].acolor;
|
||||
double weight = achv[box->ind + i].adjusted_weight;
|
||||
variancea += variance_diff(mean.a - px.a, 2.0/256.0)*weight;
|
||||
variancer += variance_diff(mean.r - px.r, 1.0/256.0)*weight;
|
||||
varianceg += variance_diff(mean.g - px.g, 1.0/256.0)*weight;
|
||||
varianceb += variance_diff(mean.b - px.b, 1.0/256.0)*weight;
|
||||
}
|
||||
|
||||
return (f_pixel){
|
||||
.a = variancea*(4.0/16.0),
|
||||
.r = variancer*(7.0/16.0),
|
||||
.g = varianceg*(9.0/16.0),
|
||||
.b = varianceb*(5.0/16.0),
|
||||
};
|
||||
}
|
||||
|
||||
static double box_max_error(const hist_item achv[], const struct box *box)
|
||||
{
|
||||
f_pixel mean = box->color;
|
||||
double max_error = 0;
|
||||
|
||||
for(unsigned int i = 0; i < box->colors; ++i) {
|
||||
const double diff = colordifference(mean, achv[box->ind + i].acolor);
|
||||
if (diff > max_error) {
|
||||
max_error = diff;
|
||||
}
|
||||
}
|
||||
return max_error;
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static double color_weight(f_pixel median, hist_item h);
|
||||
|
||||
static inline void hist_item_swap(hist_item *l, hist_item *r)
|
||||
{
|
||||
if (l != r) {
|
||||
hist_item t = *l;
|
||||
*l = *r;
|
||||
*r = t;
|
||||
}
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static unsigned int qsort_pivot(const hist_item *const base, const unsigned int len);
|
||||
inline static unsigned int qsort_pivot(const hist_item *const base, const unsigned int len)
|
||||
{
|
||||
if (len < 32) {
|
||||
return len/2;
|
||||
}
|
||||
|
||||
const unsigned int aidx=8, bidx=len/2, cidx=len-1;
|
||||
const unsigned int a=base[aidx].tmp.sort_value, b=base[bidx].tmp.sort_value, c=base[cidx].tmp.sort_value;
|
||||
return (a < b) ? ((b < c) ? bidx : ((a < c) ? cidx : aidx ))
|
||||
: ((b > c) ? bidx : ((a < c) ? aidx : cidx ));
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static unsigned int qsort_partition(hist_item *const base, const unsigned int len);
|
||||
inline static unsigned int qsort_partition(hist_item *const base, const unsigned int len)
|
||||
{
|
||||
unsigned int l = 1, r = len;
|
||||
if (len >= 8) {
|
||||
hist_item_swap(&base[0], &base[qsort_pivot(base,len)]);
|
||||
}
|
||||
|
||||
const unsigned int pivot_value = base[0].tmp.sort_value;
|
||||
while (l < r) {
|
||||
if (base[l].tmp.sort_value >= pivot_value) {
|
||||
l++;
|
||||
} else {
|
||||
while(l < --r && base[r].tmp.sort_value <= pivot_value) {}
|
||||
hist_item_swap(&base[l], &base[r]);
|
||||
}
|
||||
}
|
||||
l--;
|
||||
hist_item_swap(&base[0], &base[l]);
|
||||
|
||||
return l;
|
||||
}
|
||||
|
||||
/** quick select algorithm */
|
||||
static void hist_item_sort_range(hist_item base[], unsigned int len, unsigned int sort_start)
|
||||
{
|
||||
for(;;) {
|
||||
const unsigned int l = qsort_partition(base, len), r = l+1;
|
||||
|
||||
if (l > 0 && sort_start < l) {
|
||||
len = l;
|
||||
}
|
||||
else if (r < len && sort_start > r) {
|
||||
base += r; len -= r; sort_start -= r;
|
||||
}
|
||||
else break;
|
||||
}
|
||||
}
|
||||
|
||||
/** sorts array to make sum of weights lower than halfvar one side, returns edge between <halfvar and >halfvar parts of the set */
|
||||
static hist_item *hist_item_sort_halfvar(hist_item base[], unsigned int len, double *const lowervar, const double halfvar)
|
||||
{
|
||||
do {
|
||||
const unsigned int l = qsort_partition(base, len), r = l+1;
|
||||
|
||||
// check if sum of left side is smaller than half,
|
||||
// if it is, then it doesn't need to be sorted
|
||||
unsigned int t = 0; double tmpsum = *lowervar;
|
||||
while (t <= l && tmpsum < halfvar) tmpsum += base[t++].color_weight;
|
||||
|
||||
if (tmpsum < halfvar) {
|
||||
*lowervar = tmpsum;
|
||||
} else {
|
||||
if (l > 0) {
|
||||
hist_item *res = hist_item_sort_halfvar(base, l, lowervar, halfvar);
|
||||
if (res) return res;
|
||||
} else {
|
||||
// End of left recursion. This will be executed in order from the first element.
|
||||
*lowervar += base[0].color_weight;
|
||||
if (*lowervar > halfvar) return &base[0];
|
||||
}
|
||||
}
|
||||
|
||||
if (len > r) {
|
||||
base += r; len -= r; // tail-recursive "call"
|
||||
} else {
|
||||
*lowervar += base[r].color_weight;
|
||||
return (*lowervar > halfvar) ? &base[r] : NULL;
|
||||
}
|
||||
} while(1);
|
||||
}
|
||||
|
||||
static f_pixel get_median(const struct box *b, hist_item achv[]);
|
||||
|
||||
typedef struct {
|
||||
unsigned int chan; float variance;
|
||||
} channelvariance;
|
||||
|
||||
static int comparevariance(const void *ch1, const void *ch2)
|
||||
{
|
||||
return ((const channelvariance*)ch1)->variance > ((const channelvariance*)ch2)->variance ? -1 :
|
||||
(((const channelvariance*)ch1)->variance < ((const channelvariance*)ch2)->variance ? 1 : 0);
|
||||
}
|
||||
|
||||
/** Finds which channels need to be sorted first and preproceses achv for fast sort */
|
||||
static double prepare_sort(struct box *b, hist_item achv[])
|
||||
{
|
||||
/*
|
||||
** Sort dimensions by their variance, and then sort colors first by dimension with highest variance
|
||||
*/
|
||||
channelvariance channels[4] = {
|
||||
{index_of_channel(a), b->variance.a},
|
||||
{index_of_channel(r), b->variance.r},
|
||||
{index_of_channel(g), b->variance.g},
|
||||
{index_of_channel(b), b->variance.b},
|
||||
};
|
||||
|
||||
qsort(channels, 4, sizeof(channels[0]), comparevariance);
|
||||
|
||||
const unsigned int ind1 = b->ind;
|
||||
const unsigned int colors = b->colors;
|
||||
#if __GNUC__ >= 9
|
||||
#pragma omp parallel for if (colors > 25000) \
|
||||
schedule(static) default(none) shared(achv, channels, colors, ind1)
|
||||
#else
|
||||
#pragma omp parallel for if (colors > 25000) \
|
||||
schedule(static) default(none) shared(achv, channels)
|
||||
#endif
|
||||
for(unsigned int i=0; i < colors; i++) {
|
||||
const float *chans = (const float *)&achv[ind1 + i].acolor;
|
||||
// Only the first channel really matters. When trying median cut many times
|
||||
// with different histogram weights, I don't want sort randomness to influence outcome.
|
||||
achv[ind1 + i].tmp.sort_value = ((unsigned int)(chans[channels[0].chan]*65535.0)<<16) |
|
||||
(unsigned int)((chans[channels[2].chan] + chans[channels[1].chan]/2.0 + chans[channels[3].chan]/4.0)*65535.0);
|
||||
}
|
||||
|
||||
const f_pixel median = get_median(b, achv);
|
||||
|
||||
// box will be split to make color_weight of each side even
|
||||
const unsigned int ind = b->ind, end = ind+b->colors;
|
||||
double totalvar = 0;
|
||||
#pragma omp parallel for if (end - ind > 15000) \
|
||||
schedule(static) default(shared) reduction(+:totalvar)
|
||||
for(unsigned int j=ind; j < end; j++) totalvar += (achv[j].color_weight = color_weight(median, achv[j]));
|
||||
return totalvar / 2.0;
|
||||
}
|
||||
|
||||
/** finds median in unsorted set by sorting only minimum required */
|
||||
static f_pixel get_median(const struct box *b, hist_item achv[])
|
||||
{
|
||||
const unsigned int median_start = (b->colors-1)/2;
|
||||
|
||||
hist_item_sort_range(&(achv[b->ind]), b->colors,
|
||||
median_start);
|
||||
|
||||
if (b->colors&1) return achv[b->ind + median_start].acolor;
|
||||
|
||||
// technically the second color is not guaranteed to be sorted correctly
|
||||
// but most of the time it is good enough to be useful
|
||||
return averagepixels(2, &achv[b->ind + median_start]);
|
||||
}
|
||||
|
||||
/*
|
||||
** Find the best splittable box. -1 if no boxes are splittable.
|
||||
*/
|
||||
static int best_splittable_box(struct box bv[], unsigned int boxes, const double max_mse)
|
||||
{
|
||||
int bi=-1; double maxsum=0;
|
||||
for(unsigned int i=0; i < boxes; i++) {
|
||||
if (bv[i].colors < 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// looks only at max variance, because it's only going to split by it
|
||||
const double cv = MAX(bv[i].variance.r, MAX(bv[i].variance.g,bv[i].variance.b));
|
||||
double thissum = bv[i].sum * MAX(bv[i].variance.a, cv);
|
||||
|
||||
if (bv[i].max_error > max_mse) {
|
||||
thissum = thissum* bv[i].max_error/max_mse;
|
||||
}
|
||||
|
||||
if (thissum > maxsum) {
|
||||
maxsum = thissum;
|
||||
bi = i;
|
||||
}
|
||||
}
|
||||
return bi;
|
||||
}
|
||||
|
||||
inline static double color_weight(f_pixel median, hist_item h)
|
||||
{
|
||||
float diff = colordifference(median, h.acolor);
|
||||
return sqrt(diff) * (sqrt(1.0+h.adjusted_weight)-1.0);
|
||||
}
|
||||
|
||||
static void set_colormap_from_boxes(colormap *map, struct box bv[], unsigned int boxes, hist_item *achv);
|
||||
static void adjust_histogram(hist_item *achv, const struct box bv[], unsigned int boxes);
|
||||
|
||||
static double box_error(const struct box *box, const hist_item achv[])
|
||||
{
|
||||
f_pixel avg = box->color;
|
||||
|
||||
double total_error=0;
|
||||
for (unsigned int i = 0; i < box->colors; ++i) {
|
||||
total_error += colordifference(avg, achv[box->ind + i].acolor) * achv[box->ind + i].perceptual_weight;
|
||||
}
|
||||
|
||||
return total_error;
|
||||
}
|
||||
|
||||
|
||||
static bool total_box_error_below_target(double target_mse, struct box bv[], unsigned int boxes, const histogram *hist)
|
||||
{
|
||||
target_mse *= hist->total_perceptual_weight;
|
||||
double total_error=0;
|
||||
|
||||
for(unsigned int i=0; i < boxes; i++) {
|
||||
// error is (re)calculated lazily
|
||||
if (bv[i].total_error >= 0) {
|
||||
total_error += bv[i].total_error;
|
||||
}
|
||||
if (total_error > target_mse) return false;
|
||||
}
|
||||
|
||||
for(unsigned int i=0; i < boxes; i++) {
|
||||
if (bv[i].total_error < 0) {
|
||||
bv[i].total_error = box_error(&bv[i], hist->achv);
|
||||
total_error += bv[i].total_error;
|
||||
}
|
||||
if (total_error > target_mse) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static void box_init(struct box *box, const hist_item *achv, const unsigned int ind, const unsigned int colors, const double sum) {
|
||||
box->ind = ind;
|
||||
box->colors = colors;
|
||||
box->sum = sum;
|
||||
box->total_error = -1;
|
||||
|
||||
box->color = averagepixels(colors, &achv[ind]);
|
||||
box->variance = box_variance(achv, box);
|
||||
box->max_error = box_max_error(achv, box);
|
||||
}
|
||||
|
||||
/*
|
||||
** Here is the fun part, the median-cut colormap generator. This is based
|
||||
** on Paul Heckbert's paper, "Color Image Quantization for Frame Buffer
|
||||
** Display," SIGGRAPH 1982 Proceedings, page 297.
|
||||
*/
|
||||
LIQ_PRIVATE colormap *mediancut(histogram *hist, unsigned int newcolors, const double target_mse, const double max_mse, void* (*malloc)(size_t), void (*free)(void*))
|
||||
{
|
||||
hist_item *achv = hist->achv;
|
||||
LIQ_ARRAY(struct box, bv, newcolors);
|
||||
unsigned int boxes = 1;
|
||||
|
||||
/*
|
||||
** Set up the initial box.
|
||||
*/
|
||||
{
|
||||
double sum = 0;
|
||||
for(unsigned int i=0; i < hist->size; i++) {
|
||||
sum += achv[i].adjusted_weight;
|
||||
}
|
||||
box_init(&bv[0], achv, 0, hist->size, sum);
|
||||
|
||||
|
||||
/*
|
||||
** Main loop: split boxes until we have enough.
|
||||
*/
|
||||
while (boxes < newcolors) {
|
||||
|
||||
// first splits boxes that exceed quality limit (to have colors for things like odd green pixel),
|
||||
// later raises the limit to allow large smooth areas/gradients get colors.
|
||||
const double current_max_mse = max_mse + (boxes/(double)newcolors)*16.0*max_mse;
|
||||
const int bi = best_splittable_box(bv, boxes, current_max_mse);
|
||||
if (bi < 0) {
|
||||
break; /* ran out of colors! */
|
||||
}
|
||||
|
||||
unsigned int indx = bv[bi].ind;
|
||||
unsigned int clrs = bv[bi].colors;
|
||||
|
||||
/*
|
||||
Classic implementation tries to get even number of colors or pixels in each subdivision.
|
||||
|
||||
Here, instead of popularity I use (sqrt(popularity)*variance) metric.
|
||||
Each subdivision balances number of pixels (popular colors) and low variance -
|
||||
boxes can be large if they have similar colors. Later boxes with high variance
|
||||
will be more likely to be split.
|
||||
|
||||
Median used as expected value gives much better results than mean.
|
||||
*/
|
||||
|
||||
const double halfvar = prepare_sort(&bv[bi], achv);
|
||||
double lowervar=0;
|
||||
|
||||
// hist_item_sort_halfvar sorts and sums lowervar at the same time
|
||||
// returns item to break at …minus one, which does smell like an off-by-one error.
|
||||
hist_item *break_p = hist_item_sort_halfvar(&achv[indx], clrs, &lowervar, halfvar);
|
||||
unsigned int break_at = MIN(clrs-1, break_p - &achv[indx] + 1);
|
||||
|
||||
/*
|
||||
** Split the box.
|
||||
*/
|
||||
double sm = bv[bi].sum;
|
||||
double lowersum = 0;
|
||||
for(unsigned int i=0; i < break_at; i++) lowersum += achv[indx + i].adjusted_weight;
|
||||
|
||||
box_init(&bv[bi], achv, indx, break_at, lowersum);
|
||||
box_init(&bv[boxes], achv, indx + break_at, clrs - break_at, sm - lowersum);
|
||||
|
||||
++boxes;
|
||||
|
||||
if (total_box_error_below_target(target_mse, bv, boxes, hist)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
colormap *map = pam_colormap(boxes, malloc, free);
|
||||
set_colormap_from_boxes(map, bv, boxes, achv);
|
||||
|
||||
adjust_histogram(achv, bv, boxes);
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
static void set_colormap_from_boxes(colormap *map, struct box* bv, unsigned int boxes, hist_item *achv)
|
||||
{
|
||||
/*
|
||||
** Ok, we've got enough boxes. Now choose a representative color for
|
||||
** each box. There are a number of possible ways to make this choice.
|
||||
** One would be to choose the center of the box; this ignores any structure
|
||||
** within the boxes. Another method would be to average all the colors in
|
||||
** the box - this is the method specified in Heckbert's paper.
|
||||
*/
|
||||
|
||||
for(unsigned int bi = 0; bi < boxes; ++bi) {
|
||||
map->palette[bi].acolor = bv[bi].color;
|
||||
|
||||
/* store total color popularity (perceptual_weight is approximation of it) */
|
||||
map->palette[bi].popularity = 0;
|
||||
for(unsigned int i=bv[bi].ind; i < bv[bi].ind+bv[bi].colors; i++) {
|
||||
map->palette[bi].popularity += achv[i].perceptual_weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* increase histogram popularity by difference from the final color (this is used as part of feedback loop) */
|
||||
static void adjust_histogram(hist_item *achv, const struct box* bv, unsigned int boxes)
|
||||
{
|
||||
for(unsigned int bi = 0; bi < boxes; ++bi) {
|
||||
for(unsigned int i=bv[bi].ind; i < bv[bi].ind+bv[bi].colors; i++) {
|
||||
achv[i].tmp.likely_colormap_index = bi;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static f_pixel averagepixels(unsigned int clrs, const hist_item achv[])
|
||||
{
|
||||
double r = 0, g = 0, b = 0, a = 0, sum = 0;
|
||||
|
||||
#pragma omp parallel for if (clrs > 25000) \
|
||||
schedule(static) default(shared) reduction(+:a) reduction(+:r) reduction(+:g) reduction(+:b) reduction(+:sum)
|
||||
for(unsigned int i = 0; i < clrs; i++) {
|
||||
const f_pixel px = achv[i].acolor;
|
||||
const double weight = achv[i].adjusted_weight;
|
||||
|
||||
sum += weight;
|
||||
a += px.a * weight;
|
||||
r += px.r * weight;
|
||||
g += px.g * weight;
|
||||
b += px.b * weight;
|
||||
}
|
||||
|
||||
if (sum) {
|
||||
a /= sum;
|
||||
r /= sum;
|
||||
g /= sum;
|
||||
b /= sum;
|
||||
}
|
||||
|
||||
assert(!isnan(r) && !isnan(g) && !isnan(b) && !isnan(a));
|
||||
|
||||
return (f_pixel){.r=r, .g=g, .b=b, .a=a};
|
||||
}
|
6
CloverApp/Clover/libimagequant/mediancut.h
Normal file
6
CloverApp/Clover/libimagequant/mediancut.h
Normal file
@ -0,0 +1,6 @@
|
||||
#ifndef MEDIANCUT_H
|
||||
#define MEDIANCUT_H
|
||||
|
||||
LIQ_PRIVATE colormap *mediancut(histogram *hist, unsigned int newcolors, const double target_mse, const double max_mse, void* (*malloc)(size_t), void (*free)(void*));
|
||||
|
||||
#endif
|
70
CloverApp/Clover/libimagequant/mempool.c
Normal file
70
CloverApp/Clover/libimagequant/mempool.c
Normal file
@ -0,0 +1,70 @@
|
||||
/*
|
||||
** © 2009-2017 by Kornel Lesiński.
|
||||
** © 1989, 1991 by Jef Poskanzer.
|
||||
** © 1997, 2000, 2002 by Greg Roelofs; based on an idea by Stefan Schneider.
|
||||
**
|
||||
** See COPYRIGHT file for license.
|
||||
*/
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "mempool.h"
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include <assert.h>
|
||||
|
||||
#define ALIGN_MASK 15UL
|
||||
#define MEMPOOL_RESERVED ((sizeof(struct mempool)+ALIGN_MASK) & ~ALIGN_MASK)
|
||||
|
||||
struct mempool {
|
||||
unsigned int used, size;
|
||||
void* (*malloc)(size_t);
|
||||
void (*free)(void*);
|
||||
struct mempool *next;
|
||||
};
|
||||
LIQ_PRIVATE void* mempool_create(mempoolptr *mptr, const unsigned int size, unsigned int max_size, void* (*malloc)(size_t), void (*free)(void*))
|
||||
{
|
||||
if (*mptr && ((*mptr)->used+size) <= (*mptr)->size) {
|
||||
unsigned int prevused = (*mptr)->used;
|
||||
(*mptr)->used += (size+15UL) & ~0xFUL;
|
||||
return ((char*)(*mptr)) + prevused;
|
||||
}
|
||||
|
||||
mempoolptr old = *mptr;
|
||||
if (!max_size) max_size = (1<<17);
|
||||
max_size = size+ALIGN_MASK > max_size ? size+ALIGN_MASK : max_size;
|
||||
|
||||
*mptr = malloc(MEMPOOL_RESERVED + max_size);
|
||||
if (!*mptr) return NULL;
|
||||
**mptr = (struct mempool){
|
||||
.malloc = malloc,
|
||||
.free = free,
|
||||
.size = MEMPOOL_RESERVED + max_size,
|
||||
.used = sizeof(struct mempool),
|
||||
.next = old,
|
||||
};
|
||||
uintptr_t mptr_used_start = (uintptr_t)(*mptr) + (*mptr)->used;
|
||||
(*mptr)->used += (ALIGN_MASK + 1 - (mptr_used_start & ALIGN_MASK)) & ALIGN_MASK; // reserve bytes required to make subsequent allocations aligned
|
||||
assert(!(((uintptr_t)(*mptr) + (*mptr)->used) & ALIGN_MASK));
|
||||
|
||||
return mempool_alloc(mptr, size, size);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void* mempool_alloc(mempoolptr *mptr, const unsigned int size, const unsigned int max_size)
|
||||
{
|
||||
if (((*mptr)->used+size) <= (*mptr)->size) {
|
||||
unsigned int prevused = (*mptr)->used;
|
||||
(*mptr)->used += (size + ALIGN_MASK) & ~ALIGN_MASK;
|
||||
return ((char*)(*mptr)) + prevused;
|
||||
}
|
||||
|
||||
return mempool_create(mptr, size, max_size, (*mptr)->malloc, (*mptr)->free);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void mempool_destroy(mempoolptr m)
|
||||
{
|
||||
while (m) {
|
||||
mempoolptr next = m->next;
|
||||
m->free(m);
|
||||
m = next;
|
||||
}
|
||||
}
|
13
CloverApp/Clover/libimagequant/mempool.h
Normal file
13
CloverApp/Clover/libimagequant/mempool.h
Normal file
@ -0,0 +1,13 @@
|
||||
#ifndef MEMPOOL_H
|
||||
#define MEMPOOL_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct mempool;
|
||||
typedef struct mempool *mempoolptr;
|
||||
|
||||
LIQ_PRIVATE void* mempool_create(mempoolptr *mptr, const unsigned int size, unsigned int capacity, void* (*malloc)(size_t), void (*free)(void*));
|
||||
LIQ_PRIVATE void* mempool_alloc(mempoolptr *mptr, const unsigned int size, const unsigned int capacity);
|
||||
LIQ_PRIVATE void mempool_destroy(mempoolptr m);
|
||||
|
||||
#endif
|
195
CloverApp/Clover/libimagequant/nearest.c
Normal file
195
CloverApp/Clover/libimagequant/nearest.c
Normal file
@ -0,0 +1,195 @@
|
||||
/*
|
||||
** © 2009-2015 by Kornel Lesiński.
|
||||
** © 1989, 1991 by Jef Poskanzer.
|
||||
** © 1997, 2000, 2002 by Greg Roelofs; based on an idea by Stefan Schneider.
|
||||
**
|
||||
** See COPYRIGHT file for license.
|
||||
*/
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "pam.h"
|
||||
#include "nearest.h"
|
||||
#include "mempool.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct vp_sort_tmp {
|
||||
float distance_squared;
|
||||
unsigned int idx;
|
||||
} vp_sort_tmp;
|
||||
|
||||
typedef struct vp_search_tmp {
|
||||
float distance;
|
||||
unsigned int idx;
|
||||
int exclude;
|
||||
} vp_search_tmp;
|
||||
|
||||
typedef struct vp_node {
|
||||
struct vp_node *near, *far;
|
||||
f_pixel vantage_point;
|
||||
float radius;
|
||||
unsigned int idx;
|
||||
} vp_node;
|
||||
|
||||
struct nearest_map {
|
||||
vp_node *root;
|
||||
const colormap_item *palette;
|
||||
float nearest_other_color_dist[256];
|
||||
mempoolptr mempool;
|
||||
};
|
||||
|
||||
static void vp_search_node(const vp_node *node, const f_pixel *const needle, vp_search_tmp *const best_candidate);
|
||||
|
||||
static int vp_compare_distance(const void *ap, const void *bp) {
|
||||
float a = ((const vp_sort_tmp*)ap)->distance_squared;
|
||||
float b = ((const vp_sort_tmp*)bp)->distance_squared;
|
||||
return a > b ? 1 : -1;
|
||||
}
|
||||
|
||||
static void vp_sort_indexes_by_distance(const f_pixel vantage_point, vp_sort_tmp indexes[], int num_indexes, const colormap_item items[]) {
|
||||
for(int i=0; i < num_indexes; i++) {
|
||||
indexes[i].distance_squared = colordifference(vantage_point, items[indexes[i].idx].acolor);
|
||||
}
|
||||
qsort(indexes, num_indexes, sizeof(indexes[0]), vp_compare_distance);
|
||||
}
|
||||
|
||||
/*
|
||||
* Usually it should pick farthest point, but picking most popular point seems to make search quicker anyway
|
||||
*/
|
||||
static int vp_find_best_vantage_point_index(vp_sort_tmp indexes[], int num_indexes, const colormap_item items[]) {
|
||||
int best = 0;
|
||||
float best_popularity = items[indexes[0].idx].popularity;
|
||||
for(int i = 1; i < num_indexes; i++) {
|
||||
if (items[indexes[i].idx].popularity > best_popularity) {
|
||||
best_popularity = items[indexes[i].idx].popularity;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
static vp_node *vp_create_node(mempoolptr *m, vp_sort_tmp indexes[], int num_indexes, const colormap_item items[]) {
|
||||
if (num_indexes <= 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
vp_node *node = mempool_alloc(m, sizeof(node[0]), 0);
|
||||
|
||||
if (num_indexes == 1) {
|
||||
*node = (vp_node){
|
||||
.vantage_point = items[indexes[0].idx].acolor,
|
||||
.idx = indexes[0].idx,
|
||||
.radius = MAX_DIFF,
|
||||
};
|
||||
return node;
|
||||
}
|
||||
|
||||
const int ref = vp_find_best_vantage_point_index(indexes, num_indexes, items);
|
||||
const int ref_idx = indexes[ref].idx;
|
||||
|
||||
// Removes the `ref_idx` item from remaining items, because it's included in the current node
|
||||
num_indexes -= 1;
|
||||
indexes[ref] = indexes[num_indexes];
|
||||
|
||||
vp_sort_indexes_by_distance(items[ref_idx].acolor, indexes, num_indexes, items);
|
||||
|
||||
// Remaining items are split by the median distance
|
||||
const int half_idx = num_indexes/2;
|
||||
|
||||
*node = (vp_node){
|
||||
.vantage_point = items[ref_idx].acolor,
|
||||
.idx = ref_idx,
|
||||
.radius = sqrtf(indexes[half_idx].distance_squared),
|
||||
};
|
||||
node->near = vp_create_node(m, indexes, half_idx, items);
|
||||
node->far = vp_create_node(m, &indexes[half_idx], num_indexes - half_idx, items);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE struct nearest_map *nearest_init(const colormap *map) {
|
||||
mempoolptr m = NULL;
|
||||
struct nearest_map *handle = mempool_create(&m, sizeof(handle[0]), sizeof(handle[0]) + sizeof(vp_node)*map->colors+16, map->malloc, map->free);
|
||||
|
||||
LIQ_ARRAY(vp_sort_tmp, indexes, map->colors);
|
||||
|
||||
for(unsigned int i=0; i < map->colors; i++) {
|
||||
indexes[i].idx = i;
|
||||
}
|
||||
|
||||
vp_node *root = vp_create_node(&m, indexes, map->colors, map->palette);
|
||||
*handle = (struct nearest_map){
|
||||
.root = root,
|
||||
.palette = map->palette,
|
||||
.mempool = m,
|
||||
};
|
||||
|
||||
for(unsigned int i=0; i < map->colors; i++) {
|
||||
vp_search_tmp best = {
|
||||
.distance = MAX_DIFF,
|
||||
.exclude = i,
|
||||
};
|
||||
vp_search_node(root, &map->palette[i].acolor, &best);
|
||||
handle->nearest_other_color_dist[i] = best.distance * best.distance / 4.0; // half of squared distance
|
||||
}
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
static void vp_search_node(const vp_node *node, const f_pixel *const needle, vp_search_tmp *const best_candidate) {
|
||||
do {
|
||||
const float distance = sqrtf(colordifference(node->vantage_point, *needle));
|
||||
|
||||
if (distance < best_candidate->distance && best_candidate->exclude != node->idx) {
|
||||
best_candidate->distance = distance;
|
||||
best_candidate->idx = node->idx;
|
||||
}
|
||||
|
||||
// Recurse towards most likely candidate first to narrow best candidate's distance as soon as possible
|
||||
if (distance < node->radius) {
|
||||
if (node->near) {
|
||||
vp_search_node(node->near, needle, best_candidate);
|
||||
}
|
||||
// The best node (final answer) may be just ouside the radius, but not farther than
|
||||
// the best distance we know so far. The vp_search_node above should have narrowed
|
||||
// best_candidate->distance, so this path is rarely taken.
|
||||
if (node->far && distance >= node->radius - best_candidate->distance) {
|
||||
node = node->far; // Fast tail recursion
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (node->far) {
|
||||
vp_search_node(node->far, needle, best_candidate);
|
||||
}
|
||||
if (node->near && distance <= node->radius + best_candidate->distance) {
|
||||
node = node->near; // Fast tail recursion
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} while(true);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE unsigned int nearest_search(const struct nearest_map *handle, const f_pixel *px, const int likely_colormap_index, float *diff) {
|
||||
const float guess_diff = colordifference(handle->palette[likely_colormap_index].acolor, *px);
|
||||
if (guess_diff < handle->nearest_other_color_dist[likely_colormap_index]) {
|
||||
if (diff) *diff = guess_diff;
|
||||
return likely_colormap_index;
|
||||
}
|
||||
|
||||
vp_search_tmp best_candidate = {
|
||||
.distance = sqrtf(guess_diff),
|
||||
.idx = likely_colormap_index,
|
||||
.exclude = -1,
|
||||
};
|
||||
vp_search_node(handle->root, px, &best_candidate);
|
||||
if (diff) {
|
||||
*diff = best_candidate.distance * best_candidate.distance;
|
||||
}
|
||||
return best_candidate.idx;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void nearest_free(struct nearest_map *centroids)
|
||||
{
|
||||
mempool_destroy(centroids->mempool);
|
||||
}
|
14
CloverApp/Clover/libimagequant/nearest.h
Normal file
14
CloverApp/Clover/libimagequant/nearest.h
Normal file
@ -0,0 +1,14 @@
|
||||
//
|
||||
// nearest.h
|
||||
// pngquant
|
||||
//
|
||||
|
||||
#ifndef NEAREST_H
|
||||
#define NEAREST_H
|
||||
|
||||
struct nearest_map;
|
||||
LIQ_PRIVATE struct nearest_map *nearest_init(const colormap *palette);
|
||||
LIQ_PRIVATE unsigned int nearest_search(const struct nearest_map *map, const f_pixel *px, const int palette_index_guess, float *diff);
|
||||
LIQ_PRIVATE void nearest_free(struct nearest_map *map);
|
||||
|
||||
#endif
|
74
CloverApp/Clover/libimagequant/org/pngquant/Image.java
Normal file
74
CloverApp/Clover/libimagequant/org/pngquant/Image.java
Normal file
@ -0,0 +1,74 @@
|
||||
package org.pngquant;
|
||||
|
||||
import org.pngquant.*;
|
||||
import java.awt.image.*;
|
||||
|
||||
/**
|
||||
* PngQuant's representation of an Image constructed from BufferedImage.
|
||||
*/
|
||||
public class Image extends LiqObject {
|
||||
|
||||
/**
|
||||
* Converts BufferedImage to internal representation (pixel data is copied).
|
||||
* It's best to use BufferedImage in RGB/RGBA format backed by DataBufferByte.
|
||||
* Throws if conversion fails.
|
||||
*/
|
||||
public Image(BufferedImage image) throws PngQuantException {
|
||||
this(new PngQuant(), image);
|
||||
}
|
||||
|
||||
public Image(PngQuant attr, BufferedImage image) throws PngQuantException {
|
||||
handle = handleFromImage(attr, image);
|
||||
|
||||
if (handle == 0) {
|
||||
BufferedImage converted = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
|
||||
converted.getGraphics().drawImage(image, 0, 0, null);
|
||||
handle = handleFromImage(attr, converted);
|
||||
|
||||
if (handle == 0) {
|
||||
throw new PngQuantException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarantees presence of the given color in the palette (subject to setMaxColors())
|
||||
* if this image is used for quantization.
|
||||
*/
|
||||
public native boolean addFixedColor(int r, int g, int b, int a);
|
||||
public boolean addFixedColor(int r, int g, int b) {
|
||||
return addFixedColor(r, g, b, 255);
|
||||
}
|
||||
public native int getWidth();
|
||||
public native int getHeight();
|
||||
|
||||
public void close() {
|
||||
if (handle != 0) {
|
||||
liq_image_destroy(handle);
|
||||
handle = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static long handleFromImage(PngQuant attr, BufferedImage image) {
|
||||
// The JNI wrapper will accept non-premultiplied ABGR and BGR only.
|
||||
int type = image.getType();
|
||||
if (type != BufferedImage.TYPE_3BYTE_BGR &&
|
||||
type != BufferedImage.TYPE_4BYTE_ABGR &&
|
||||
type != BufferedImage.TYPE_4BYTE_ABGR_PRE) return 0;
|
||||
|
||||
WritableRaster raster = image.getRaster();
|
||||
ColorModel color = image.getColorModel();
|
||||
if (type == BufferedImage.TYPE_4BYTE_ABGR_PRE) color.coerceData(raster, false);
|
||||
|
||||
DataBuffer buffer = raster.getDataBuffer();
|
||||
if (buffer instanceof DataBufferByte) {
|
||||
byte[] imageData = ((DataBufferByte)buffer).getData();
|
||||
return liq_image_create(attr.handle, imageData,
|
||||
raster.getWidth(), raster.getHeight(), color.getNumComponents());
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static native long liq_image_create(long attr, byte[] bitmap, int width, int height, int components);
|
||||
private static native void liq_image_destroy(long handle);
|
||||
}
|
19
CloverApp/Clover/libimagequant/org/pngquant/LiqObject.java
Normal file
19
CloverApp/Clover/libimagequant/org/pngquant/LiqObject.java
Normal file
@ -0,0 +1,19 @@
|
||||
package org.pngquant;
|
||||
|
||||
abstract class LiqObject {
|
||||
static {
|
||||
// libimagequant.jnilib or libimagequant.so must be in java.library.path
|
||||
System.loadLibrary("imagequant");
|
||||
}
|
||||
|
||||
long handle;
|
||||
|
||||
/**
|
||||
* Free memory used by the library. The object must not be used after this call.
|
||||
*/
|
||||
abstract public void close();
|
||||
|
||||
protected void finalize() throws Throwable {
|
||||
close();
|
||||
}
|
||||
}
|
156
CloverApp/Clover/libimagequant/org/pngquant/PngQuant.c
Normal file
156
CloverApp/Clover/libimagequant/org/pngquant/PngQuant.c
Normal file
@ -0,0 +1,156 @@
|
||||
#include "org/pngquant/PngQuant.h"
|
||||
#include "org/pngquant/Image.h"
|
||||
#include "org/pngquant/Result.h"
|
||||
#include "libimagequant.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct {
|
||||
liq_image *image;
|
||||
jbyte *data;
|
||||
} liq_jni_image;
|
||||
|
||||
static void *handle(JNIEnv *env, jobject obj) {
|
||||
jlong h = (*env)->GetLongField(env, obj, (*env)->GetFieldID(env, (*env)->GetObjectClass(env, obj), "handle", "J"));
|
||||
return (void*)h;
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_org_pngquant_PngQuant_liq_1attr_1create(JNIEnv *env, jclass class) {
|
||||
return (jlong)liq_attr_create();
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_org_pngquant_PngQuant_liq_1attr_1copy(JNIEnv *env, jclass class, jlong attr) {
|
||||
return (jlong)liq_attr_copy((liq_attr*)attr);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_pngquant_PngQuant_liq_1attr_1destroy(JNIEnv *env, jclass class, jlong attr) {
|
||||
return liq_attr_destroy((liq_attr*)attr);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setMaxColors(JNIEnv *env, jobject obj, jint colors) {
|
||||
return LIQ_OK == liq_set_max_colors(handle(env, obj), colors);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setSpeed(JNIEnv *env, jobject obj, jint speed) {
|
||||
return LIQ_OK == liq_set_speed(handle(env, obj), speed);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setMinPosterization(JNIEnv *env, jobject obj, jint p) {
|
||||
return LIQ_OK == liq_set_min_posterization(handle(env, obj), p);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setQuality__I(JNIEnv *env, jobject obj, jint q) {
|
||||
return LIQ_OK == liq_set_quality(handle(env, obj), q/2, q);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setQuality__II(JNIEnv *env, jobject obj, jint qmin, jint qmax) {
|
||||
return LIQ_OK == liq_set_quality(handle(env, obj), qmin, qmax);
|
||||
}
|
||||
|
||||
static void convert_abgr(liq_color row_out[], int row_index, int width, void* user_info) {
|
||||
liq_jni_image *jniimg = user_info;
|
||||
int column_index;
|
||||
for(column_index=0; column_index < width; column_index++) {
|
||||
row_out[column_index].r = jniimg->data[4*(width*row_index + column_index) + 3];
|
||||
row_out[column_index].g = jniimg->data[4*(width*row_index + column_index) + 2];
|
||||
row_out[column_index].b = jniimg->data[4*(width*row_index + column_index) + 1];
|
||||
row_out[column_index].a = jniimg->data[4*(width*row_index + column_index) + 0];
|
||||
}
|
||||
}
|
||||
|
||||
static void convert_bgr(liq_color row_out[], int row_index, int width, void* user_info) {
|
||||
liq_jni_image *jniimg = user_info;
|
||||
int column_index;
|
||||
for(column_index=0; column_index < width; column_index++) {
|
||||
row_out[column_index].r = jniimg->data[3*(width*row_index + column_index) + 2];
|
||||
row_out[column_index].g = jniimg->data[3*(width*row_index + column_index) + 1];
|
||||
row_out[column_index].b = jniimg->data[3*(width*row_index + column_index) + 0];
|
||||
row_out[column_index].a = 255;
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_org_pngquant_Image_liq_1image_1create(JNIEnv *env, jclass class, jlong attr, jbyteArray bytearray, jint w, jint h, jint components) {
|
||||
/* liq_image needs to be wrapped to keep track of allocated buffer */
|
||||
liq_jni_image *jniimg = malloc(sizeof(liq_jni_image));
|
||||
|
||||
/* copying buffer, since ReleaseByteArrayElements was crashing when called from finalize() */
|
||||
jsize size = (*env)->GetArrayLength(env, bytearray);
|
||||
jniimg->data = malloc(size);
|
||||
(*env)->GetByteArrayRegion(env, bytearray, 0, size, jniimg->data);
|
||||
|
||||
jniimg->image = liq_image_create_custom((liq_attr*)attr, components == 4 ? convert_abgr : convert_bgr, jniimg, w, h, 0);
|
||||
|
||||
if (!jniimg->image) {
|
||||
free(jniimg->data);
|
||||
free(jniimg);
|
||||
return 0;
|
||||
}
|
||||
return (jlong)jniimg;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_Image_addFixedColor(JNIEnv *env, jobject obj, jint r, jint g, jint b, jint a) {
|
||||
liq_color c = {r,g,b,a};
|
||||
return LIQ_OK == liq_image_add_fixed_color(((liq_jni_image*)handle(env,obj))->image, c);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_org_pngquant_Image_getWidth(JNIEnv *env, jobject obj) {
|
||||
return liq_image_get_width(((liq_jni_image*)handle(env,obj))->image);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_org_pngquant_Image_getHeight(JNIEnv *env, jobject obj) {
|
||||
return liq_image_get_height(((liq_jni_image*)handle(env,obj))->image);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_pngquant_Image_liq_1image_1destroy(JNIEnv *env, jclass class, jlong handle) {
|
||||
liq_jni_image *jniimg = (liq_jni_image*)handle;
|
||||
liq_image_destroy(jniimg->image);
|
||||
free(jniimg->data);
|
||||
free(jniimg);
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_org_pngquant_Result_liq_1quantize_1image(JNIEnv *env, jclass class, jlong attr, jlong handle) {
|
||||
return (jlong)liq_quantize_image((liq_attr*)attr, ((liq_jni_image*)handle)->image);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_Result_setDitheringLevel(JNIEnv *env, jobject obj, jfloat l) {
|
||||
return LIQ_OK == liq_set_dithering_level(handle(env, obj), l);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_Result_setGamma(JNIEnv *env, jobject obj, jdouble gamma) {
|
||||
return LIQ_OK == liq_set_output_gamma(handle(env, obj), gamma);
|
||||
}
|
||||
|
||||
JNIEXPORT jdouble JNICALL Java_org_pngquant_Result_getGamma(JNIEnv *env, jobject obj) {
|
||||
return liq_get_output_gamma(handle(env, obj));
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_Result_liq_1write_1remapped_1image(JNIEnv *env, jclass class, jlong result, jlong image_handle, jbyteArray bytearray) {
|
||||
jsize size = (*env)->GetArrayLength(env, bytearray);
|
||||
|
||||
jbyte *bitmap = (*env)->GetByteArrayElements(env, bytearray, 0);
|
||||
liq_error err = liq_write_remapped_image((liq_result*)result, ((liq_jni_image*)image_handle)->image, bitmap, size);
|
||||
(*env)->ReleaseByteArrayElements(env, bytearray, bitmap, 0);
|
||||
|
||||
return LIQ_OK == err;
|
||||
}
|
||||
|
||||
JNIEXPORT jdouble JNICALL Java_org_pngquant_Result_getMeanSquareError(JNIEnv *env, jobject obj) {
|
||||
return liq_get_quantization_error(handle(env, obj));
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_org_pngquant_Result_getQuality(JNIEnv *env, jobject obj) {
|
||||
return liq_get_quantization_quality(handle(env, obj));
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_pngquant_Result_liq_1result_1destroy(JNIEnv *env, jclass class, jlong result) {
|
||||
return liq_result_destroy((liq_result*)result);
|
||||
}
|
||||
|
||||
JNIEXPORT jbyteArray JNICALL Java_org_pngquant_Result_liq_1get_1palette(JNIEnv *env, jclass class, jlong result) {
|
||||
const liq_palette *pal = liq_get_palette((liq_result*)result);
|
||||
jbyteArray arr = (*env)->NewByteArray(env, pal->count * 4);
|
||||
int i;
|
||||
for(i=0; i < pal->count; i++) {
|
||||
(*env)->SetByteArrayRegion(env, arr, i*4, 4, ((jbyte*)&pal->entries[i]));
|
||||
}
|
||||
return arr;
|
||||
}
|
111
CloverApp/Clover/libimagequant/org/pngquant/PngQuant.java
Normal file
111
CloverApp/Clover/libimagequant/org/pngquant/PngQuant.java
Normal file
@ -0,0 +1,111 @@
|
||||
package org.pngquant;
|
||||
|
||||
import org.pngquant.*;
|
||||
import java.awt.image.*;
|
||||
|
||||
/**
|
||||
* Starting point for the library. Holds configuration. Equivalent of liq_attr* in libimagequant.
|
||||
*/
|
||||
public class PngQuant extends LiqObject {
|
||||
|
||||
/**
|
||||
* Single instance can be "recycled" for many remappings.
|
||||
*/
|
||||
public PngQuant() {
|
||||
handle = liq_attr_create();
|
||||
}
|
||||
|
||||
public PngQuant(PngQuant other) {
|
||||
handle = liq_attr_copy(other.handle);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1-shot quantization and remapping with current settings.
|
||||
* @see quantize()
|
||||
*
|
||||
* @return 8-bit indexed image or null on failure
|
||||
*/
|
||||
public BufferedImage getRemapped(BufferedImage bufimg) {
|
||||
try {
|
||||
Image liqimg = new Image(this, bufimg);
|
||||
BufferedImage remapped = getRemapped(liqimg);
|
||||
liqimg.close();
|
||||
return remapped;
|
||||
} catch(PngQuantException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return remapped image or null on failure */
|
||||
public BufferedImage getRemapped(Image liqimg) {
|
||||
Result result = quantize(liqimg);
|
||||
if (result == null) return null;
|
||||
BufferedImage remapped = result.getRemapped(liqimg);
|
||||
result.close();
|
||||
return remapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs quantization (chooses optimal palette for the given Image).
|
||||
* Returned object can be used to customize remapping and reused to remap other images to the same palette.
|
||||
* @link http://pngquant.org/lib/#liq_quantize_image
|
||||
*
|
||||
* @return null on failure
|
||||
*/
|
||||
public Result quantize(Image img) {
|
||||
try {
|
||||
return new Result(this, img);
|
||||
} catch(PngQuantException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remapped images won't use more than given number of colors (may use less if setQuality() is used)
|
||||
*
|
||||
* @link http://pngquant.org/lib/#liq_set_max_colors
|
||||
*/
|
||||
public native boolean setMaxColors(int colors);
|
||||
|
||||
/**
|
||||
* Equivalent of setQuality(target/2, target)
|
||||
*
|
||||
* @link http://pngquant.org/lib/#liq_set_quality
|
||||
*/
|
||||
public native boolean setQuality(int target);
|
||||
|
||||
/**
|
||||
* Quality in range 0-100. Quantization will fail if minimum quality cannot
|
||||
* be achieved with given number of colors.
|
||||
*
|
||||
* @link http://pngquant.org/lib/#liq_set_quality
|
||||
*/
|
||||
public native boolean setQuality(int min, int max);
|
||||
|
||||
/**
|
||||
* Speed in range 1 (slowest) and 11 (fastest). 3 is the optimum.
|
||||
* Higher speeds quantize quicker, but at cost of quality and sometimes larger images.
|
||||
*
|
||||
* @link http://pngquant.org/lib/#liq_set_speed
|
||||
*/
|
||||
public native boolean setSpeed(int speed);
|
||||
|
||||
/**
|
||||
* Reduces color precision by truncating number of least significant bits.
|
||||
* Slightly improves speed and helps generating images for low-fidelity displays/textures.
|
||||
*
|
||||
* @link http://pngquant.org/lib/#liq_set_min_posterization
|
||||
*/
|
||||
public native boolean setMinPosterization(int bits);
|
||||
|
||||
public void close() {
|
||||
if (handle != 0) {
|
||||
liq_attr_destroy(handle);
|
||||
handle = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static native long liq_attr_create();
|
||||
private static native long liq_attr_copy(long orig);
|
||||
private static native void liq_attr_destroy(long handle);
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
package org.pngquant;
|
||||
|
||||
public class PngQuantException extends Exception {
|
||||
}
|
90
CloverApp/Clover/libimagequant/org/pngquant/Result.java
Normal file
90
CloverApp/Clover/libimagequant/org/pngquant/Result.java
Normal file
@ -0,0 +1,90 @@
|
||||
package org.pngquant;
|
||||
|
||||
import org.pngquant.*;
|
||||
import java.awt.image.*;
|
||||
|
||||
/**
|
||||
* Quantization result that holds palette and options for remapping.
|
||||
*/
|
||||
public class Result extends LiqObject {
|
||||
|
||||
/**
|
||||
* Throws when quantization fails (e.g. due to failing to achieve minimum quality)
|
||||
*/
|
||||
public Result(PngQuant pngquant, Image image) throws PngQuantException {
|
||||
handle = liq_quantize_image(pngquant.handle, image.handle);
|
||||
if (handle == 0) {
|
||||
throw new PngQuantException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BufferedImage remapped to palette this Result has been created with or null on failure.
|
||||
*/
|
||||
public BufferedImage getRemapped(Image orig_image) {
|
||||
byte[] pal = liq_get_palette(handle);
|
||||
IndexColorModel color = new IndexColorModel(8, pal.length/4, pal, 0, true);
|
||||
BufferedImage img = new BufferedImage(
|
||||
orig_image.getWidth(), orig_image.getHeight(),
|
||||
BufferedImage.TYPE_BYTE_INDEXED, color);
|
||||
|
||||
byte[] data = get8bitDataFromImage(img);
|
||||
if (data == null) return null;
|
||||
|
||||
if (!liq_write_remapped_image(handle, orig_image.handle, data)) return null;
|
||||
|
||||
return img;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dithering strength. Floyd-Steinberg is always used and in
|
||||
* speed settings 1-5 high-quality adaptive dithering is used.
|
||||
* @see PngQuant.setSpeed()
|
||||
* @link http://pngquant.org/lib/#liq_set_dithering_level
|
||||
*
|
||||
* @param dither_level Dithering in range 0 (none) and 1 (full)
|
||||
*/
|
||||
public native boolean setDitheringLevel(float dither_level);
|
||||
|
||||
/**
|
||||
* The default is 0.45455 (1/2.2) which is PNG's approximation of sRGB.
|
||||
*/
|
||||
public native boolean setGamma(double gamma);
|
||||
public native double getGamma();
|
||||
|
||||
/**
|
||||
* Mean Square Error of remapping of image used to create this result.
|
||||
* @link http://pngquant.org/lib/#liq_get_quantization_error
|
||||
*
|
||||
* @return MSE or -1 if not available
|
||||
*/
|
||||
public native double getMeanSquareError();
|
||||
|
||||
/**
|
||||
* @link http://pngquant.org/lib/#liq_get_quantization_quality
|
||||
* @return Actually achieved quality in 0-100 range on scale compatible with PngQuant.setQuality()
|
||||
*/
|
||||
public native int getQuality();
|
||||
|
||||
public void close() {
|
||||
if (handle != 0) {
|
||||
liq_result_destroy(handle);
|
||||
handle = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] get8bitDataFromImage(BufferedImage image) {
|
||||
if (image.getType() == BufferedImage.TYPE_BYTE_INDEXED) {
|
||||
DataBuffer buffer = image.getRaster().getDataBuffer();
|
||||
if (buffer instanceof DataBufferByte) {
|
||||
return ((DataBufferByte)buffer).getData();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static native byte[] liq_get_palette(long handle);
|
||||
private static native long liq_quantize_image(long attr, long image);
|
||||
private static native boolean liq_write_remapped_image(long handle, long image, byte[] buffer);
|
||||
private static native void liq_result_destroy(long handle);
|
||||
}
|
286
CloverApp/Clover/libimagequant/pam.c
Normal file
286
CloverApp/Clover/libimagequant/pam.c
Normal file
@ -0,0 +1,286 @@
|
||||
/* pam.c - pam (portable alpha map) utility library
|
||||
**
|
||||
** © 2009-2017 by Kornel Lesiński.
|
||||
** © 1989, 1991 by Jef Poskanzer.
|
||||
** © 1997, 2000, 2002 by Greg Roelofs; based on an idea by Stefan Schneider.
|
||||
**
|
||||
** See COPYRIGHT file for license.
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "pam.h"
|
||||
#include "mempool.h"
|
||||
|
||||
LIQ_PRIVATE bool pam_computeacolorhash(struct acolorhash_table *acht, const rgba_pixel *const pixels[], unsigned int cols, unsigned int rows, const unsigned char *importance_map)
|
||||
{
|
||||
const unsigned int ignorebits = acht->ignorebits;
|
||||
const unsigned int channel_mask = 255U>>ignorebits<<ignorebits;
|
||||
const unsigned int channel_hmask = (255U>>ignorebits) ^ 0xFFU;
|
||||
const unsigned int posterize_mask = channel_mask << 24 | channel_mask << 16 | channel_mask << 8 | channel_mask;
|
||||
const unsigned int posterize_high_mask = channel_hmask << 24 | channel_hmask << 16 | channel_hmask << 8 | channel_hmask;
|
||||
|
||||
const unsigned int hash_size = acht->hash_size;
|
||||
|
||||
/* Go through the entire image, building a hash table of colors. */
|
||||
for(unsigned int row = 0; row < rows; ++row) {
|
||||
|
||||
for(unsigned int col = 0; col < cols; ++col) {
|
||||
unsigned int boost;
|
||||
|
||||
// RGBA color is casted to long for easier hasing/comparisons
|
||||
union rgba_as_int px = {pixels[row][col]};
|
||||
unsigned int hash;
|
||||
if (!px.rgba.a) {
|
||||
// "dirty alpha" has different RGBA values that end up being the same fully transparent color
|
||||
px.l=0; hash=0;
|
||||
|
||||
boost = 2000;
|
||||
if (importance_map) {
|
||||
importance_map++;
|
||||
}
|
||||
} else {
|
||||
// mask posterizes all 4 channels in one go
|
||||
px.l = (px.l & posterize_mask) | ((px.l & posterize_high_mask) >> (8-ignorebits));
|
||||
// fancier hashing algorithms didn't improve much
|
||||
hash = px.l % hash_size;
|
||||
|
||||
if (importance_map) {
|
||||
boost = *importance_map++;
|
||||
} else {
|
||||
boost = 255;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pam_add_to_hash(acht, hash, boost, px, row, rows)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
acht->cols = cols;
|
||||
acht->rows += rows;
|
||||
return true;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE bool pam_add_to_hash(struct acolorhash_table *acht, unsigned int hash, unsigned int boost, union rgba_as_int px, unsigned int row, unsigned int rows)
|
||||
{
|
||||
/* head of the hash function stores first 2 colors inline (achl->used = 1..2),
|
||||
to reduce number of allocations of achl->other_items.
|
||||
*/
|
||||
struct acolorhist_arr_head *achl = &acht->buckets[hash];
|
||||
if (achl->inline1.color.l == px.l && achl->used) {
|
||||
achl->inline1.perceptual_weight += boost;
|
||||
return true;
|
||||
}
|
||||
if (achl->used) {
|
||||
if (achl->used > 1) {
|
||||
if (achl->inline2.color.l == px.l) {
|
||||
achl->inline2.perceptual_weight += boost;
|
||||
return true;
|
||||
}
|
||||
// other items are stored as an array (which gets reallocated if needed)
|
||||
struct acolorhist_arr_item *other_items = achl->other_items;
|
||||
unsigned int i = 0;
|
||||
for (; i < achl->used-2; i++) {
|
||||
if (other_items[i].color.l == px.l) {
|
||||
other_items[i].perceptual_weight += boost;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// the array was allocated with spare items
|
||||
if (i < achl->capacity) {
|
||||
other_items[i] = (struct acolorhist_arr_item){
|
||||
.color = px,
|
||||
.perceptual_weight = boost,
|
||||
};
|
||||
achl->used++;
|
||||
++acht->colors;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (++acht->colors > acht->maxcolors) {
|
||||
return false;
|
||||
}
|
||||
|
||||
struct acolorhist_arr_item *new_items;
|
||||
unsigned int capacity;
|
||||
if (!other_items) { // there was no array previously, alloc "small" array
|
||||
capacity = 8;
|
||||
if (acht->freestackp <= 0) {
|
||||
// estimate how many colors are going to be + headroom
|
||||
const size_t mempool_size = ((acht->rows + rows-row) * 2 * acht->colors / (acht->rows + row + 1) + 1024) * sizeof(struct acolorhist_arr_item);
|
||||
new_items = mempool_alloc(&acht->mempool, sizeof(struct acolorhist_arr_item)*capacity, mempool_size);
|
||||
} else {
|
||||
// freestack stores previously freed (reallocated) arrays that can be reused
|
||||
// (all pesimistically assumed to be capacity = 8)
|
||||
new_items = acht->freestack[--acht->freestackp];
|
||||
}
|
||||
} else {
|
||||
const unsigned int stacksize = sizeof(acht->freestack)/sizeof(acht->freestack[0]);
|
||||
|
||||
// simply reallocs and copies array to larger capacity
|
||||
capacity = achl->capacity*2 + 16;
|
||||
if (acht->freestackp < stacksize-1) {
|
||||
acht->freestack[acht->freestackp++] = other_items;
|
||||
}
|
||||
const size_t mempool_size = ((acht->rows + rows-row) * 2 * acht->colors / (acht->rows + row + 1) + 32*capacity) * sizeof(struct acolorhist_arr_item);
|
||||
new_items = mempool_alloc(&acht->mempool, sizeof(struct acolorhist_arr_item)*capacity, mempool_size);
|
||||
if (!new_items) return false;
|
||||
memcpy(new_items, other_items, sizeof(other_items[0])*achl->capacity);
|
||||
}
|
||||
|
||||
achl->other_items = new_items;
|
||||
achl->capacity = capacity;
|
||||
new_items[i] = (struct acolorhist_arr_item){
|
||||
.color = px,
|
||||
.perceptual_weight = boost,
|
||||
};
|
||||
achl->used++;
|
||||
} else {
|
||||
// these are elses for first checks whether first and second inline-stored colors are used
|
||||
achl->inline2.color.l = px.l;
|
||||
achl->inline2.perceptual_weight = boost;
|
||||
achl->used = 2;
|
||||
++acht->colors;
|
||||
}
|
||||
} else {
|
||||
achl->inline1.color.l = px.l;
|
||||
achl->inline1.perceptual_weight = boost;
|
||||
achl->used = 1;
|
||||
++acht->colors;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE struct acolorhash_table *pam_allocacolorhash(unsigned int maxcolors, unsigned int surface, unsigned int ignorebits, void* (*malloc)(size_t), void (*free)(void*))
|
||||
{
|
||||
const size_t estimated_colors = MIN(maxcolors, surface/(ignorebits + (surface > 512*512 ? 6 : 5)));
|
||||
const size_t hash_size = estimated_colors < 66000 ? 6673 : (estimated_colors < 200000 ? 12011 : 24019);
|
||||
|
||||
mempoolptr m = NULL;
|
||||
const size_t buckets_size = hash_size * sizeof(struct acolorhist_arr_head);
|
||||
const size_t mempool_size = sizeof(struct acolorhash_table) + buckets_size + estimated_colors * sizeof(struct acolorhist_arr_item);
|
||||
struct acolorhash_table *t = mempool_create(&m, sizeof(*t) + buckets_size, mempool_size, malloc, free);
|
||||
if (!t) return NULL;
|
||||
*t = (struct acolorhash_table){
|
||||
.mempool = m,
|
||||
.hash_size = hash_size,
|
||||
.maxcolors = maxcolors,
|
||||
.ignorebits = ignorebits,
|
||||
};
|
||||
memset(t->buckets, 0, buckets_size);
|
||||
return t;
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static float pam_add_to_hist(const float *gamma_lut, hist_item *achv, unsigned int *j, const struct acolorhist_arr_item *entry, const float max_perceptual_weight)
|
||||
{
|
||||
if (entry->perceptual_weight == 0) {
|
||||
return 0;
|
||||
}
|
||||
const float w = MIN(entry->perceptual_weight/128.f, max_perceptual_weight);
|
||||
achv[*j].adjusted_weight = achv[*j].perceptual_weight = w;
|
||||
achv[*j].acolor = rgba_to_f(gamma_lut, entry->color.rgba);
|
||||
*j += 1;
|
||||
return w;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE histogram *pam_acolorhashtoacolorhist(const struct acolorhash_table *acht, const double gamma, void* (*malloc)(size_t), void (*free)(void*))
|
||||
{
|
||||
histogram *hist = malloc(sizeof(hist[0]));
|
||||
if (!hist || !acht) return NULL;
|
||||
*hist = (histogram){
|
||||
.achv = malloc(MAX(1,acht->colors) * sizeof(hist->achv[0])),
|
||||
.size = acht->colors,
|
||||
.free = free,
|
||||
.ignorebits = acht->ignorebits,
|
||||
};
|
||||
if (!hist->achv) return NULL;
|
||||
|
||||
float gamma_lut[256];
|
||||
to_f_set_gamma(gamma_lut, gamma);
|
||||
|
||||
/* Limit perceptual weight to 1/10th of the image surface area to prevent
|
||||
a single color from dominating all others. */
|
||||
float max_perceptual_weight = 0.1f * acht->cols * acht->rows;
|
||||
double total_weight = 0;
|
||||
|
||||
unsigned int j=0;
|
||||
for(unsigned int i=0; i < acht->hash_size; ++i) {
|
||||
const struct acolorhist_arr_head *const achl = &acht->buckets[i];
|
||||
if (achl->used) {
|
||||
total_weight += pam_add_to_hist(gamma_lut, hist->achv, &j, &achl->inline1, max_perceptual_weight);
|
||||
|
||||
if (achl->used > 1) {
|
||||
total_weight += pam_add_to_hist(gamma_lut, hist->achv, &j, &achl->inline2, max_perceptual_weight);
|
||||
|
||||
for(unsigned int k=0; k < achl->used-2; k++) {
|
||||
total_weight += pam_add_to_hist(gamma_lut, hist->achv, &j, &achl->other_items[k], max_perceptual_weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hist->size = j;
|
||||
hist->total_perceptual_weight = total_weight;
|
||||
if (!j) {
|
||||
pam_freeacolorhist(hist);
|
||||
return NULL;
|
||||
}
|
||||
return hist;
|
||||
}
|
||||
|
||||
|
||||
LIQ_PRIVATE void pam_freeacolorhash(struct acolorhash_table *acht)
|
||||
{
|
||||
if (acht) {
|
||||
mempool_destroy(acht->mempool);
|
||||
}
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void pam_freeacolorhist(histogram *hist)
|
||||
{
|
||||
hist->free(hist->achv);
|
||||
hist->free(hist);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE colormap *pam_colormap(unsigned int colors, void* (*malloc)(size_t), void (*free)(void*))
|
||||
{
|
||||
assert(colors > 0 && colors < 65536);
|
||||
|
||||
colormap *map;
|
||||
const size_t colors_size = colors * sizeof(map->palette[0]);
|
||||
map = malloc(sizeof(colormap) + colors_size);
|
||||
if (!map) return NULL;
|
||||
*map = (colormap){
|
||||
.malloc = malloc,
|
||||
.free = free,
|
||||
.colors = colors,
|
||||
};
|
||||
memset(map->palette, 0, colors_size);
|
||||
return map;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE colormap *pam_duplicate_colormap(colormap *map)
|
||||
{
|
||||
colormap *dupe = pam_colormap(map->colors, map->malloc, map->free);
|
||||
for(unsigned int i=0; i < map->colors; i++) {
|
||||
dupe->palette[i] = map->palette[i];
|
||||
}
|
||||
return dupe;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void pam_freecolormap(colormap *c)
|
||||
{
|
||||
c->free(c);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void to_f_set_gamma(float gamma_lut[], const double gamma)
|
||||
{
|
||||
for(int i=0; i < 256; i++) {
|
||||
gamma_lut[i] = pow((double)i/255.0, internal_gamma/gamma);
|
||||
}
|
||||
}
|
||||
|
283
CloverApp/Clover/libimagequant/pam.h
Normal file
283
CloverApp/Clover/libimagequant/pam.h
Normal file
@ -0,0 +1,283 @@
|
||||
/* pam.h - pam (portable alpha map) utility library
|
||||
**
|
||||
** Colormap routines.
|
||||
**
|
||||
** Copyright (C) 1989, 1991 by Jef Poskanzer.
|
||||
** Copyright (C) 1997 by Greg Roelofs.
|
||||
**
|
||||
** Permission to use, copy, modify, and distribute this software and its
|
||||
** documentation for any purpose and without fee is hereby granted, provided
|
||||
** that the above copyright notice appear in all copies and that both that
|
||||
** copyright notice and this permission notice appear in supporting
|
||||
** documentation. This software is provided "as is" without express or
|
||||
** implied warranty.
|
||||
*/
|
||||
|
||||
#ifndef PAM_H
|
||||
#define PAM_H
|
||||
|
||||
// accidental debug assertions make color search much slower,
|
||||
// so force assertions off if there's no explicit setting
|
||||
#if !defined(NDEBUG) && !defined(DEBUG)
|
||||
#define NDEBUG
|
||||
#endif
|
||||
|
||||
#include <math.h>
|
||||
#include <assert.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifndef MAX
|
||||
# define MAX(a,b) ((a) > (b)? (a) : (b))
|
||||
# define MIN(a,b) ((a) < (b)? (a) : (b))
|
||||
#endif
|
||||
|
||||
#define MAX_DIFF 1e20
|
||||
|
||||
#ifndef USE_SSE
|
||||
# if defined(__SSE__) && (defined(__amd64__) || defined(__X86_64__) || defined(_WIN64) || defined(WIN32) || defined(__WIN32__))
|
||||
# define USE_SSE 1
|
||||
# else
|
||||
# define USE_SSE 0
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if USE_SSE
|
||||
# include <xmmintrin.h>
|
||||
# ifdef _MSC_VER
|
||||
# include <intrin.h>
|
||||
# define SSE_ALIGN
|
||||
# else
|
||||
# define SSE_ALIGN __attribute__ ((aligned (16)))
|
||||
# if defined(__i386__) && defined(__PIC__)
|
||||
# define cpuid(func,ax,bx,cx,dx)\
|
||||
__asm__ __volatile__ ( \
|
||||
"push %%ebx\n" \
|
||||
"cpuid\n" \
|
||||
"mov %%ebx, %1\n" \
|
||||
"pop %%ebx\n" \
|
||||
: "=a" (ax), "=r" (bx), "=c" (cx), "=d" (dx) \
|
||||
: "a" (func));
|
||||
# else
|
||||
# define cpuid(func,ax,bx,cx,dx)\
|
||||
__asm__ __volatile__ ("cpuid":\
|
||||
"=a" (ax), "=b" (bx), "=c" (cx), "=d" (dx) : "a" (func));
|
||||
# endif
|
||||
#endif
|
||||
#else
|
||||
# define SSE_ALIGN
|
||||
#endif
|
||||
|
||||
#ifndef _MSC_VER
|
||||
#define LIQ_ARRAY(type, var, count) type var[count]
|
||||
#else
|
||||
#define LIQ_ARRAY(type, var, count) type* var = (type*)_alloca(sizeof(type)*(count))
|
||||
#endif
|
||||
|
||||
#if defined(__GNUC__) || defined (__llvm__)
|
||||
#define ALWAYS_INLINE __attribute__((always_inline)) inline
|
||||
#define NEVER_INLINE __attribute__ ((noinline))
|
||||
#elif defined(_MSC_VER)
|
||||
#define inline __inline
|
||||
#define restrict __restrict
|
||||
#define ALWAYS_INLINE __forceinline
|
||||
#define NEVER_INLINE __declspec(noinline)
|
||||
#else
|
||||
#define ALWAYS_INLINE inline
|
||||
#define NEVER_INLINE
|
||||
#endif
|
||||
|
||||
/* from pam.h */
|
||||
|
||||
typedef struct {
|
||||
unsigned char r, g, b, a;
|
||||
} rgba_pixel;
|
||||
|
||||
typedef struct {
|
||||
float a, r, g, b;
|
||||
} SSE_ALIGN f_pixel;
|
||||
|
||||
static const float internal_gamma = 0.5499f;
|
||||
|
||||
LIQ_PRIVATE void to_f_set_gamma(float gamma_lut[], const double gamma);
|
||||
|
||||
/**
|
||||
Converts 8-bit color to internal gamma and premultiplied alpha.
|
||||
(premultiplied color space is much better for blending of semitransparent colors)
|
||||
*/
|
||||
ALWAYS_INLINE static f_pixel rgba_to_f(const float gamma_lut[], const rgba_pixel px);
|
||||
inline static f_pixel rgba_to_f(const float gamma_lut[], const rgba_pixel px)
|
||||
{
|
||||
float a = px.a/255.f;
|
||||
|
||||
return (f_pixel) {
|
||||
.a = a,
|
||||
.r = gamma_lut[px.r]*a,
|
||||
.g = gamma_lut[px.g]*a,
|
||||
.b = gamma_lut[px.b]*a,
|
||||
};
|
||||
}
|
||||
|
||||
inline static rgba_pixel f_to_rgb(const float gamma, const f_pixel px)
|
||||
{
|
||||
if (px.a < 1.f/256.f) {
|
||||
return (rgba_pixel){0,0,0,0};
|
||||
}
|
||||
|
||||
float r = px.r / px.a,
|
||||
g = px.g / px.a,
|
||||
b = px.b / px.a,
|
||||
a = px.a;
|
||||
|
||||
r = powf(r, gamma/internal_gamma);
|
||||
g = powf(g, gamma/internal_gamma);
|
||||
b = powf(b, gamma/internal_gamma);
|
||||
|
||||
// 256, because numbers are in range 1..255.9999… rounded down
|
||||
r *= 256.f;
|
||||
g *= 256.f;
|
||||
b *= 256.f;
|
||||
a *= 256.f;
|
||||
|
||||
return (rgba_pixel){
|
||||
.r = r>=255.f ? 255 : r,
|
||||
.g = g>=255.f ? 255 : g,
|
||||
.b = b>=255.f ? 255 : b,
|
||||
.a = a>=255.f ? 255 : a,
|
||||
};
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static double colordifference_ch(const double x, const double y, const double alphas);
|
||||
inline static double colordifference_ch(const double x, const double y, const double alphas)
|
||||
{
|
||||
// maximum of channel blended on white, and blended on black
|
||||
// premultiplied alpha and backgrounds 0/1 shorten the formula
|
||||
const double black = x-y, white = black+alphas;
|
||||
return MAX(black*black, white*white);
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static float colordifference_stdc(const f_pixel px, const f_pixel py);
|
||||
inline static float colordifference_stdc(const f_pixel px, const f_pixel py)
|
||||
{
|
||||
// px_b.rgb = px.rgb + 0*(1-px.a) // blend px on black
|
||||
// px_b.a = px.a + 1*(1-px.a)
|
||||
// px_w.rgb = px.rgb + 1*(1-px.a) // blend px on white
|
||||
// px_w.a = px.a + 1*(1-px.a)
|
||||
|
||||
// px_b.rgb = px.rgb // difference same as in opaque RGB
|
||||
// px_b.a = 1
|
||||
// px_w.rgb = px.rgb - px.a // difference simplifies to formula below
|
||||
// px_w.a = 1
|
||||
|
||||
// (px.rgb - px.a) - (py.rgb - py.a)
|
||||
// (px.rgb - py.rgb) + (py.a - px.a)
|
||||
|
||||
const double alphas = py.a-px.a;
|
||||
return colordifference_ch(px.r, py.r, alphas) +
|
||||
colordifference_ch(px.g, py.g, alphas) +
|
||||
colordifference_ch(px.b, py.b, alphas);
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static float colordifference(f_pixel px, f_pixel py);
|
||||
inline static float colordifference(f_pixel px, f_pixel py)
|
||||
{
|
||||
#if USE_SSE
|
||||
const __m128 vpx = _mm_load_ps((const float*)&px);
|
||||
const __m128 vpy = _mm_load_ps((const float*)&py);
|
||||
|
||||
// y.a - x.a
|
||||
__m128 alphas = _mm_sub_ss(vpy, vpx);
|
||||
alphas = _mm_shuffle_ps(alphas,alphas,0); // copy first to all four
|
||||
|
||||
__m128 onblack = _mm_sub_ps(vpx, vpy); // x - y
|
||||
__m128 onwhite = _mm_add_ps(onblack, alphas); // x - y + (y.a - x.a)
|
||||
|
||||
onblack = _mm_mul_ps(onblack, onblack);
|
||||
onwhite = _mm_mul_ps(onwhite, onwhite);
|
||||
const __m128 max = _mm_max_ps(onwhite, onblack);
|
||||
|
||||
// add rgb, not a
|
||||
const __m128 maxhl = _mm_movehl_ps(max, max);
|
||||
const __m128 tmp = _mm_add_ps(max, maxhl);
|
||||
const __m128 sum = _mm_add_ss(maxhl, _mm_shuffle_ps(tmp, tmp, 1));
|
||||
|
||||
const float res = _mm_cvtss_f32(sum);
|
||||
assert(fabs(res - colordifference_stdc(px,py)) < 0.001);
|
||||
return res;
|
||||
#else
|
||||
return colordifference_stdc(px,py);
|
||||
#endif
|
||||
}
|
||||
|
||||
/* from pamcmap.h */
|
||||
union rgba_as_int {
|
||||
rgba_pixel rgba;
|
||||
unsigned int l;
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
f_pixel acolor;
|
||||
float adjusted_weight, // perceptual weight changed to tweak how mediancut selects colors
|
||||
perceptual_weight; // number of pixels weighted by importance of different areas of the picture
|
||||
|
||||
float color_weight; // these two change every time histogram subset is sorted
|
||||
union {
|
||||
unsigned int sort_value;
|
||||
unsigned char likely_colormap_index;
|
||||
} tmp;
|
||||
} hist_item;
|
||||
|
||||
typedef struct {
|
||||
hist_item *achv;
|
||||
void (*free)(void*);
|
||||
double total_perceptual_weight;
|
||||
unsigned int size;
|
||||
unsigned int ignorebits;
|
||||
} histogram;
|
||||
|
||||
typedef struct {
|
||||
f_pixel acolor;
|
||||
float popularity;
|
||||
bool fixed; // if true it's user-supplied and must not be changed (e.g in K-Means iteration)
|
||||
} colormap_item;
|
||||
|
||||
typedef struct colormap {
|
||||
unsigned int colors;
|
||||
void* (*malloc)(size_t);
|
||||
void (*free)(void*);
|
||||
colormap_item palette[];
|
||||
} colormap;
|
||||
|
||||
struct acolorhist_arr_item {
|
||||
union rgba_as_int color;
|
||||
unsigned int perceptual_weight;
|
||||
};
|
||||
|
||||
struct acolorhist_arr_head {
|
||||
struct acolorhist_arr_item inline1, inline2;
|
||||
unsigned int used, capacity;
|
||||
struct acolorhist_arr_item *other_items;
|
||||
};
|
||||
|
||||
struct acolorhash_table {
|
||||
struct mempool *mempool;
|
||||
unsigned int ignorebits, maxcolors, colors, cols, rows;
|
||||
unsigned int hash_size;
|
||||
unsigned int freestackp;
|
||||
struct acolorhist_arr_item *freestack[512];
|
||||
struct acolorhist_arr_head buckets[];
|
||||
};
|
||||
|
||||
LIQ_PRIVATE void pam_freeacolorhash(struct acolorhash_table *acht);
|
||||
LIQ_PRIVATE struct acolorhash_table *pam_allocacolorhash(unsigned int maxcolors, unsigned int surface, unsigned int ignorebits, void* (*malloc)(size_t), void (*free)(void*));
|
||||
LIQ_PRIVATE histogram *pam_acolorhashtoacolorhist(const struct acolorhash_table *acht, const double gamma, void* (*malloc)(size_t), void (*free)(void*));
|
||||
LIQ_PRIVATE bool pam_computeacolorhash(struct acolorhash_table *acht, const rgba_pixel *const pixels[], unsigned int cols, unsigned int rows, const unsigned char *importance_map);
|
||||
LIQ_PRIVATE bool pam_add_to_hash(struct acolorhash_table *acht, unsigned int hash, unsigned int boost, union rgba_as_int px, unsigned int row, unsigned int rows);
|
||||
|
||||
LIQ_PRIVATE void pam_freeacolorhist(histogram *h);
|
||||
|
||||
LIQ_PRIVATE colormap *pam_colormap(unsigned int colors, void* (*malloc)(size_t), void (*free)(void*));
|
||||
LIQ_PRIVATE colormap *pam_duplicate_colormap(colormap *map);
|
||||
LIQ_PRIVATE void pam_freecolormap(colormap *c);
|
||||
|
||||
#endif
|
87
CloverApp/Clover/libimagequant/pom.xml
Normal file
87
CloverApp/Clover/libimagequant/pom.xml
Normal file
@ -0,0 +1,87 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.pngquant</groupId>
|
||||
<artifactId>libimagequant</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>2.1.1</version>
|
||||
<name>pngquant</name>
|
||||
<url>http://pngquant.org</url>
|
||||
<build>
|
||||
<sourceDirectory>.</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>build</id>
|
||||
<phase>compile</phase>
|
||||
<goals><goal>exec</goal></goals>
|
||||
<configuration>
|
||||
<executable>make</executable>
|
||||
<arguments>
|
||||
<argument>-j8</argument>
|
||||
<argument>USE_SSE=1</argument>
|
||||
<argument>java</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>clean</id>
|
||||
<phase>clean</phase>
|
||||
<goals><goal>exec</goal></goals>
|
||||
<configuration>
|
||||
<executable>make</executable>
|
||||
<arguments>
|
||||
<argument>clean</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>mac-x64</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>Mac</family>
|
||||
<arch>x64</arch>
|
||||
</os>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.pngquant</groupId>
|
||||
<artifactId>libimagequant-jni</artifactId>
|
||||
<version>1</version>
|
||||
<type>jnilib</type>
|
||||
<classifier>mac-x64</classifier>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>linux-x64</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>unix</family>
|
||||
<name>Linux</name>
|
||||
<arch>x64</arch>
|
||||
</os>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.pngquant</groupId>
|
||||
<artifactId>libimagequant-jni</artifactId>
|
||||
<type>so</type>
|
||||
<version>1</version>
|
||||
<classifier>linux-x64</classifier>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
</profiles>
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
</project>
|
2
CloverApp/Clover/libimagequant/rust-api/.gitignore
vendored
Normal file
2
CloverApp/Clover/libimagequant/rust-api/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
target/
|
||||
Cargo.lock
|
635
CloverApp/Clover/libimagequant/rust-api/COPYRIGHT
Normal file
635
CloverApp/Clover/libimagequant/rust-api/COPYRIGHT
Normal file
@ -0,0 +1,635 @@
|
||||
https://raw.githubusercontent.com/ImageOptim/libimagequant/master/COPYRIGHT
|
||||
|
||||
libimagequant © 2009-2016 by Kornel Lesiński.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||
|
||||
© 1989, 1991 by Jef Poskanzer.
|
||||
© 1997, 2000, 2002 by Greg Roelofs.
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted, provided
|
||||
that the above copyright notice appear in all copies and that both that
|
||||
copyright notice and this permission notice appear in supporting
|
||||
documentation. This software is provided "as is" without express or
|
||||
implied warranty.
|
27
CloverApp/Clover/libimagequant/rust-api/Cargo.toml
Normal file
27
CloverApp/Clover/libimagequant/rust-api/Cargo.toml
Normal file
@ -0,0 +1,27 @@
|
||||
[package]
|
||||
categories = ["multimedia::images"]
|
||||
description = "Convert 24/32-bit images to 8-bit palette with alpha channel.\nBindings for libimagequant that powers pngquant lossy PNG compressor.\n\nDual-licensed like pngquant. See https://pngquant.org for details."
|
||||
documentation = "https://docs.rs/imagequant"
|
||||
homepage = "https://pngquant.org/lib/"
|
||||
include = ["src/*", "examples/*", "COPYRIGHT", "Cargo.toml", "README.md"]
|
||||
keywords = ["quantization", "palette", "image", "pngquant", "compression"]
|
||||
authors = [ "Kornel <kornel@pngquant.org>" ]
|
||||
license = "GPL-3.0+"
|
||||
name = "imagequant"
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/ImageOptim/libimagequant"
|
||||
version = "2.12.6"
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
imagequant-sys = { version = "2.12.6", path = "../" }
|
||||
libc = "0.2.60"
|
||||
|
||||
[features]
|
||||
default = ["sse"]
|
||||
sse = ["imagequant-sys/sse"]
|
||||
openmp = ["imagequant-sys/openmp"]
|
||||
openmp-static = ["openmp", "imagequant-sys/openmp-static"]
|
||||
|
||||
[lib]
|
||||
name = "imagequant"
|
15
CloverApp/Clover/libimagequant/rust-api/README.md
Normal file
15
CloverApp/Clover/libimagequant/rust-api/README.md
Normal file
@ -0,0 +1,15 @@
|
||||
# [libimagequant](https://pngquant.org/lib/) bindings for [Rust](https://www.rust-lang.org/)
|
||||
|
||||
Imagequant library converts RGBA images to 8-bit indexed images with palette, *including* alpha component.
|
||||
It's ideal for generating tiny PNG images (although [image I/O](https://github.com/kornelski/lodepng-rust) isn't handled by the library itself).
|
||||
|
||||
This wrapper makes the library usable from Rust.
|
||||
|
||||
Rust API closely follows the C API, but is slightly OO-ified:
|
||||
|
||||
liq_set_dithering_level(result, 1.0);
|
||||
↓
|
||||
result.set_dithering_level(1.0);
|
||||
|
||||
For more details see [libimagequant documentation](https://pngquant.org/lib/) and [Rust function reference](https://kornelski.github.io/libimagequant-rust/imagequant/).
|
||||
|
32
CloverApp/Clover/libimagequant/rust-api/examples/basic.rs
Normal file
32
CloverApp/Clover/libimagequant/rust-api/examples/basic.rs
Normal file
@ -0,0 +1,32 @@
|
||||
// Don't forget to add -L . (or whatever dir has .rlib) to rustc!
|
||||
|
||||
fn main() {
|
||||
// Image loading/saving is outside scope of this library
|
||||
let width = 10usize;
|
||||
let height = 10usize;
|
||||
let fakebitmap = vec![255u8; 4 * width * height];
|
||||
|
||||
// http://pngquant.org/lib/
|
||||
|
||||
// Configure the library
|
||||
let mut liq = imagequant::new();
|
||||
liq.set_speed(5);
|
||||
liq.set_quality(70, 99);
|
||||
|
||||
// Describe the bitmap
|
||||
let ref mut img = liq.new_image(&fakebitmap[..], width, height, 0.0).unwrap();
|
||||
|
||||
// The magic happens in quantize()
|
||||
let mut res = match liq.quantize(img) {
|
||||
Ok(res) => res,
|
||||
Err(err) => panic!("Quantization failed, because: {:?}", err),
|
||||
};
|
||||
|
||||
// Enable dithering for subsequent remappings
|
||||
res.set_dithering_level(1.0);
|
||||
|
||||
// You can reuse the result to generate several images with the same palette
|
||||
let (palette, pixels) = res.remapped(img).unwrap();
|
||||
|
||||
println!("Done! Got palette {:?} and {} pixels with {}% quality", palette, pixels.len(), res.quantization_quality());
|
||||
}
|
566
CloverApp/Clover/libimagequant/rust-api/src/lib.rs
Normal file
566
CloverApp/Clover/libimagequant/rust-api/src/lib.rs
Normal file
@ -0,0 +1,566 @@
|
||||
//! https://pngquant.org/lib/
|
||||
//!
|
||||
//! Converts RGBA images to 8-bit with alpha channel.
|
||||
//!
|
||||
//! This is based on imagequant library, which generates very high quality images.
|
||||
//!
|
||||
//! See `examples/` directory for example code.
|
||||
#![doc(html_logo_url = "https://pngquant.org/pngquant-logo.png")]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
extern crate imagequant_sys as ffi;
|
||||
|
||||
pub use crate::ffi::liq_error;
|
||||
pub use crate::ffi::liq_error::*;
|
||||
use std::fmt;
|
||||
use std::marker;
|
||||
use std::mem;
|
||||
use std::os::raw::c_int;
|
||||
use std::ptr;
|
||||
|
||||
/// 8-bit RGBA. This is the only color format used by the library.
|
||||
pub type Color = ffi::liq_color;
|
||||
|
||||
/// Number of pixels in a given color
|
||||
///
|
||||
/// Used if you're building histogram manually. Otherwise see `add_image()`
|
||||
pub type HistogramEntry = ffi::liq_histogram_entry;
|
||||
|
||||
/// Settings for the conversion proces. Start here.
|
||||
pub struct Attributes {
|
||||
handle: *mut ffi::liq_attr,
|
||||
}
|
||||
|
||||
/// Describes image dimensions for the library.
|
||||
pub struct Image<'a> {
|
||||
handle: *mut ffi::liq_image,
|
||||
/// Holds row pointers for images with stride
|
||||
_marker: marker::PhantomData<&'a [u8]>,
|
||||
}
|
||||
|
||||
/// Palette inside.
|
||||
pub struct QuantizationResult {
|
||||
handle: *mut ffi::liq_result,
|
||||
}
|
||||
|
||||
/// Generate one shared palette for multiple images.
|
||||
pub struct Histogram<'a> {
|
||||
attr: &'a Attributes,
|
||||
handle: *mut ffi::liq_histogram,
|
||||
}
|
||||
|
||||
impl Drop for Attributes {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
if !self.handle.is_null() {
|
||||
ffi::liq_attr_destroy(&mut *self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Drop for Image<'a> {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ffi::liq_image_destroy(&mut *self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for QuantizationResult {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ffi::liq_result_destroy(&mut *self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Drop for Histogram<'a> {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ffi::liq_histogram_destroy(&mut *self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Attributes {
|
||||
fn clone(&self) -> Attributes {
|
||||
unsafe { Attributes { handle: ffi::liq_attr_copy(&*self.handle) } }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Attributes {
|
||||
fn default() -> Attributes {
|
||||
Attributes::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Attributes {
|
||||
/// New handle for library configuration
|
||||
///
|
||||
/// See also `new_image()`
|
||||
pub fn new() -> Self {
|
||||
let handle = unsafe { ffi::liq_attr_create() };
|
||||
assert!(!handle.is_null(), "SSE-capable CPU is required for this build.");
|
||||
Attributes { handle }
|
||||
}
|
||||
|
||||
/// It's better to use `set_quality()`
|
||||
pub fn set_max_colors(&mut self, value: i32) -> liq_error {
|
||||
unsafe { ffi::liq_set_max_colors(&mut *self.handle, value) }
|
||||
}
|
||||
|
||||
/// Number of least significant bits to ignore.
|
||||
///
|
||||
/// Useful for generating palettes for VGA, 15-bit textures, or other retro platforms.
|
||||
pub fn set_min_posterization(&mut self, value: i32) -> liq_error {
|
||||
unsafe { ffi::liq_set_min_posterization(&mut *self.handle, value) }
|
||||
}
|
||||
|
||||
/// Returns number of bits of precision truncated
|
||||
pub fn min_posterization(&mut self) -> i32 {
|
||||
unsafe { ffi::liq_get_min_posterization(&*self.handle) }
|
||||
}
|
||||
|
||||
/// Range 0-100, roughly like JPEG.
|
||||
///
|
||||
/// If minimum quality can't be met, quantization will fail.
|
||||
///
|
||||
/// Default is min 0, max 100.
|
||||
pub fn set_quality(&mut self, min: u32, max: u32) -> liq_error {
|
||||
unsafe { ffi::liq_set_quality(&mut *self.handle, min as c_int, max as c_int) }
|
||||
}
|
||||
|
||||
/// Reads values set with `set_quality`
|
||||
pub fn quality(&mut self) -> (u32, u32) {
|
||||
unsafe {
|
||||
(ffi::liq_get_min_quality(&*self.handle) as u32,
|
||||
ffi::liq_get_max_quality(&*self.handle) as u32)
|
||||
}
|
||||
}
|
||||
|
||||
/// 1-10.
|
||||
///
|
||||
/// Faster speeds generate images of lower quality, but may be useful
|
||||
/// for real-time generation of images.
|
||||
pub fn set_speed(&mut self, value: i32) -> liq_error {
|
||||
unsafe { ffi::liq_set_speed(&mut *self.handle, value) }
|
||||
}
|
||||
|
||||
/// Move transparent color to the last entry in the palette
|
||||
///
|
||||
/// This is less efficient for PNG, but required by some broken software
|
||||
pub fn set_last_index_transparent(&mut self, value: bool) {
|
||||
unsafe { ffi::liq_set_last_index_transparent(&mut *self.handle, value as c_int) }
|
||||
}
|
||||
|
||||
/// Return currently set speed/quality trade-off setting
|
||||
pub fn speed(&mut self) -> i32 {
|
||||
unsafe { ffi::liq_get_speed(&*self.handle) }
|
||||
}
|
||||
|
||||
/// Return max number of colors set
|
||||
pub fn max_colors(&mut self) -> i32 {
|
||||
unsafe { ffi::liq_get_max_colors(&*self.handle) }
|
||||
}
|
||||
|
||||
/// Describe dimensions of a slice of RGBA pixels
|
||||
///
|
||||
/// Use 0.0 for gamma if the image is sRGB (most images are).
|
||||
pub fn new_image<'a, RGBA: Copy>(&self, bitmap: &'a [RGBA], width: usize, height: usize, gamma: f64) -> Result<Image<'a>, liq_error> {
|
||||
Image::new(self, bitmap, width, height, gamma)
|
||||
}
|
||||
|
||||
/// Stride is in pixels. Allows defining regions of larger images or images with padding without copying.
|
||||
pub fn new_image_stride<'a, RGBA: Copy>(&self, bitmap: &'a [RGBA], width: usize, height: usize, stride: usize, gamma: f64) -> Result<Image<'a>, liq_error> {
|
||||
Image::new_stride(self, bitmap, width, height, stride, gamma)
|
||||
}
|
||||
|
||||
/// Create new histogram
|
||||
///
|
||||
/// Use to make one palette suitable for many images
|
||||
pub fn new_histogram(&self) -> Histogram<'_> {
|
||||
Histogram::new(&self)
|
||||
}
|
||||
|
||||
/// Generate palette for the image
|
||||
pub fn quantize(&mut self, image: &Image<'_>) -> Result<QuantizationResult, liq_error> {
|
||||
unsafe {
|
||||
let mut h = ptr::null_mut();
|
||||
match ffi::liq_image_quantize(&*image.handle, &*self.handle, &mut h) {
|
||||
liq_error::LIQ_OK if !h.is_null() => Ok(QuantizationResult { handle: h }),
|
||||
err => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start here: creates new handle for library configuration
|
||||
pub fn new() -> Attributes {
|
||||
Attributes::new()
|
||||
}
|
||||
|
||||
impl<'a> Histogram<'a> {
|
||||
/// Creates histogram object that will be used to collect color statistics from multiple images.
|
||||
///
|
||||
/// All options should be set on `attr` before the histogram object is created. Options changed later may not have effect.
|
||||
pub fn new(attr: &'a Attributes) -> Self {
|
||||
Histogram {
|
||||
attr,
|
||||
handle: unsafe { ffi::liq_histogram_create(&*attr.handle) },
|
||||
}
|
||||
}
|
||||
|
||||
/// "Learns" colors from the image, which will be later used to generate the palette.
|
||||
///
|
||||
/// Fixed colors added to the image are also added to the histogram. If total number of fixed colors exceeds 256, this function will fail with `LIQ_BUFFER_TOO_SMALL`.
|
||||
pub fn add_image(&mut self, image: &mut Image<'_>) -> liq_error {
|
||||
unsafe { ffi::liq_histogram_add_image(&mut *self.handle, &*self.attr.handle, &mut *image.handle) }
|
||||
}
|
||||
|
||||
/// Alternative to `add_image()`. Intead of counting colors in an image, it directly takes an array of colors and their counts.
|
||||
///
|
||||
/// This function is only useful if you already have a histogram of the image from another source.
|
||||
pub fn add_colors(&mut self, colors: &[HistogramEntry], gamma: f64) -> liq_error {
|
||||
unsafe {
|
||||
ffi::liq_histogram_add_colors(&mut *self.handle, &*self.attr.handle, colors.as_ptr(), colors.len() as c_int, gamma)
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate palette for all images/colors added to the histogram.
|
||||
///
|
||||
/// Palette generated using this function won't be improved during remapping.
|
||||
/// If you're generating palette for only one image, it's better not to use the `Histogram`.
|
||||
pub fn quantize(&mut self) -> Result<QuantizationResult, liq_error> {
|
||||
unsafe {
|
||||
let mut h = ptr::null_mut();
|
||||
match ffi::liq_histogram_quantize(&*self.handle, &*self.attr.handle, &mut h) {
|
||||
liq_error::LIQ_OK if !h.is_null() => Ok(QuantizationResult { handle: h }),
|
||||
err => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate image row on the fly
|
||||
///
|
||||
/// `output_row` is an array `width` RGBA elements wide.
|
||||
/// `y` is the row (0-indexed) to write to the `output_row`
|
||||
/// `user_data` is the data given to `Image::new_unsafe_fn()`
|
||||
pub type ConvertRowUnsafeFn<UserData> = unsafe extern "C" fn(output_row: *mut Color, y: c_int, width: c_int, user_data: *mut UserData);
|
||||
|
||||
impl<'bitmap> Image<'bitmap> {
|
||||
/// Describe dimensions of a slice of RGBA pixels.
|
||||
///
|
||||
/// `bitmap` must be either `&[u8]` or a slice with one element per pixel (`&[RGBA]`).
|
||||
///
|
||||
/// Use `0.` for gamma if the image is sRGB (most images are).
|
||||
#[inline]
|
||||
pub fn new<PixelType: Copy>(attr: &Attributes, bitmap: &'bitmap [PixelType], width: usize, height: usize, gamma: f64) -> Result<Self, liq_error> {
|
||||
Self::new_stride(attr, bitmap, width, height, width, gamma)
|
||||
}
|
||||
|
||||
/// Generate rows on demand using a callback function.
|
||||
///
|
||||
/// The callback function must be cheap (e.g. just byte-swap pixels).
|
||||
/// It will be called multiple times per row. May be called in any order from any thread.
|
||||
///
|
||||
/// The user data must be compatible with a primitive pointer
|
||||
/// (i.e. not a slice, not a Trait object. `Box` it if you must).
|
||||
pub fn new_unsafe_fn<CustomData: Send + Sync + 'bitmap>(attr: &Attributes, convert_row_fn: ConvertRowUnsafeFn<CustomData>, user_data: *mut CustomData, width: usize, height: usize, gamma: f64) -> Result<Self, liq_error> {
|
||||
unsafe {
|
||||
match ffi::liq_image_create_custom(&*attr.handle, mem::transmute(convert_row_fn), user_data as *mut _, width as c_int, height as c_int, gamma) {
|
||||
handle if !handle.is_null() => Ok(Image { handle, _marker: marker::PhantomData }),
|
||||
_ => Err(LIQ_INVALID_POINTER),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stride is in pixels. Allows defining regions of larger images or images with padding without copying.
|
||||
pub fn new_stride<PixelType: Copy>(attr: &Attributes, bitmap: &'bitmap [PixelType], width: usize, height: usize, stride: usize, gamma: f64) -> Result<Self, liq_error> {
|
||||
let bytes_per_pixel = mem::size_of::<PixelType>();
|
||||
match bytes_per_pixel {
|
||||
1 | 4 => {}
|
||||
_ => return Err(LIQ_UNSUPPORTED),
|
||||
}
|
||||
if bitmap.len() * bytes_per_pixel < (stride * height + width - stride) * 4 {
|
||||
eprintln!("Buffer length is {}×{} bytes, which is not enough for {}×{}×4 RGBA bytes", bitmap.len(), bytes_per_pixel, stride, height);
|
||||
return Err(LIQ_BUFFER_TOO_SMALL);
|
||||
}
|
||||
unsafe {
|
||||
let rows = Self::malloc_image_rows(bitmap, stride, height, bytes_per_pixel);
|
||||
match ffi::liq_image_create_rgba_rows(&*attr.handle, rows, width as c_int, height as c_int, gamma) {
|
||||
h if !h.is_null() && ffi::liq_image_set_memory_ownership(&*h, ffi::liq_ownership::LIQ_OWN_ROWS).is_ok() => {
|
||||
Ok(Image {
|
||||
handle: h,
|
||||
_marker: marker::PhantomData,
|
||||
})
|
||||
},
|
||||
_ => {
|
||||
libc::free(rows as *mut _);
|
||||
Err(LIQ_INVALID_POINTER)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// For arbitrary stride libimagequant requires rows. It's most convenient if they're allocated using libc,
|
||||
/// so they can be owned and freed automatically by the C library.
|
||||
unsafe fn malloc_image_rows<PixelType: Copy>(bitmap: &'bitmap [PixelType], stride: usize, height: usize, bytes_per_pixel: usize) -> *mut *const u8 {
|
||||
let mut byte_ptr = bitmap.as_ptr() as *const u8;
|
||||
let stride_bytes = (stride * bytes_per_pixel) as isize;
|
||||
let rows = libc::malloc(mem::size_of::<*const u8>() * height) as *mut *const u8;
|
||||
for y in 0..height as isize {
|
||||
*rows.offset(y) = byte_ptr;
|
||||
byte_ptr = byte_ptr.offset(stride_bytes);
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Width of the image in pixels
|
||||
pub fn width(&self) -> usize {
|
||||
unsafe { ffi::liq_image_get_width(&*self.handle) as usize }
|
||||
}
|
||||
|
||||
/// Height of the image in pixels
|
||||
pub fn height(&self) -> usize {
|
||||
unsafe { ffi::liq_image_get_height(&*self.handle) as usize }
|
||||
}
|
||||
|
||||
/// Reserves a color in the output palette created from this image. It behaves as if the given color was used in the image and was very important.
|
||||
///
|
||||
/// RGB values of liq_color are assumed to have the same gamma as the image.
|
||||
///
|
||||
/// It must be called before the image is quantized.
|
||||
///
|
||||
/// Returns error if more than 256 colors are added. If image is quantized to fewer colors than the number of fixed colors added, then excess fixed colors will be ignored.
|
||||
pub fn add_fixed_color(&mut self, color: ffi::liq_color) -> liq_error {
|
||||
unsafe {
|
||||
ffi::liq_image_add_fixed_color(&mut *self.handle, color)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remap pixels assuming they will be displayed on this background.
|
||||
///
|
||||
/// Pixels that match the background color will be made transparent if there's a fully transparent color available in the palette.
|
||||
///
|
||||
/// The background image's pixels must outlive this image
|
||||
pub fn set_background<'own, 'bg: 'own>(&'own mut self, background: Image<'bg>) -> Result<(), liq_error> {
|
||||
unsafe {
|
||||
ffi::liq_image_set_background(&mut *self.handle, background.into_raw()).ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// Set which pixels are more important (and more likely to get a palette entry)
|
||||
///
|
||||
/// The map must be `width`×`height` pixels large. Higher numbers = more important.
|
||||
pub fn set_importance_map(&mut self, map: &[u8]) -> Result<(), liq_error> {
|
||||
unsafe {
|
||||
ffi::liq_image_set_importance_map(&mut *self.handle, map.as_ptr() as *mut _, map.len(), ffi::liq_ownership::LIQ_COPY_PIXELS).ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn into_raw(mut self) -> *mut ffi::liq_image {
|
||||
let handle = self.handle;
|
||||
self.handle = ptr::null_mut();
|
||||
handle
|
||||
}
|
||||
}
|
||||
|
||||
impl QuantizationResult {
|
||||
/// Set to 1.0 to get nice smooth image
|
||||
pub fn set_dithering_level(&mut self, value: f32) -> liq_error {
|
||||
unsafe { ffi::liq_set_dithering_level(&mut *self.handle, value) }
|
||||
}
|
||||
|
||||
/// The default is sRGB gamma (~1/2.2)
|
||||
pub fn set_output_gamma(&mut self, value: f64) -> liq_error {
|
||||
unsafe { ffi::liq_set_output_gamma(&mut *self.handle, value) }
|
||||
}
|
||||
|
||||
/// Approximate gamma correction value used for the output
|
||||
///
|
||||
/// Colors are converted from input gamma to this gamma
|
||||
pub fn output_gamma(&mut self) -> f64 {
|
||||
unsafe { ffi::liq_get_output_gamma(&*self.handle) }
|
||||
}
|
||||
|
||||
/// Number 0-100 guessing how nice the input image will look if remapped to this palette
|
||||
pub fn quantization_quality(&self) -> i32 {
|
||||
unsafe { ffi::liq_get_quantization_quality(&*self.handle) as i32 }
|
||||
}
|
||||
|
||||
/// Approximate mean square error of the palette
|
||||
pub fn quantization_error(&self) -> Option<f64> {
|
||||
match unsafe { ffi::liq_get_quantization_error(&*self.handle) } {
|
||||
x if x < 0. => None,
|
||||
x => Some(x),
|
||||
}
|
||||
}
|
||||
|
||||
/// Final palette
|
||||
///
|
||||
/// It's slighly better if you get palette from the `remapped()` call instead
|
||||
pub fn palette(&mut self) -> Vec<Color> {
|
||||
unsafe {
|
||||
let pal = &*ffi::liq_get_palette(&mut *self.handle);
|
||||
pal.entries.iter().cloned().take(pal.count as usize).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Remap image
|
||||
///
|
||||
/// Returns palette and 1-byte-per-pixel uncompresed bitmap
|
||||
pub fn remapped(&mut self, image: &mut Image<'_>) -> Result<(Vec<Color>, Vec<u8>), liq_error> {
|
||||
let len = image.width() * image.height();
|
||||
let mut buf = Vec::with_capacity(len);
|
||||
unsafe {
|
||||
buf.set_len(len); // Creates uninitialized buffer
|
||||
match ffi::liq_write_remapped_image(&mut *self.handle, &mut *image.handle, buf.as_mut_ptr(), buf.len()) {
|
||||
LIQ_OK => Ok((self.palette(), buf)),
|
||||
err => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for QuantizationResult {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "QuantizationResult(q={})", self.quantization_quality())
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for Attributes {}
|
||||
unsafe impl Send for QuantizationResult {}
|
||||
unsafe impl<'bitmap> Send for Image<'bitmap> {}
|
||||
unsafe impl<'a> Send for Histogram<'a> {}
|
||||
|
||||
#[test]
|
||||
fn takes_rgba() {
|
||||
let liq = Attributes::new();
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct RGBA {r:u8, g:u8, b:u8, a:u8};
|
||||
let img = vec![RGBA {r:0, g:0, b:0, a:0}; 8];
|
||||
|
||||
|
||||
liq.new_image(&img, 1, 1, 0.0).unwrap();
|
||||
liq.new_image(&img, 4, 2, 0.0).unwrap();
|
||||
liq.new_image(&img, 8, 1, 0.0).unwrap();
|
||||
assert!(liq.new_image(&img, 9, 1, 0.0).is_err());
|
||||
assert!(liq.new_image(&img, 4, 3, 0.0).is_err());
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct RGB {r:u8, g:u8, b:u8};
|
||||
let badimg = vec![RGB {r:0, g:0, b:0}; 8];
|
||||
assert!(liq.new_image(&badimg, 1, 1, 0.0).is_err());
|
||||
assert!(liq.new_image(&badimg, 100, 100, 0.0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram() {
|
||||
let attr = Attributes::new();
|
||||
let mut hist = attr.new_histogram();
|
||||
|
||||
let bitmap1 = vec![0u8; 4];
|
||||
let mut image1 = attr.new_image(&bitmap1[..], 1, 1, 0.0).unwrap();
|
||||
hist.add_image(&mut image1);
|
||||
|
||||
let bitmap2 = vec![255u8; 4];
|
||||
let mut image2 = attr.new_image(&bitmap2[..], 1, 1, 0.0).unwrap();
|
||||
hist.add_image(&mut image2);
|
||||
|
||||
hist.add_colors(&[HistogramEntry{
|
||||
color: Color::new(255,128,255,128),
|
||||
count: 10,
|
||||
}], 0.0);
|
||||
|
||||
let mut res = hist.quantize().unwrap();
|
||||
let pal = res.palette();
|
||||
assert_eq!(3, pal.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poke_it() {
|
||||
let width = 10usize;
|
||||
let height = 10usize;
|
||||
let mut fakebitmap = vec![255u8; 4*width*height];
|
||||
|
||||
fakebitmap[0] = 0x55;
|
||||
fakebitmap[1] = 0x66;
|
||||
fakebitmap[2] = 0x77;
|
||||
|
||||
// Configure the library
|
||||
let mut liq = Attributes::new();
|
||||
liq.set_speed(5);
|
||||
liq.set_quality(70, 99);
|
||||
liq.set_min_posterization(1);
|
||||
assert_eq!(1, liq.min_posterization());
|
||||
liq.set_min_posterization(0);
|
||||
|
||||
// Describe the bitmap
|
||||
let ref mut img = liq.new_image(&fakebitmap[..], width, height, 0.0).unwrap();
|
||||
|
||||
// The magic happens in quantize()
|
||||
let mut res = match liq.quantize(img) {
|
||||
Ok(res) => res,
|
||||
Err(err) => panic!("Quantization failed, because: {:?}", err),
|
||||
};
|
||||
|
||||
// Enable dithering for subsequent remappings
|
||||
res.set_dithering_level(1.0);
|
||||
|
||||
// You can reuse the result to generate several images with the same palette
|
||||
let (palette, pixels) = res.remapped(img).unwrap();
|
||||
|
||||
assert_eq!(width * height, pixels.len());
|
||||
assert_eq!(100, res.quantization_quality());
|
||||
assert_eq!(Color { r: 255, g: 255, b: 255, a: 255 }, palette[0]);
|
||||
assert_eq!(Color { r: 0x55, g: 0x66, b: 0x77, a: 255 }, palette[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_importance_map() {
|
||||
use crate::ffi::liq_color as RGBA;
|
||||
let mut liq = new();
|
||||
let bitmap = &[RGBA::new(255, 0, 0, 255), RGBA::new(0u8, 0, 255, 255)];
|
||||
let ref mut img = liq.new_image(&bitmap[..], 2, 1, 0.).unwrap();
|
||||
let map = &[255, 0];
|
||||
img.set_importance_map(map).unwrap();
|
||||
let mut res = liq.quantize(img).unwrap();
|
||||
let pal = res.palette();
|
||||
assert_eq!(1, pal.len());
|
||||
assert_eq!(bitmap[0], pal[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread() {
|
||||
let liq = Attributes::new();
|
||||
std::thread::spawn(move || {
|
||||
let b = vec![0u8;4];
|
||||
liq.new_image(&b, 1, 1, 0.).unwrap();
|
||||
}).join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_test() {
|
||||
let mut called = 0;
|
||||
let mut res = {
|
||||
let mut a = new();
|
||||
unsafe extern "C" fn get_row(output_row: *mut Color, y: c_int, width: c_int, user_data: *mut i32) {
|
||||
assert!(y >= 0 && y < 5);
|
||||
assert_eq!(123, width);
|
||||
for i in 0..width as isize {
|
||||
let n = i as u8;
|
||||
*output_row.offset(i as isize) = Color::new(n,n,n,n);
|
||||
}
|
||||
*user_data += 1;
|
||||
}
|
||||
let mut img = Image::new_unsafe_fn(&a, get_row, &mut called, 123, 5, 0.).unwrap();
|
||||
a.quantize(&mut img).unwrap()
|
||||
};
|
||||
assert!(called > 5 && called < 50);
|
||||
assert_eq!(123, res.palette().len());
|
||||
}
|
63
CloverApp/Clover/libimagequant/rust-sys/build.rs
Normal file
63
CloverApp/Clover/libimagequant/rust-sys/build.rs
Normal file
@ -0,0 +1,63 @@
|
||||
//! This is a build script for Cargo https://crates.io/
|
||||
//! It produces a static library that can be used by C or Rust.
|
||||
|
||||
extern crate cc;
|
||||
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::fs::canonicalize;
|
||||
|
||||
fn main() {
|
||||
let mut cc = cc::Build::new();
|
||||
let compiler = cc.get_compiler();
|
||||
cc.warnings(false);
|
||||
|
||||
if env::var("PROFILE").map(|p|p != "debug").unwrap_or(true) {
|
||||
cc.define("NDEBUG", Some("1"));
|
||||
} else {
|
||||
cc.define("DEBUG", Some("1"));
|
||||
}
|
||||
|
||||
if cfg!(feature = "openmp") {
|
||||
cc.flag(&env::var("DEP_OPENMP_FLAG").unwrap());
|
||||
}
|
||||
|
||||
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").expect("Needs CARGO_CFG_TARGET_ARCH");
|
||||
if target_arch =="x86_64" ||
|
||||
(target_arch == "x86" && cfg!(feature = "sse")) {
|
||||
cc.flag(if compiler.is_like_msvc() {"/arch:SSE2"} else {"-msse"});
|
||||
cc.define("USE_SSE", Some("1"));
|
||||
}
|
||||
|
||||
let outdated_c_compiler = env::var("TARGET").unwrap().contains("windows-msvc");
|
||||
let has_msvc_files = PathBuf::from("msvc-dist/libimagequant.c").exists();
|
||||
|
||||
if outdated_c_compiler && has_msvc_files {
|
||||
println!("cargo:include={}", canonicalize("msvc-dist").unwrap().display());
|
||||
cc.file("msvc-dist/libimagequant.c")
|
||||
.file("msvc-dist/nearest.c")
|
||||
.file("msvc-dist/kmeans.c")
|
||||
.file("msvc-dist/mediancut.c")
|
||||
.file("msvc-dist/mempool.c")
|
||||
.file("msvc-dist/pam.c")
|
||||
.file("msvc-dist/blur.c");
|
||||
} else {
|
||||
// This is so that I don't forget to publish MSVC version as well
|
||||
if !has_msvc_files {
|
||||
println!("cargo:warning=msvc-dist/ directory not present. MSVC builds may fail");
|
||||
}
|
||||
println!("cargo:include={}", canonicalize(".").unwrap().display());
|
||||
if !compiler.is_like_msvc() {
|
||||
cc.flag("-std=c99");
|
||||
}
|
||||
cc.file("libimagequant.c")
|
||||
.file("nearest.c")
|
||||
.file("kmeans.c")
|
||||
.file("mediancut.c")
|
||||
.file("mempool.c")
|
||||
.file("pam.c")
|
||||
.file("blur.c");
|
||||
}
|
||||
|
||||
cc.compile("libimagequant.a");
|
||||
}
|
307
CloverApp/Clover/libimagequant/rust-sys/libimagequant.rs
Normal file
307
CloverApp/Clover/libimagequant/rust-sys/libimagequant.rs
Normal file
@ -0,0 +1,307 @@
|
||||
//! Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images.
|
||||
//! It's powering [pngquant2](https://pngquant.org).
|
||||
//!
|
||||
//! This is a low-level crate exposing a C API. If you're looking for a Rust library, see [imagequant](https://crates.io/crates/imagequant).
|
||||
//!
|
||||
//! ## License
|
||||
//!
|
||||
//! Libimagequant is dual-licensed:
|
||||
//!
|
||||
//! * For Free/Libre Open Source Software it's available under [GPL v3 or later](https://raw.github.com/ImageOptim/libimagequant/master/COPYRIGHT) with additional copyright notices for older parts of the code.
|
||||
//!
|
||||
//! * For use in non-GPL software (e.g. closed-source or App Store distribution) please ask kornel@pngquant.org for a commercial license.
|
||||
//!
|
||||
//! ## Overview
|
||||
//!
|
||||
//! The basic flow is:
|
||||
//!
|
||||
//! 1. Create attributes object and configure the library.
|
||||
//! 2. Create image object from RGBA pixels or data source.
|
||||
//! 3. Perform quantization (generate palette).
|
||||
//! 4. Store remapped image and final palette.
|
||||
//! 5. Free memory.
|
||||
//!
|
||||
//! Please note that libimagequant only handles raw uncompressed arrays of pixels in memory and is completely independent of any file format.
|
||||
//!
|
||||
//! There are 3 ways to create image object for quantization:
|
||||
//!
|
||||
//! * `liq_image_create_rgba()` for simple, contiguous RGBA pixel arrays (width×height×4 bytes large bitmap).
|
||||
//! * `liq_image_create_rgba_rows()` for non-contiguous RGBA pixel arrays (that have padding between rows or reverse order, e.g. BMP).
|
||||
//! * `liq_image_create_custom()` for RGB, ABGR, YUV and all other formats that can be converted on-the-fly to RGBA (you have to supply the conversion function).
|
||||
//!
|
||||
//! Note that "image" here means raw uncompressed pixels. If you have a compressed image file, such as PNG, you must use another library (e.g. lodepng) to decode it first.
|
||||
|
||||
#![allow(non_camel_case_types)]
|
||||
|
||||
#[cfg(feature = "openmp")]
|
||||
extern crate openmp_sys;
|
||||
|
||||
use std::os::raw::{c_int, c_uint, c_char, c_void};
|
||||
use std::error;
|
||||
use std::fmt;
|
||||
use std::error::Error;
|
||||
|
||||
pub enum liq_attr {}
|
||||
pub enum liq_image {}
|
||||
pub enum liq_result {}
|
||||
pub enum liq_histogram {}
|
||||
pub type liq_color = rgb::RGBA8;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
||||
pub enum liq_error {
|
||||
LIQ_OK = 0,
|
||||
LIQ_QUALITY_TOO_LOW = 99,
|
||||
LIQ_VALUE_OUT_OF_RANGE = 100,
|
||||
LIQ_OUT_OF_MEMORY,
|
||||
LIQ_ABORTED,
|
||||
LIQ_BITMAP_NOT_AVAILABLE,
|
||||
LIQ_BUFFER_TOO_SMALL,
|
||||
LIQ_INVALID_POINTER,
|
||||
LIQ_UNSUPPORTED,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone)]
|
||||
pub enum liq_ownership {
|
||||
LIQ_OWN_ROWS = 4,
|
||||
LIQ_OWN_PIXELS = 8,
|
||||
LIQ_COPY_PIXELS = 16,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct liq_palette {
|
||||
pub count: c_int,
|
||||
pub entries: [liq_color; 256],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct liq_histogram_entry {
|
||||
pub color: liq_color,
|
||||
pub count: c_uint,
|
||||
}
|
||||
|
||||
impl error::Error for liq_error {
|
||||
fn description(&self) -> &str {
|
||||
match *self {
|
||||
liq_error::LIQ_OK => "OK",
|
||||
liq_error::LIQ_QUALITY_TOO_LOW => "LIQ_QUALITY_TOO_LOW",
|
||||
liq_error::LIQ_VALUE_OUT_OF_RANGE => "VALUE_OUT_OF_RANGE",
|
||||
liq_error::LIQ_OUT_OF_MEMORY => "OUT_OF_MEMORY",
|
||||
liq_error::LIQ_ABORTED => "LIQ_ABORTED",
|
||||
liq_error::LIQ_BITMAP_NOT_AVAILABLE => "BITMAP_NOT_AVAILABLE",
|
||||
liq_error::LIQ_BUFFER_TOO_SMALL => "BUFFER_TOO_SMALL",
|
||||
liq_error::LIQ_INVALID_POINTER => "INVALID_POINTER",
|
||||
liq_error::LIQ_UNSUPPORTED => "LIQ_UNSUPPORTED",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for liq_error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.description())
|
||||
}
|
||||
}
|
||||
|
||||
impl liq_error {
|
||||
#[inline]
|
||||
pub fn is_ok(&self) -> bool {
|
||||
*self == liq_error::LIQ_OK
|
||||
}
|
||||
|
||||
pub fn is_err(&self) -> bool {
|
||||
!self.is_ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn ok(&self) -> Result<(), liq_error> {
|
||||
match *self {
|
||||
liq_error::LIQ_OK => Ok(()),
|
||||
e => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn ok_or<E>(self, err: E) -> Result<(), E> {
|
||||
if self.is_ok() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unwrap(&self) {
|
||||
assert!(self.is_ok(), "{}", self);
|
||||
}
|
||||
|
||||
pub fn expect(&self, msg: &str) {
|
||||
assert!(self.is_ok(), "{}", msg);
|
||||
}
|
||||
}
|
||||
|
||||
pub type liq_log_callback_function = Option<unsafe extern "C" fn(arg1: &liq_attr, message: *const c_char, user_info: *mut c_void)>;
|
||||
pub type liq_log_flush_callback_function = Option<unsafe extern "C" fn(arg1: &liq_attr, user_info: *mut c_void)>;
|
||||
pub type liq_progress_callback_function = Option<unsafe extern "C" fn(progress_percent: f32, user_info: *mut c_void) -> c_int>;
|
||||
pub type liq_image_get_rgba_row_callback = unsafe extern "C" fn(row_out: *mut liq_color, row: c_int, width: c_int, user_info: *mut c_void);
|
||||
|
||||
#[link(name="imagequant", kind="static")]
|
||||
extern "C" {
|
||||
|
||||
/// Returns object that will hold initial settings (attributes) for the library.
|
||||
///
|
||||
/// The object should be freed using `liq_attr_destroy()` after it's no longer needed.
|
||||
/// Returns `NULL` in the unlikely case that the library cannot run on the current machine (e.g. the library has been compiled for SSE-capable x86 CPU and run on VIA C3 CPU).
|
||||
pub fn liq_attr_create() -> *mut liq_attr;
|
||||
pub fn liq_attr_copy(orig: &liq_attr) -> *mut liq_attr;
|
||||
pub fn liq_attr_destroy(attr: &mut liq_attr);
|
||||
|
||||
/// Specifies maximum number of colors to use.
|
||||
///
|
||||
/// The default is 256. Instead of setting a fixed limit it's better to use `liq_set_quality()`.
|
||||
/// The first argument is attributes object from `liq_attr_create()`.
|
||||
/// Returns `LIQ_VALUE_OUT_OF_RANGE` if number of colors is outside the range 2-256.
|
||||
pub fn liq_set_max_colors(attr: &mut liq_attr, colors: c_int) -> liq_error;
|
||||
pub fn liq_get_max_colors(attr: &liq_attr) -> c_int;
|
||||
pub fn liq_set_speed(attr: &mut liq_attr, speed: c_int) -> liq_error;
|
||||
pub fn liq_get_speed(attr: &liq_attr) -> c_int;
|
||||
pub fn liq_set_min_posterization(attr: &mut liq_attr, bits: c_int) -> liq_error;
|
||||
pub fn liq_get_min_posterization(attr: &liq_attr) -> c_int;
|
||||
/// Quality is in range `0` (worst) to `100` (best) and values are analoguous to JPEG quality (i.e. `80` is usually good enough).
|
||||
///
|
||||
/// Quantization will attempt to use the lowest number of colors needed to achieve `maximum` quality. `maximum` value of `100` is the default and means conversion as good as possible.
|
||||
/// If it's not possible to convert the image with at least `minimum` quality (i.e. 256 colors is not enough to meet the minimum quality), then `liq_image_quantize()` will fail. The default minumum is `0` (proceeds regardless of quality).
|
||||
/// Quality measures how well the generated palette fits image given to `liq_image_quantize()`. If a different image is remapped with `liq_write_remapped_image()` then actual quality may be different.
|
||||
/// Regardless of the quality settings the number of colors won't exceed the maximum (see `liq_set_max_colors()`).
|
||||
/// The first argument is attributes object from `liq_attr_create()`.
|
||||
///
|
||||
/// Returns `LIQ_VALUE_OUT_OF_RANGE` if target is lower than minimum or any of them is outside the 0-100 range.
|
||||
/// Returns `LIQ_INVALID_POINTER` if `attr` appears to be invalid.
|
||||
pub fn liq_set_quality(attr: &mut liq_attr, minimum: c_int, maximum: c_int) -> liq_error;
|
||||
pub fn liq_get_min_quality(attr: &liq_attr) -> c_int;
|
||||
pub fn liq_get_max_quality(attr: &liq_attr) -> c_int;
|
||||
pub fn liq_set_last_index_transparent(attr: &mut liq_attr, is_last: c_int);
|
||||
|
||||
pub fn liq_image_create_rgba_rows(attr: &liq_attr, rows: *const *const u8, width: c_int, height: c_int, gamma: f64) -> *mut liq_image;
|
||||
/// Creates an object that represents the image pixels to be used for quantization and remapping.
|
||||
///
|
||||
/// The pixel array must be contiguous run of RGBA pixels (alpha is the last component, 0 = transparent, 255 = opaque).
|
||||
///
|
||||
/// The first argument is attributes object from `liq_attr_create()`. The same `attr` object should be used for the entire process, from creation of images to quantization.
|
||||
///
|
||||
/// The `pixels` array must not be modified or freed until this object is freed with `liq_image_destroy()`. See also `liq_image_set_memory_ownership()`.
|
||||
///
|
||||
/// `width` and `height` are dimensions in pixels. An image 10x10 pixel large will need a 400-byte array.
|
||||
///
|
||||
/// `gamma` can be `0` for images with the typical 1/2.2 [gamma](https://en.wikipedia.org/wiki/Gamma_correction).
|
||||
/// Otherwise `gamma` must be > 0 and < 1, e.g. `0.45455` (1/2.2) or `0.55555` (1/1.8). Generated palette will use the same gamma unless `liq_set_output_gamma()` is used. If `liq_set_output_gamma` is not used, then it only affects whether brighter or darker areas of the image will get more palette colors allocated.
|
||||
///
|
||||
/// Returns `NULL` on failure, e.g. if `pixels` is `NULL` or `width`/`height` is <= 0.
|
||||
pub fn liq_image_create_rgba(attr: &liq_attr, bitmap: *const u8, width: c_int, height: c_int, gamma: f64) -> *mut liq_image;
|
||||
/// unsafe: It will crash if the owned memory wasn't allocated using `libc::malloc()` (or whatever allocator C side is using)
|
||||
pub fn liq_image_set_memory_ownership(image: &liq_image, own: liq_ownership) -> liq_error;
|
||||
|
||||
pub fn liq_set_log_callback(arg1: &mut liq_attr, arg2: liq_log_callback_function, user_info: *mut c_void);
|
||||
pub fn liq_set_log_flush_callback(arg1: &mut liq_attr, arg2: liq_log_flush_callback_function, user_info: *mut c_void);
|
||||
pub fn liq_attr_set_progress_callback(arg1: &mut liq_attr, arg2: liq_progress_callback_function, user_info: *mut c_void);
|
||||
pub fn liq_result_set_progress_callback(arg1: &mut liq_result, arg2: liq_progress_callback_function, user_info: *mut c_void);
|
||||
pub fn liq_image_create_custom(attr: &liq_attr, row_callback: liq_image_get_rgba_row_callback, user_info: *mut c_void, width: c_int, height: c_int, gamma: f64) -> *mut liq_image;
|
||||
/// Remap assuming the image will be always presented exactly on top of this background.
|
||||
///
|
||||
/// Takes ownership of the background image (i.e. do NOT use it afterwards, do NOT call liq_image_destroy on it).
|
||||
///
|
||||
/// The background must have the same size. The foreground image must have a transparent color.
|
||||
pub fn liq_image_set_background(img: &mut liq_image, background: *mut liq_image) -> liq_error;
|
||||
pub fn liq_image_set_importance_map(img: &mut liq_image, buffer: *mut u8, buffer_size: usize, own: liq_ownership) -> liq_error;
|
||||
pub fn liq_image_add_fixed_color(img: &mut liq_image, color: liq_color) -> liq_error;
|
||||
pub fn liq_image_get_width(img: &liq_image) -> c_int;
|
||||
pub fn liq_image_get_height(img: &liq_image) -> c_int;
|
||||
pub fn liq_image_destroy(img: &mut liq_image);
|
||||
|
||||
pub fn liq_histogram_create(attr: &liq_attr) -> *mut liq_histogram;
|
||||
pub fn liq_histogram_add_image(hist: &mut liq_histogram, attr: &liq_attr, image: &mut liq_image) -> liq_error;
|
||||
pub fn liq_histogram_add_colors(hist: &mut liq_histogram, attr: &liq_attr, entries: *const liq_histogram_entry, num_entries: c_int, gamma: f64) -> liq_error;
|
||||
pub fn liq_histogram_add_fixed_color(hist: &mut liq_histogram, color: liq_color) -> liq_error;
|
||||
pub fn liq_histogram_destroy(hist: &mut liq_histogram);
|
||||
|
||||
/// Performs quantization (palette generation) based on settings in `attr` (from `liq_attr_create()`) and pixels of the image.
|
||||
///
|
||||
/// Returns `LIQ_OK` if quantization succeeds and sets `liq_result` pointer in `out_result`. The last argument is used for receiving the `result` object:
|
||||
///
|
||||
/// liq_result *result;
|
||||
/// if (LIQ_OK == liq_image_quantize(img, attr, &result)) { // Note &result
|
||||
/// // result pointer is valid here
|
||||
/// }
|
||||
///
|
||||
/// Returns `LIQ_QUALITY_TOO_LOW` if quantization fails due to limit set in `liq_set_quality()`.
|
||||
///
|
||||
/// See `liq_write_remapped_image()`.
|
||||
///
|
||||
/// If you want to generate one palette for multiple images at once, see `liq_histogram_create()`.
|
||||
pub fn liq_quantize_image(options: &liq_attr, input_image: &liq_image) -> *mut liq_result;
|
||||
pub fn liq_histogram_quantize(input_hist: &liq_histogram, options: &liq_attr, result_output: &mut *mut liq_result) -> liq_error;
|
||||
pub fn liq_image_quantize(input_image: &liq_image, options: &liq_attr, result_output: &mut *mut liq_result) -> liq_error;
|
||||
/// Enables/disables dithering in `liq_write_remapped_image()`.
|
||||
///
|
||||
/// Dithering level must be between `0` and `1` (inclusive). Dithering level `0` enables fast non-dithered remapping. Otherwise a variation of Floyd-Steinberg error diffusion is used.
|
||||
///
|
||||
/// Precision of the dithering algorithm depends on the speed setting, see `liq_set_speed()`.
|
||||
///
|
||||
/// Returns `LIQ_VALUE_OUT_OF_RANGE` if the dithering level is outside the 0-1 range.
|
||||
pub fn liq_set_dithering_level(res: &mut liq_result, dither_level: f32) -> liq_error;
|
||||
pub fn liq_set_output_gamma(res: &mut liq_result, gamma: f64) -> liq_error;
|
||||
pub fn liq_get_output_gamma(result: &liq_result) -> f64;
|
||||
/// Returns pointer to palette optimized for image that has been quantized or remapped
|
||||
/// (final refinements are applied to the palette during remapping).
|
||||
///
|
||||
/// It's valid to call this method before remapping, if you don't plan to remap any images or want to use same palette for multiple images.
|
||||
///
|
||||
/// `liq_palette->count` contains number of colors (up to 256), `liq_palette->entries[n]` contains RGBA value for nth palette color.
|
||||
pub fn liq_get_palette<'a>(result: &'a mut liq_result) -> &'a liq_palette;
|
||||
/// Remaps the image to palette and writes its pixels to the given buffer, 1 pixel per byte.
|
||||
///
|
||||
/// The buffer must be large enough to fit the entire image, i.e. width×height bytes large. For safety, pass the size of the buffer as `buffer_size`.
|
||||
///
|
||||
/// For best performance call `liq_get_palette()` *after* this function, as palette is improved during remapping (except when `liq_histogram_quantize()` is used).
|
||||
///
|
||||
/// Returns `LIQ_BUFFER_TOO_SMALL` if given size of the buffer is not enough to fit the entire image.
|
||||
///
|
||||
/// int buffer_size = width*height;
|
||||
/// char *buffer = malloc(buffer_size);
|
||||
/// if (LIQ_OK == liq_write_remapped_image(result, input_image, buffer, buffer_size)) {
|
||||
/// liq_palette *pal = liq_get_palette(result);
|
||||
/// // save image
|
||||
/// }
|
||||
///
|
||||
/// See `liq_get_palette()`.
|
||||
///
|
||||
/// The buffer is assumed to be contiguous, with rows ordered from top to bottom, and no gaps between rows. If you need to write rows with padding or upside-down order, then use `liq_write_remapped_image_rows()`.
|
||||
///
|
||||
/// Please note that it only writes raw uncompressed pixels to memory. It does not perform any PNG compression. If you'd like to create a PNG file then you need to pass the raw pixel data to another library, e.g. libpng or lodepng. See `rwpng.c` in `pngquant` project for an example how to do that.
|
||||
pub fn liq_write_remapped_image(result: &mut liq_result, input_image: &mut liq_image, buffer: *mut u8, buffer_size: usize) -> liq_error;
|
||||
pub fn liq_write_remapped_image_rows(result: &mut liq_result, input_image: &mut liq_image, row_pointers: *const *mut u8) -> liq_error;
|
||||
pub fn liq_get_quantization_error(result: &liq_result) -> f64;
|
||||
pub fn liq_get_quantization_quality(result: &liq_result) -> c_int;
|
||||
|
||||
pub fn liq_result_destroy(res: &mut liq_result);
|
||||
pub fn liq_get_remapping_error(result: &liq_result) -> f64;
|
||||
pub fn liq_get_remapping_quality(result: &liq_result) -> c_int;
|
||||
pub fn liq_version() -> c_int;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_and_runs() {
|
||||
use std::ptr;
|
||||
unsafe {
|
||||
assert!(liq_version() >= 20901);
|
||||
let attr = liq_attr_create();
|
||||
assert!(!attr.is_null());
|
||||
let hist = liq_histogram_create(&*attr);
|
||||
assert!(!hist.is_null());
|
||||
let mut res = ptr::null_mut();
|
||||
liq_histogram_quantize(&*hist, &*attr, &mut res);
|
||||
assert!(res.is_null());
|
||||
liq_histogram_destroy(&mut *hist);
|
||||
liq_attr_destroy(&mut *attr);
|
||||
}
|
||||
}
|
27
CloverApp/libimagequant-2.12.6/.gitignore
vendored
Normal file
27
CloverApp/libimagequant-2.12.6/.gitignore
vendored
Normal file
@ -0,0 +1,27 @@
|
||||
config.mk
|
||||
imagequant.pc
|
||||
*.lo
|
||||
*.o
|
||||
*.a
|
||||
*.so.0
|
||||
*.so
|
||||
*.bz2
|
||||
*.dylib
|
||||
*.dylib.0
|
||||
*.jnilib
|
||||
*.dSYM
|
||||
org/pngquant/*.class
|
||||
org/pngquant/*.h
|
||||
target/
|
||||
msvc-dist/org/
|
||||
msvc-dist/*.md
|
||||
msvc-dist/Makefile*
|
||||
msvc-dist/*.cs
|
||||
msvc-dist/*.xml
|
||||
msvc-dist/CHANGELOG
|
||||
msvc-dist/COPYRIGHT
|
||||
msvc-dist/configure
|
||||
msvc-dist/.gitignore
|
||||
quantized_example.png
|
||||
example
|
||||
lodepng.?
|
17
CloverApp/libimagequant-2.12.6/.travis.yml
Normal file
17
CloverApp/libimagequant-2.12.6/.travis.yml
Normal file
@ -0,0 +1,17 @@
|
||||
matrix:
|
||||
include:
|
||||
- os: linux
|
||||
language: java
|
||||
jdk: oraclejdk9
|
||||
env: CFLAGS="-fPIC"
|
||||
install: true
|
||||
script: make java
|
||||
- os: linux
|
||||
language: rust
|
||||
script: cargo build --verbose --all && cargo test --verbose --all
|
||||
- os: linux
|
||||
language: generic
|
||||
script: make static
|
||||
- os: linux
|
||||
language: generic
|
||||
script: ./configure --prefix=/tmp && make libimagequant.so && make install
|
65
CloverApp/libimagequant-2.12.6/CHANGELOG
Normal file
65
CloverApp/libimagequant-2.12.6/CHANGELOG
Normal file
@ -0,0 +1,65 @@
|
||||
version 2.12
|
||||
------------
|
||||
- new liq_histogram_add_fixed_color()
|
||||
- faster for large/complex images
|
||||
- workarounds for Microsoft's outdated C compiler
|
||||
|
||||
version 2.11
|
||||
------------
|
||||
- new liq_image_set_background() for high-quality remapping of GIF frames
|
||||
- new liq_image_set_importance_map() for controlling which parts of the image get more palette colors
|
||||
- improved OpenMP support
|
||||
|
||||
version 2.10
|
||||
-----------
|
||||
- supports building with Rust/Cargo
|
||||
|
||||
version 2.9
|
||||
-----------
|
||||
- new liq_histogram_add_colors()
|
||||
|
||||
version 2.8
|
||||
-----------
|
||||
- standalone version
|
||||
- added Java interface (JNI)
|
||||
- new API for remapping multiple images to a single shared palette
|
||||
|
||||
version 2.7
|
||||
-----------
|
||||
- improved dithering of saturated and semitransparent colors
|
||||
- libimagequant reports detailed progress and supports aborting of operations via callbacks
|
||||
- fixed order of log output when using openmp
|
||||
|
||||
version 2.5
|
||||
-----------
|
||||
- replaced color search algorithm with vantage point tree, which is much faster and more reliable
|
||||
- deprecated IE6 workaround
|
||||
- warn when compiled without color profile support
|
||||
- improved support for predefined colors in libimagequant
|
||||
|
||||
version 2.4
|
||||
-----------
|
||||
- fixed remapping of bright colors when dithering
|
||||
- added libimagequant API to add fixed preset colors to the palette
|
||||
|
||||
version 2.3
|
||||
-----------
|
||||
- added ./configure script for better support of Intel C compiler and dependencies [thanks to pdknsk]
|
||||
- tweaked quality metric to better estimate quality of images with large solid backgrounds [thanks to Rolf Timmermans]
|
||||
- avoid applying quality setting to images that use palette already
|
||||
|
||||
version 2.2
|
||||
-----------
|
||||
- OpenMP acceleration
|
||||
- improved support for Intel C Compiler, speedup in 32-bit GCC, and some workarounds for Visual Studio's incomplete C support
|
||||
|
||||
version 2.1
|
||||
-----------
|
||||
- option to generate posterized output (for use with 16-bit textures)
|
||||
|
||||
version 2.0
|
||||
-----------
|
||||
- refactored codebase into pngquant and standalone libimagequant
|
||||
- reduced memory usage by further 30% (and more for very large images)
|
||||
- less precise remapping improving speed by 25% in higher speed settings
|
||||
- fixed regression in dithering of alpha channel
|
74
CloverApp/libimagequant-2.12.6/CODE_OF_CONDUCT.md
Normal file
74
CloverApp/libimagequant-2.12.6/CODE_OF_CONDUCT.md
Normal file
@ -0,0 +1,74 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, gender identity and expression, level of experience,
|
||||
nationality, personal appearance, race, religion, or sexual identity and
|
||||
orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at kornel@geekhood.net. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at [http://contributor-covenant.org/version/1/4][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/4/
|
26
CloverApp/libimagequant-2.12.6/CONTRIBUTING.md
Normal file
26
CloverApp/libimagequant-2.12.6/CONTRIBUTING.md
Normal file
@ -0,0 +1,26 @@
|
||||
|
||||
Thank you for contributing! pngquant and libimagequant are licensed under multiple
|
||||
licenses, so to make things clear, I'm accepting contributions as licensed under
|
||||
the BSD 2-clause license:
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
641
CloverApp/libimagequant-2.12.6/COPYRIGHT
Normal file
641
CloverApp/libimagequant-2.12.6/COPYRIGHT
Normal file
@ -0,0 +1,641 @@
|
||||
|
||||
libimagequant is derived from code by Jef Poskanzer and Greg Roelofs
|
||||
licensed under pngquant's original license (at the end of this file),
|
||||
and contains extensive changes and additions by Kornel Lesiński
|
||||
licensed under GPL v3 or later.
|
||||
|
||||
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||
|
||||
libimagequant © 2009-2018 by Kornel Lesiński.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||
|
||||
© 1989, 1991 by Jef Poskanzer.
|
||||
© 1997, 2000, 2002 by Greg Roelofs.
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted, provided
|
||||
that the above copyright notice appear in all copies and that both that
|
||||
copyright notice and this permission notice appear in supporting
|
||||
documentation. This software is provided "as is" without express or
|
||||
implied warranty.
|
39
CloverApp/libimagequant-2.12.6/Cargo.toml
Normal file
39
CloverApp/libimagequant-2.12.6/Cargo.toml
Normal file
@ -0,0 +1,39 @@
|
||||
# libimagequant is a pure C library.
|
||||
# Rust/Cargo is entirely optional. You can also use ./configure && make
|
||||
[package]
|
||||
version = "2.12.6"
|
||||
authors = ["Kornel Lesiński <kornel@pngquant.org>"]
|
||||
build = "rust-sys/build.rs"
|
||||
categories = ["external-ffi-bindings"]
|
||||
homepage = "https://pngquant.org/lib"
|
||||
include = ["COPYRIGHT", "rust-sys/*", "*.c", "*.h", "README.md", "Cargo.toml"]
|
||||
keywords = ["pngquant"]
|
||||
license = "GPL-3.0+"
|
||||
links = "imagequant"
|
||||
name = "imagequant-sys"
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/ImageOptim/libimagequant"
|
||||
description = "Statically linked C part of imagequant library powering tools such as pngquant.\n\nThis library is dual-licensed like pngquant: either GPL or a commercial license. See website for details: https://pngquant.org"
|
||||
edition = "2018"
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.0.38"
|
||||
|
||||
[dependencies]
|
||||
rgb = "0.8.13"
|
||||
|
||||
[dependencies.openmp-sys]
|
||||
optional = true
|
||||
version = "0.1.5"
|
||||
|
||||
[features]
|
||||
default = ["sse"]
|
||||
openmp = ["openmp-sys"]
|
||||
openmp-static = ["openmp", "openmp-sys/static"]
|
||||
sse = []
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "staticlib", "lib"]
|
||||
name = "imagequant_sys"
|
||||
path = "rust-sys/libimagequant.rs"
|
||||
doctest = false
|
139
CloverApp/libimagequant-2.12.6/Makefile
Normal file
139
CloverApp/libimagequant-2.12.6/Makefile
Normal file
@ -0,0 +1,139 @@
|
||||
-include config.mk
|
||||
|
||||
STATICLIB=libimagequant.a
|
||||
SHAREDLIB=libimagequant.$(SOLIBSUFFIX)
|
||||
SOVER=0
|
||||
ifeq ($(SOLIBSUFFIX),dylib)
|
||||
SHAREDLIBVER=libimagequant.$(SOVER).$(SOLIBSUFFIX)
|
||||
FIX_INSTALL_NAME=install_name_tool -id $(LIBDIR)/$(SHAREDLIBVER) $(DESTDIR)$(LIBDIR)/$(SHAREDLIBVER)
|
||||
else
|
||||
SHAREDLIBVER=libimagequant.$(SOLIBSUFFIX).$(SOVER)
|
||||
FIX_INSTALL_NAME=
|
||||
endif
|
||||
|
||||
JNILIB=libimagequant.jnilib
|
||||
DLL=imagequant.dll
|
||||
DLLIMP=imagequant_dll.a
|
||||
DLLDEF=imagequant_dll.def
|
||||
JNIDLL=libimagequant.dll
|
||||
JNIDLLIMP=libimagequant_dll.a
|
||||
JNIDLLDEF=libimagequant_dll.def
|
||||
|
||||
OBJS = pam.o mediancut.o blur.o mempool.o kmeans.o nearest.o libimagequant.o
|
||||
SHAREDOBJS = $(subst .o,.lo,$(OBJS))
|
||||
|
||||
JAVACLASSES = org/pngquant/LiqObject.class org/pngquant/PngQuant.class org/pngquant/Image.class org/pngquant/Result.class
|
||||
JAVAHEADERS = $(JAVACLASSES:.class=.h)
|
||||
JAVAINCLUDE = -I'$(JAVA_HOME)/include' -I'$(JAVA_HOME)/include/linux' -I'$(JAVA_HOME)/include/win32' -I'$(JAVA_HOME)/include/darwin'
|
||||
|
||||
DISTFILES = $(OBJS:.o=.c) *.h README.md CHANGELOG COPYRIGHT Makefile configure imagequant.pc.in
|
||||
TARNAME = libimagequant-$(VERSION)
|
||||
TARFILE = $(TARNAME)-src.tar.bz2
|
||||
PKGCONFIG = imagequant.pc
|
||||
|
||||
all: static shared
|
||||
|
||||
static: $(STATICLIB)
|
||||
|
||||
shared: $(SHAREDLIB)
|
||||
|
||||
dll:
|
||||
$(MAKE) CFLAGS="$(CFLAGS) -DIMAGEQUANT_EXPORTS" $(DLL)
|
||||
|
||||
java: $(JNILIB)
|
||||
|
||||
java-dll:
|
||||
$(MAKE) CFLAGS="$(CFLAGS) -DIMAGEQUANT_EXPORTS" $(JNIDLL)
|
||||
|
||||
$(DLL) $(DLLIMP): $(OBJS)
|
||||
$(CC) -fPIC -shared -o $(DLL) $^ $(LDFLAGS) -Wl,--out-implib,$(DLLIMP),--output-def,$(DLLDEF)
|
||||
|
||||
$(STATICLIB): $(OBJS)
|
||||
$(AR) $(ARFLAGS) $@ $^
|
||||
|
||||
$(SHAREDOBJS):
|
||||
$(CC) -fPIC $(CFLAGS) -c $(@:.lo=.c) -o $@
|
||||
|
||||
libimagequant.so: $(SHAREDOBJS)
|
||||
$(CC) -shared -Wl,-soname,$(SHAREDLIBVER) -o $(SHAREDLIBVER) $^ $(LDFLAGS)
|
||||
ln -fs $(SHAREDLIBVER) $(SHAREDLIB)
|
||||
|
||||
libimagequant.dylib: $(SHAREDOBJS)
|
||||
$(CC) -shared -o $(SHAREDLIBVER) $^ $(LDFLAGS)
|
||||
ln -fs $(SHAREDLIBVER) $(SHAREDLIB)
|
||||
|
||||
$(OBJS): $(wildcard *.h) config.mk
|
||||
|
||||
$(JNILIB): $(JAVAHEADERS) $(STATICLIB) org/pngquant/PngQuant.c
|
||||
$(CC) -g $(CFLAGS) $(LDFLAGS) $(JAVAINCLUDE) -shared -o $@ org/pngquant/PngQuant.c $(STATICLIB)
|
||||
|
||||
$(JNIDLL) $(JNIDLLIMP): $(JAVAHEADERS) $(OBJS) org/pngquant/PngQuant.c
|
||||
$(CC) -fPIC -shared -I. $(JAVAINCLUDE) -o $(JNIDLL) $^ $(LDFLAGS) -Wl,--out-implib,$(JNIDLLIMP),--output-def,$(JNIDLLDEF)
|
||||
|
||||
$(JAVACLASSES): %.class: %.java
|
||||
javac $<
|
||||
|
||||
$(JAVAHEADERS): %.h: %.class
|
||||
javah -o $@ $(subst /,., $(patsubst %.class,%,$<)) && touch $@
|
||||
|
||||
dist: $(TARFILE) cargo
|
||||
|
||||
$(TARFILE): $(DISTFILES)
|
||||
rm -rf $(TARFILE) $(TARNAME)
|
||||
mkdir $(TARNAME)
|
||||
cp $(DISTFILES) $(TARNAME)
|
||||
tar -cjf $(TARFILE) --numeric-owner --exclude='._*' $(TARNAME)
|
||||
rm -rf $(TARNAME)
|
||||
-shasum $(TARFILE)
|
||||
|
||||
cargo:
|
||||
rm -rf msvc-dist
|
||||
git clone . -b msvc msvc-dist
|
||||
rm -rf msvc-dist/Cargo.toml msvc-dist/org msvc-dist/rust msvc-dist/README.md msvc-dist/COPYRIGHT
|
||||
cargo test
|
||||
|
||||
example: example.c lodepng.h lodepng.c $(STATICLIB)
|
||||
$(CC) -g $(CFLAGS) -Wall example.c $(STATICLIB) -o example
|
||||
|
||||
lodepng.h:
|
||||
curl -o lodepng.h -L https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.h
|
||||
|
||||
lodepng.c:
|
||||
curl -o lodepng.c -L https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.cpp
|
||||
|
||||
clean:
|
||||
rm -f $(OBJS) $(SHAREDOBJS) $(SHAREDLIBVER) $(SHAREDLIB) $(STATICLIB) $(TARFILE) $(DLL) '$(DLLIMP)' '$(DLLDEF)'
|
||||
rm -f $(JAVAHEADERS) $(JAVACLASSES) $(JNILIB) example
|
||||
|
||||
distclean: clean
|
||||
rm -f config.mk
|
||||
rm -f imagequant.pc
|
||||
|
||||
install: all $(PKGCONFIG)
|
||||
install -d $(DESTDIR)$(LIBDIR)
|
||||
install -d $(DESTDIR)$(PKGCONFIGDIR)
|
||||
install -d $(DESTDIR)$(INCLUDEDIR)
|
||||
install -m 644 $(STATICLIB) $(DESTDIR)$(LIBDIR)/$(STATICLIB)
|
||||
install -m 644 $(SHAREDLIBVER) $(DESTDIR)$(LIBDIR)/$(SHAREDLIBVER)
|
||||
ln -sf $(SHAREDLIBVER) $(DESTDIR)$(LIBDIR)/$(SHAREDLIB)
|
||||
install -m 644 $(PKGCONFIG) $(DESTDIR)$(PKGCONFIGDIR)/$(PKGCONFIG)
|
||||
install -m 644 libimagequant.h $(DESTDIR)$(INCLUDEDIR)/libimagequant.h
|
||||
$(FIX_INSTALL_NAME)
|
||||
|
||||
uninstall:
|
||||
rm -f $(DESTDIR)$(LIBDIR)/$(STATICLIB)
|
||||
rm -f $(DESTDIR)$(LIBDIR)/$(SHAREDLIBVER)
|
||||
rm -f $(DESTDIR)$(LIBDIR)/$(SHAREDLIB)
|
||||
rm -f $(DESTDIR)$(PKGCONFIGDIR)/$(PKGCONFIG)
|
||||
rm -f $(DESTDIR)$(INCLUDEDIR)/libimagequant.h
|
||||
|
||||
config.mk:
|
||||
ifeq ($(filter %clean %distclean, $(MAKECMDGOALS)), )
|
||||
./configure
|
||||
endif
|
||||
|
||||
$(PKGCONFIG): config.mk
|
||||
sed 's|PREFIX|$(PREFIX)|;s|VERSION|$(VERSION)|' < imagequant.pc.in > $(PKGCONFIG)
|
||||
|
||||
.PHONY: all static shared clean dist distclean dll java cargo
|
||||
.DELETE_ON_ERROR:
|
679
CloverApp/libimagequant-2.12.6/README.md
Normal file
679
CloverApp/libimagequant-2.12.6/README.md
Normal file
@ -0,0 +1,679 @@
|
||||
# libimagequant—Image Quantization Library
|
||||
|
||||
Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images.
|
||||
It's powering [pngquant2](https://pngquant.org).
|
||||
|
||||
## License
|
||||
|
||||
Libimagequant is dual-licensed:
|
||||
|
||||
* For Free/Libre Open Source Software it's available under GPL v3 or later with additional [copyright notices](https://raw.github.com/ImageOptim/libimagequant/master/COPYRIGHT) for older parts of the code.
|
||||
* For use in closed-source software, AppStore distribution, and other non-GPL uses, you can [obtain a commercial license](https://supso.org/projects/pngquant). Feel free to ask kornel@pngquant.org for details and custom licensing terms if you need them.
|
||||
|
||||
## Download
|
||||
|
||||
The [library](https://pngquant.org/lib) is currently a part of the [pngquant2 project](https://pngquant.org). [Repository](https://github.com/ImageOptim/libimagequant).
|
||||
|
||||
## Compiling and Linking
|
||||
|
||||
The library can be linked with ANSI C, C++, [C#](https://github.com/ImageOptim/libimagequant/blob/master/libimagequant.cs), [Rust](https://github.com/pornel/libimagequant-rust), [Java](https://github.com/ImageOptim/libimagequant/tree/master/org/pngquant) and [Golang](https://github.com/larrabee/go-imagequant) programs. It has no external dependencies.
|
||||
|
||||
To build on Unix-like systems run:
|
||||
|
||||
make static
|
||||
|
||||
it will create `libimagequant.a` which you can link with your program.
|
||||
|
||||
gcc yourprogram.c /path/to/libimagequant.a
|
||||
|
||||
On BSD, use `gmake` (GNU make) rather than the native `make`.
|
||||
|
||||
Alternatively you can compile the library with your program simply by including all `.c` files (and define `NDEBUG` to get a fast version):
|
||||
|
||||
gcc -std=c99 -O3 -DNDEBUG libimagequant/*.c yourprogram.c
|
||||
|
||||
### Building for use in Rust programs
|
||||
|
||||
In [Rust](https://www.rust-lang.org/) you can use Cargo to build the library. Add [`imagequant`](https://crates.io/crates/imagequant) to dependencies of the Rust program. You can also use `cargo build` in [`imagequant-sys`](https://crates.io/crates/imagequant-sys) to build `libimagequant.a` for any C-compatible language.
|
||||
|
||||
### Building for Java JNI
|
||||
|
||||
To build Java JNI interface, ensure `JAVA_HOME` is set to your JDK directory, and run:
|
||||
|
||||
# export JAVA_HOME=$(locate include/jni.h) # you may need to set JAVA_HOME first
|
||||
make java
|
||||
|
||||
It will create `libimagequant.jnilib` and classes in `org/pngquant/`.
|
||||
|
||||
On Windows run `make java-dll` and it'll create `libimagequant.dll` instead.
|
||||
|
||||
### Compiling on Windows/Visual Studio
|
||||
|
||||
The library can be compiled with any C compiler that has at least basic support for C99 (GCC, clang, ICC, C++ Builder, even Tiny C Compiler), but Visual Studio 2012 and older are not up to date with the 1999 C standard. There are 2 options for using `libimagequant` on Windows:
|
||||
|
||||
* Use Visual Studio **2015** and an [MSVC-compatible branch of the library](https://github.com/ImageOptim/libimagequant/tree/msvc)
|
||||
* Or use GCC from [MinGW](http://www.mingw.org) or [MSYS2](http://www.msys2.org/). Use GCC to build `libimagequant.a` (using the instructions above for Unix) and add it along with `libgcc.a` (shipped with the MinGW compiler) to your VC project.
|
||||
|
||||
### Building as shared library
|
||||
|
||||
To build on Unix-like systems run:
|
||||
|
||||
./configure --prefix=/usr
|
||||
make libimagequant.so
|
||||
|
||||
To install on Unix-like systems run:
|
||||
|
||||
make install
|
||||
|
||||
|
||||
|
||||
## Overview
|
||||
|
||||
The basic flow is:
|
||||
|
||||
1. Create attributes object and configure the library.
|
||||
2. Create image object from RGBA pixels or data source.
|
||||
3. Perform quantization (generate palette).
|
||||
4. Store remapped image and final palette.
|
||||
5. Free memory.
|
||||
|
||||
Please note that libimagequant only handles raw uncompressed arrays of pixels in memory and is completely independent of any file format.
|
||||
|
||||
<p>
|
||||
/* See example.c for the full code! */
|
||||
|
||||
#include "libimagequant.h"
|
||||
|
||||
liq_attr *attr = liq_attr_create();
|
||||
liq_image *image = liq_image_create_rgba(attr, example_bitmap_rgba, width, height, 0);
|
||||
liq_result *res;
|
||||
liq_image_quantize(image, attr, &res);
|
||||
|
||||
liq_write_remapped_image(res, image, example_bitmap_8bpp, example_bitmap_size);
|
||||
const liq_palette *pal = liq_get_palette(res);
|
||||
|
||||
// Save the image and the palette now.
|
||||
for(int i=0; i < pal->count; i++) {
|
||||
example_copy_palette_entry(pal->entries[i]);
|
||||
}
|
||||
// You'll need a PNG library to write to a file.
|
||||
example_write_image(example_bitmap_8bpp);
|
||||
|
||||
liq_result_destroy(res);
|
||||
liq_image_destroy(image);
|
||||
liq_attr_destroy(attr);
|
||||
|
||||
Functions returning `liq_error` return `LIQ_OK` (`0`) on success and non-zero on error.
|
||||
|
||||
It's safe to pass `NULL` to any function accepting `liq_attr`, `liq_image`, `liq_result` (in that case the error code `LIQ_INVALID_POINTER` will be returned). These objects can be reused multiple times.
|
||||
|
||||
There are 3 ways to create image object for quantization:
|
||||
|
||||
* `liq_image_create_rgba()` for simple, contiguous RGBA pixel arrays (width×height×4 bytes large bitmap).
|
||||
* `liq_image_create_rgba_rows()` for non-contiguous RGBA pixel arrays (that have padding between rows or reverse order, e.g. BMP).
|
||||
* `liq_image_create_custom()` for RGB, ABGR, YUV and all other formats that can be converted on-the-fly to RGBA (you have to supply the conversion function).
|
||||
|
||||
Note that "image" here means raw uncompressed pixels. If you have a compressed image file, such as PNG, you must use another library (e.g. libpng or lodepng) to decode it first.
|
||||
|
||||
You'll find full example code in "example.c" file in the library source directory.
|
||||
|
||||
## Functions
|
||||
|
||||
----
|
||||
|
||||
liq_attr* liq_attr_create(void);
|
||||
|
||||
Returns object that will hold initial settings (attributes) for the library. The object should be freed using `liq_attr_destroy()` after it's no longer needed.
|
||||
|
||||
Returns `NULL` in the unlikely case that the library cannot run on the current machine (e.g. the library has been compiled for SSE-capable x86 CPU and run on VIA C3 CPU).
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_set_max_colors(liq_attr* attr, int colors);
|
||||
|
||||
Specifies maximum number of colors to use. The default is 256. Instead of setting a fixed limit it's better to use `liq_set_quality()`.
|
||||
|
||||
The first argument is attributes object from `liq_attr_create()`.
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if number of colors is outside the range 2-256.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_max_colors(liq_attr* attr);
|
||||
|
||||
Returns the value set by `liq_set_max_colors()`.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_set_quality(liq_attr* attr, int minimum, int maximum);
|
||||
|
||||
Quality is in range `0` (worst) to `100` (best) and values are analoguous to JPEG quality (i.e. `80` is usually good enough).
|
||||
|
||||
Quantization will attempt to use the lowest number of colors needed to achieve `maximum` quality. `maximum` value of `100` is the default and means conversion as good as possible.
|
||||
|
||||
If it's not possible to convert the image with at least `minimum` quality (i.e. 256 colors is not enough to meet the minimum quality), then `liq_image_quantize()` will fail. The default minimum is `0` (proceeds regardless of quality).
|
||||
|
||||
Quality measures how well the generated palette fits image given to `liq_image_quantize()`. If a different image is remapped with `liq_write_remapped_image()` then actual quality may be different.
|
||||
|
||||
Regardless of the quality settings the number of colors won't exceed the maximum (see `liq_set_max_colors()`).
|
||||
|
||||
The first argument is attributes object from `liq_attr_create()`.
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if target is lower than minimum or any of them is outside the 0-100 range.
|
||||
Returns `LIQ_INVALID_POINTER` if `attr` appears to be invalid.
|
||||
|
||||
liq_attr *attr = liq_attr_create();
|
||||
liq_set_quality(attr, 50, 80); // use quality 80 if possible. Give up if quality drops below 50.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_min_quality(liq_attr* attr);
|
||||
|
||||
Returns the lower bound set by `liq_set_quality()`.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_max_quality(liq_attr* attr);
|
||||
|
||||
Returns the upper bound set by `liq_set_quality()`.
|
||||
|
||||
----
|
||||
|
||||
liq_image *liq_image_create_rgba(liq_attr *attr, void* pixels, int width, int height, double gamma);
|
||||
|
||||
Creates an object that represents the image pixels to be used for quantization and remapping. The pixel array must be contiguous run of RGBA pixels (alpha is the last component, 0 = transparent, 255 = opaque).
|
||||
|
||||
The first argument is attributes object from `liq_attr_create()`. The same `attr` object should be used for the entire process, from creation of images to quantization.
|
||||
|
||||
The `pixels` array must not be modified or freed until this object is freed with `liq_image_destroy()`. See also `liq_image_set_memory_ownership()`.
|
||||
|
||||
`width` and `height` are dimensions in pixels. An image 10x10 pixel large will need a 400-byte array.
|
||||
|
||||
If the `gamma` argument is `0`, then the default of 1/2.2 [gamma](https://en.wikipedia.org/wiki/Gamma_correction) is assumed, which is good for most sRGB images.
|
||||
Otherwise `gamma` must be > 0 and < 1, e.g. `0.45455` (1/2.2) or `0.55555` (1/1.8). Generated palette will use the same gamma unless `liq_set_output_gamma()` is used. If `liq_set_output_gamma` is not used, then it only affects whether brighter or darker areas of the image will get more palette colors allocated.
|
||||
|
||||
Returns `NULL` on failure, e.g. if `pixels` is `NULL` or `width`/`height` is <= 0.
|
||||
|
||||
----
|
||||
|
||||
liq_image *liq_image_create_rgba_rows(liq_attr *attr, void* rows[], int width, int height, double gamma);
|
||||
|
||||
Same as `liq_image_create_rgba()`, but takes an array of pointers to rows of pixels. This allows defining images with reversed rows (like in BMP), "stride" different than width or using only fragment of a larger bitmap, etc.
|
||||
|
||||
The `rows` array must have at least `height` elements, and each row must be at least `width` RGBA pixels wide.
|
||||
|
||||
unsigned char *bitmap = …;
|
||||
void *rows = malloc(height * sizeof(void*));
|
||||
int bytes_per_row = width * 4 + padding; // stride
|
||||
for(int i=0; i < height; i++) {
|
||||
rows[i] = bitmap + i * bytes_per_row;
|
||||
}
|
||||
liq_image *img = liq_image_create_rgba_rows(attr, rows, width, height, 0);
|
||||
// …
|
||||
liq_image_destroy(img);
|
||||
free(rows);
|
||||
|
||||
The row pointers and pixels must not be modified or freed until this object is freed with `liq_image_destroy()` (you can change that with `liq_image_set_memory_ownership()`).
|
||||
|
||||
See also `liq_image_create_rgba()` and `liq_image_create_custom()`.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_image_quantize(liq_image *const input_image, liq_attr *const attr, liq_result **out_result);
|
||||
|
||||
Performs quantization (palette generation) based on settings in `attr` (from `liq_attr_create()`) and pixels of the image.
|
||||
|
||||
Returns `LIQ_OK` if quantization succeeds and sets `liq_result` pointer in `out_result`. The last argument is used for receiving the `result` object:
|
||||
|
||||
liq_result *result;
|
||||
if (LIQ_OK == liq_image_quantize(img, attr, &result)) { // Note &result
|
||||
// result pointer is valid here
|
||||
}
|
||||
|
||||
Returns `LIQ_QUALITY_TOO_LOW` if quantization fails due to limit set in `liq_set_quality()`.
|
||||
|
||||
See `liq_write_remapped_image()`.
|
||||
|
||||
If you want to generate one palette for multiple images at once, see `liq_histogram_create()`.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_set_dithering_level(liq_result *res, float dither_level);
|
||||
|
||||
Enables/disables dithering in `liq_write_remapped_image()`. Dithering level must be between `0` and `1` (inclusive). Dithering level `0` enables fast non-dithered remapping. Otherwise a variation of Floyd-Steinberg error diffusion is used.
|
||||
|
||||
Precision of the dithering algorithm depends on the speed setting, see `liq_set_speed()`.
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if the dithering level is outside the 0-1 range.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_write_remapped_image(liq_result *result, liq_image *input_image, void *buffer, size_t buffer_size);
|
||||
|
||||
Remaps the image to palette and writes its pixels to the given buffer, 1 pixel per byte.
|
||||
|
||||
The buffer must be large enough to fit the entire image, i.e. width×height bytes large. For safety, pass the size of the buffer as `buffer_size`.
|
||||
|
||||
For best performance call `liq_get_palette()` *after* this function, as palette is improved during remapping (except when `liq_histogram_quantize()` is used).
|
||||
|
||||
Returns `LIQ_BUFFER_TOO_SMALL` if given size of the buffer is not enough to fit the entire image.
|
||||
|
||||
int buffer_size = width*height;
|
||||
char *buffer = malloc(buffer_size);
|
||||
if (LIQ_OK == liq_write_remapped_image(result, input_image, buffer, buffer_size)) {
|
||||
liq_palette *pal = liq_get_palette(result);
|
||||
// save image
|
||||
}
|
||||
|
||||
See `liq_get_palette()`.
|
||||
|
||||
The buffer is assumed to be contiguous, with rows ordered from top to bottom, and no gaps between rows. If you need to write rows with padding or upside-down order, then use `liq_write_remapped_image_rows()`.
|
||||
|
||||
Please note that it only writes raw uncompressed pixels to memory. It does not perform any PNG compression. If you'd like to create a PNG file then you need to pass the raw pixel data to another library, e.g. libpng or lodepng. See `rwpng.c` in `pngquant` project for an example how to do that.
|
||||
|
||||
----
|
||||
|
||||
const liq_palette *liq_get_palette(liq_result *result);
|
||||
|
||||
Returns pointer to palette optimized for image that has been quantized or remapped (final refinements are applied to the palette during remapping).
|
||||
|
||||
It's valid to call this method before remapping, if you don't plan to remap any images or want to use same palette for multiple images.
|
||||
|
||||
`liq_palette->count` contains number of colors (up to 256), `liq_palette->entries[n]` contains RGBA value for nth palette color.
|
||||
|
||||
The palette is **temporary and read-only**. You must copy the palette elsewhere *before* calling `liq_result_destroy()`.
|
||||
|
||||
Returns `NULL` on error.
|
||||
|
||||
----
|
||||
|
||||
void liq_attr_destroy(liq_attr *);
|
||||
void liq_image_destroy(liq_image *);
|
||||
void liq_result_destroy(liq_result *);
|
||||
void liq_histogram_destroy(liq_histogram *);
|
||||
|
||||
Releases memory owned by the given object. Object must not be used any more after it has been freed.
|
||||
|
||||
Freeing `liq_result` also frees any `liq_palette` obtained from it.
|
||||
|
||||
## Advanced Functions
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_set_speed(liq_attr* attr, int speed);
|
||||
|
||||
Higher speed levels disable expensive algorithms and reduce quantization precision. The default speed is `4`. Speed `1` gives marginally better quality at significant CPU cost. Speed `10` has usually 5% lower quality, but is 8 times faster than the default.
|
||||
|
||||
High speeds combined with `liq_set_quality()` will use more colors than necessary and will be less likely to meet minimum required quality.
|
||||
|
||||
<table><caption>Features dependent on speed</caption>
|
||||
<tr><th>Noise-sensitive dithering</th><td>speed 1 to 5</td></tr>
|
||||
<tr><th>Forced posterization</th><td>8-10 or if image has more than million colors</td></tr>
|
||||
<tr><th>Quantization error known</th><td>1-7 or if minimum quality is set</td></tr>
|
||||
<tr><th>Additional quantization techniques</th><td>1-6</td></tr>
|
||||
</table>
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if the speed is outside the 1-10 range.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_speed(liq_attr* attr);
|
||||
|
||||
Returns the value set by `liq_set_speed()`.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_set_min_opacity(liq_attr* attr, int min);
|
||||
|
||||
Alpha values higher than this will be rounded to opaque. This is a workaround for Internet Explorer 6, but because this browser is not used any more, this option is deprecated and will be removed. The default is `255` (no change).
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if the value is outside the 0-255 range.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_min_opacity(liq_attr* attr);
|
||||
|
||||
Returns the value set by `liq_set_min_opacity()`.
|
||||
|
||||
----
|
||||
|
||||
liq_set_min_posterization(liq_attr* attr, int bits);
|
||||
|
||||
Ignores given number of least significant bits in all channels, posterizing image to `2^bits` levels. `0` gives full quality. Use `2` for VGA or 16-bit RGB565 displays, `4` if image is going to be output on a RGB444/RGBA4444 display (e.g. low-quality textures on Android).
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if the value is outside the 0-4 range.
|
||||
|
||||
----
|
||||
|
||||
int liq_get_min_posterization(liq_attr* attr);
|
||||
|
||||
Returns the value set by `liq_set_min_posterization()`.
|
||||
|
||||
----
|
||||
|
||||
liq_set_last_index_transparent(liq_attr* attr, int is_last);
|
||||
|
||||
`0` (default) makes alpha colors sorted before opaque colors. Non-`0` mixes colors together except completely transparent color, which is moved to the end of the palette. This is a workaround for programs that blindly assume the last palette entry is transparent.
|
||||
|
||||
----
|
||||
|
||||
liq_image *liq_image_create_custom(liq_attr *attr, liq_image_get_rgba_row_callback *row_callback, void *user_info, int width, int height, double gamma);
|
||||
|
||||
<p>
|
||||
|
||||
void image_get_rgba_row_callback(liq_color row_out[], int row_index, int width, void *user_info) {
|
||||
for(int column_index=0; column_index < width; column_index++) {
|
||||
row_out[column_index] = /* generate pixel at (row_index, column_index) */;
|
||||
}
|
||||
}
|
||||
|
||||
Creates image object that will use callback to read image data. This allows on-the-fly conversion of images that are not in the RGBA color space.
|
||||
|
||||
`user_info` value will be passed to the callback. It may be useful for storing pointer to program's internal representation of the image.
|
||||
|
||||
The callback must read/generate `row_index`-th row and write its RGBA pixels to the `row_out` array. Row `width` is given for convenience and will always equal to image width.
|
||||
|
||||
The callback will be called multiple times for each row. Quantization and remapping require at least two full passes over image data, so caching of callback's work makes no sense — in such case it's better to convert entire image and use `liq_image_create_rgba()` instead.
|
||||
|
||||
To use RGB image:
|
||||
|
||||
void rgb_to_rgba_callback(liq_color row_out[], int row_index, int width, void *user_info) {
|
||||
unsigned char *rgb_row = ((unsigned char *)user_info) + 3*width*row_index;
|
||||
|
||||
for(int i=0; i < width; i++) {
|
||||
row_out[i].r = rgb_row[i*3];
|
||||
row_out[i].g = rgb_row[i*3+1];
|
||||
row_out[i].b = rgb_row[i*3+2];
|
||||
row_out[i].a = 255;
|
||||
}
|
||||
}
|
||||
liq_image *img = liq_image_create_custom(attr, rgb_to_rgba_callback, rgb_bitmap, width, height, 0);
|
||||
|
||||
The library doesn't support RGB bitmaps "natively", because supporting only single format allows compiler to inline more code, 4-byte pixel alignment is faster, and SSE instructions operate on 4 values at once, so alpha support is almost free.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_image_set_memory_ownership(liq_image *image, int ownership_flags);
|
||||
|
||||
Passes ownership of image pixel data and/or its rows array to the `liq_image` object, so you don't have to free it yourself. Memory owned by the object will be freed at its discretion with `free` function specified in `liq_attr_create_with_allocator()` (by default it's stdlib's `free()`).
|
||||
|
||||
* `LIQ_OWN_PIXELS` makes pixel array owned by the object. The pixels will be freed automatically at any point when it's no longer needed. If you set this flag you must **not** free the pixel array yourself. If the image has been created with `liq_image_create_rgba_rows()` then the starting address of the array of pixels is assumed to be the lowest address of any row.
|
||||
|
||||
* `LIQ_OWN_ROWS` makes array of row pointers (but not the pixels pointed by these rows) owned by the object. Rows will be freed when object is deallocated. If you set this flag you must **not** free the rows array yourself. This flag is valid only if the object has been created with `liq_image_create_rgba_rows()`.
|
||||
|
||||
These flags can be combined with binary *or*, i.e. `LIQ_OWN_PIXELS | LIQ_OWN_ROWS`.
|
||||
|
||||
This function must not be used if the image has been created with `liq_image_create_custom()`.
|
||||
|
||||
Returns `LIQ_VALUE_OUT_OF_RANGE` if invalid flags are specified or the image object only takes pixels from a callback.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_image_set_background(liq_image *image, liq_image *background_image);
|
||||
|
||||
Analyze and remap this image with assumption that it will be always presented exactly on top of this background.
|
||||
|
||||
When this image is remapped to a palette with a fully transparent color (use `liq_image_add_fixed_color()` to ensure this) pixels that are better represented by the background than the palette will be made transparent. This function can be used to improve quality of animated GIFs by setting previous animation frame as the background.
|
||||
|
||||
This function takes full ownership of the background image, so you should **not** free the background object. It will be freed automatically together with the foreground image.
|
||||
|
||||
Returns `LIQ_BUFFER_TOO_SMALL` if the background image has a different size than the foreground.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_image_set_importance_map(liq_image *image, unsigned char map[], size_t buffer_size, liq_ownership ownership);
|
||||
|
||||
Impotance map controls which areas of the image get more palette colors. Pixels corresponding to 0 values in the map are completely ignored. The higher the value the more weight is placed on the given pixel, giving it higher chance of influencing the final palette.
|
||||
|
||||
The map is one byte per pixel and must have the same size as the image (width×height bytes). `buffer_size` argument is used to double-check that.
|
||||
|
||||
If the `ownership` is `LIQ_COPY_PIXELS` then the `map` content be copied immediately (it's up to you to ensure the `map` memory is freed).
|
||||
|
||||
If the `ownership` is `LIQ_OWN_PIXELS` then the `map` memory will be owned by the image and will be freed automatically when the image is freed. If a custom allocator has been set using `liq_attr_create_with_allocator()`, the `map` must be allocated using the same allocator.
|
||||
|
||||
Returns `LIQ_INVALID_POINTER` if any pointer is `NULL`, `LIQ_BUFFER_TOO_SMALL` if the `buffer_size` does not match the image size, and `LIQ_UNSUPPORTED` if `ownership` isn't a valid value.
|
||||
|
||||
----
|
||||
|
||||
liq_error liq_write_remapped_image_rows(liq_result *result, liq_image *input_image, unsigned char **row_pointers);
|
||||
|
||||
Similar to `liq_write_remapped_image()`. Writes remapped image, at 1 byte per pixel, to each row pointed by `row_pointers` array. The array must have at least as many elements as height of the image, and each row must have at least as many bytes as width of the image. Rows must not overlap.
|
||||
|
||||
For best performance call `liq_get_palette()` *after* this function, as remapping may change the palette (except when `liq_histogram_quantize()` is used).
|
||||
|
||||
Returns `LIQ_INVALID_POINTER` if `result` or `input_image` is `NULL`.
|
||||
|
||||
----
|
||||
|
||||
double liq_get_quantization_error(liq_result *result);
|
||||
|
||||
Returns mean square error of quantization (square of difference between pixel values in the source image and its remapped version). Alpha channel, gamma correction and approximate importance of pixels is taken into account, so the result isn't exactly the mean square error of all channels.
|
||||
|
||||
For most images MSE 1-5 is excellent. 7-10 is OK. 20-30 will have noticeable errors. 100 is awful.
|
||||
|
||||
This function may return `-1` if the value is not available (this happens when a high speed has been requested, the image hasn't been remapped yet, and quality limit hasn't been set, see `liq_set_speed()` and `liq_set_quality()`). The value is not updated when multiple images are remapped, it applies only to the image used in `liq_image_quantize()` or the first image that has been remapped. See `liq_get_remapping_error()`.
|
||||
|
||||
----
|
||||
|
||||
double liq_get_remapping_error(liq_result *result);
|
||||
|
||||
Returns mean square error of last remapping done (square of difference between pixel values in the remapped image and its remapped version). Alpha channel and gamma correction are taken into account, so the result isn't exactly the mean square error of all channels.
|
||||
|
||||
This function may return `-1` if the value is not available (this happens when a high speed has been requested or the image hasn't been remapped yet).
|
||||
|
||||
----
|
||||
|
||||
double liq_get_quantization_quality(liq_result *result);
|
||||
|
||||
Analoguous to `liq_get_quantization_error()`, but returns quantization error as quality value in the same 0-100 range that is used by `liq_set_quality()`.
|
||||
|
||||
It may return `-1` if the value is not available (see note in `liq_get_quantization_error()`).
|
||||
|
||||
This function can be used to add upper limit to quality options presented to the user, e.g.
|
||||
|
||||
liq_attr *attr = liq_attr_create();
|
||||
liq_image *img = liq_image_create_rgba(…);
|
||||
liq_result *res;
|
||||
liq_image_quantize(img, attr, &res);
|
||||
int max_attainable_quality = liq_get_quantization_quality(res);
|
||||
printf("Please select quality between 0 and %d: ", max_attainable_quality);
|
||||
int user_selected_quality = prompt();
|
||||
if (user_selected_quality < max_attainable_quality) {
|
||||
liq_set_quality(user_selected_quality, 0);
|
||||
liq_result_destroy(res);
|
||||
liq_image_quantize(img, attr, &res);
|
||||
}
|
||||
liq_write_remapped_image(…);
|
||||
|
||||
----
|
||||
|
||||
double liq_get_remapping_quality(liq_result *result);
|
||||
|
||||
Analoguous to `liq_get_remapping_error()`, but returns quantization error as quality value in the same 0-100 range that is used by `liq_set_quality()`.
|
||||
|
||||
----
|
||||
|
||||
void liq_set_log_callback(liq_attr*, liq_log_callback_function*, void *user_info);
|
||||
|
||||
<p>
|
||||
|
||||
void log_callback_function(const liq_attr*, const char *message, void *user_info) {}
|
||||
|
||||
----
|
||||
|
||||
void liq_set_log_flush_callback(liq_attr*, liq_log_flush_callback_function*, void *user_info);
|
||||
<p>
|
||||
|
||||
void log_flush_callback_function(const liq_attr*, void *user_info) {}
|
||||
|
||||
Sets up callback function to be called when the library reports status or errors. The callback must not call any library functions.
|
||||
|
||||
`user_info` value will be passed through to the callback. It can be `NULL`.
|
||||
|
||||
`NULL` callback clears the current callback.
|
||||
|
||||
In the log callback the `message` is a zero-terminated string containing informative message to output. It is valid only until the callback returns, so you must copy it.
|
||||
|
||||
`liq_set_log_flush_callback()` sets up callback function that will be called after the last log callback, which can be used to flush buffers and free resources used by the log callback.
|
||||
|
||||
----
|
||||
|
||||
void liq_set_progress_callback(liq_attr*, liq_progress_callback_function*, void *user_info);
|
||||
void liq_result_set_progress_callback(liq_result*, liq_progress_callback_function*, void *user_info);
|
||||
|
||||
<p>
|
||||
|
||||
int progress_callback_function(const liq_attr*, float progress_percent, void *user_info) {}
|
||||
|
||||
Sets up callback function to be called while the library is processing images. The callback may abort processing by returning `0`.
|
||||
|
||||
Setting callback to `NULL` clears the current callback. `liq_set_progress_callback` is for quantization progress, and `liq_result_set_progress_callback` is for remapping progress (currently only dithered remapping reports progress).
|
||||
|
||||
`user_info` value will be passed through to the callback. It can be `NULL`.
|
||||
|
||||
The callback must not call any library functions.
|
||||
|
||||
`progress_percent` is a value between 0 and 100 that estimates how much of the current task has been done.
|
||||
|
||||
The callback should return `1` to continue the operation, and `0` to abort current operation.
|
||||
|
||||
----
|
||||
|
||||
liq_attr* liq_attr_create_with_allocator(void* (*malloc)(size_t), void (*free)(void*));
|
||||
|
||||
Same as `liq_attr_create`, but uses given `malloc` and `free` replacements to allocate all memory used by the library.
|
||||
|
||||
The `malloc` function must return 16-byte aligned memory on x86 (and on other architectures memory aligned for `double` and pointers). Conversely, if your stdlib's `malloc` doesn't return appropriately aligned memory, you should use this function to provide aligned replacements.
|
||||
|
||||
----
|
||||
|
||||
liq_attr* liq_attr_copy(liq_attr *orig);
|
||||
|
||||
Creates an independent copy of `liq_attr`. The copy should also be freed using `liq_attr_destroy()`.
|
||||
|
||||
---
|
||||
|
||||
liq_error liq_set_output_gamma(liq_result* res, double gamma);
|
||||
|
||||
Sets gamma correction for generated palette and remapped image. Must be > 0 and < 1, e.g. `0.45455` for gamma 1/2.2 in PNG images. By default output gamma is same as gamma of the input image.
|
||||
|
||||
----
|
||||
|
||||
int liq_image_get_width(const liq_image *img);
|
||||
int liq_image_get_height(const liq_image *img);
|
||||
double liq_get_output_gamma(const liq_result *result);
|
||||
|
||||
Getters for `width`, `height` and `gamma` of the input image.
|
||||
|
||||
If the input is invalid, these all return -1.
|
||||
|
||||
---
|
||||
|
||||
liq_error liq_image_add_fixed_color(liq_image* img, liq_color color);
|
||||
liq_error liq_histogram_add_fixed_color(liq_histogram* hist, liq_color color, double gamma);
|
||||
|
||||
Reserves a color in the output palette created from this image. It behaves as if the given color was used in the image and was very important.
|
||||
|
||||
RGB values of `liq_color` are assumed to have the same gamma as the image. For the histogram function, the `gamma` can be `0` (see `liq_image_create_rgba()`).
|
||||
|
||||
It must be called before the image is quantized.
|
||||
|
||||
Returns error if more than 256 colors are added. If image is quantized to fewer colors than the number of fixed colors added, then excess fixed colors will be ignored.
|
||||
|
||||
For histograms see also a more flexible `liq_histogram_add_colors()`.
|
||||
|
||||
---
|
||||
|
||||
int liq_version();
|
||||
|
||||
Returns version of the library as an integer. Same as `LIQ_VERSION`. Human-readable version is defined as `LIQ_VERSION_STRING`.
|
||||
|
||||
## Multiple images with the same palette
|
||||
|
||||
It's possible to efficiently generate a single palette that is optimal for multiple images, e.g. for an APNG animation. This is done by collecting statistics of images in a `liq_histogram` object.
|
||||
|
||||
liq_attr *attr = liq_attr_create();
|
||||
liq_histogram *hist = liq_histogram_create(attr);
|
||||
|
||||
liq_image *image1 = liq_image_create_rgba(attr, example_bitmap_rgba1, width, height, 0);
|
||||
liq_histogram_add_image(hist, attr, image1);
|
||||
|
||||
liq_image *image2 = liq_image_create_rgba(attr, example_bitmap_rgba2, width, height, 0);
|
||||
liq_histogram_add_image(hist, attr, image2);
|
||||
|
||||
liq_result *result;
|
||||
liq_error err = liq_histogram_quantize(attr, hist, &result);
|
||||
if (LIQ_OK == err) {
|
||||
// result will contain shared palette best for both image1 and image2
|
||||
}
|
||||
|
||||
---
|
||||
|
||||
liq_histogram *liq_histogram_create(liq_attr *attr);
|
||||
|
||||
Creates histogram object that will be used to collect color statistics from multiple images. It must be freed using `liq_histogram_destroy()`.
|
||||
|
||||
All options should be set on `attr` before the histogram object is created. Options changed later may not have effect.
|
||||
|
||||
---
|
||||
|
||||
liq_error liq_histogram_add_image(liq_histogram *hist, liq_attr *attr, liq_image* image);
|
||||
|
||||
"Learns" colors from the image, which will be later used to generate the palette.
|
||||
|
||||
After the image is added to the histogram it may be freed to save memory (but it's more efficient to keep the image object if it's going to be used for remapping).
|
||||
|
||||
Fixed colors added to the image are also added to the histogram. If total number of fixed colors exceeds 256, this function will fail with `LIQ_BUFFER_TOO_SMALL`.
|
||||
|
||||
---
|
||||
|
||||
liq_error liq_histogram_add_colors(liq_histogram *hist, liq_attr *attr, liq_histogram_entry entries[], int num_entries, double gamma);
|
||||
|
||||
Alternative to `liq_histogram_add_image()`. Intead of counting colors in an image, it directly takes an array of colors and their counts (see `liq_histogram_entry` in `libimagequant.h`). This function is only useful if you already have a histogram of the image from another source.
|
||||
|
||||
For description of gamma, see `liq_image_create_rgba()`.
|
||||
|
||||
---
|
||||
|
||||
liq_error liq_histogram_quantize(liq_histogram *const hist, liq_attr *const attr, liq_result **out_result);
|
||||
|
||||
Generates palette from the histogram. On success returns `LIQ_OK` and writes `liq_result*` pointer to `out_result`. Use it as follows:
|
||||
|
||||
liq_result *result;
|
||||
liq_error err = liq_histogram_quantize(attr, hist, &result);
|
||||
if (LIQ_OK == err) {
|
||||
// Use result here to remap and get palette
|
||||
}
|
||||
|
||||
Returns `LIQ_QUALITY_TOO_LOW` if the palette is worse than limit set in `liq_set_quality()`. One histogram object can be quantized only once.
|
||||
|
||||
Palette generated using this function won't be improved during remapping. If you're generating palette for only one image, it's better to use `liq_image_quantize()`.
|
||||
|
||||
## Working with GIF
|
||||
|
||||
The library can generate palettes for GIF images. To ensure correct transparency is used you need to preprocess the image yourself and replace alpha values other than 0 or 255 with one of these.
|
||||
|
||||
For animated GIFs see `liq_image_set_background()` which remaps images for GIF's "keep" frame disposal method. See [gif.ski](https://gif.ski).
|
||||
|
||||
## Multithreading
|
||||
|
||||
The library is stateless and doesn't use any global or thread-local storage. It doesn't use any locks.
|
||||
|
||||
* Different threads can perform unrelated quantizations/remappings at the same time (e.g. each thread working on a different image).
|
||||
* The same `liq_attr`, `liq_result`, etc. can be accessed from different threads, but not at the same time (e.g. you can create `liq_attr` in one thread and free it in another).
|
||||
|
||||
The library needs to sort unique colors present in the image. Although the sorting algorithm does few things to make stack usage minimal in typical cases, there is no guarantee against extremely degenerate cases, so threads should have automatically growing stack.
|
||||
|
||||
### OpenMP
|
||||
|
||||
The library will parallelize some operations if compiled with OpenMP.
|
||||
|
||||
You must not increase number of maximum threads after `liq_image` has been created, as it allocates some per-thread buffers.
|
||||
|
||||
Callback of `liq_image_create_custom()` may be called from different threads at the same time.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
Thanks to Irfan Skiljan for helping test the first version of the library.
|
||||
|
||||
The library is developed by [Kornel Lesiński](mailto:%20kornel@pngquant.org).
|
132
CloverApp/libimagequant-2.12.6/blur.c
Normal file
132
CloverApp/libimagequant-2.12.6/blur.c
Normal file
@ -0,0 +1,132 @@
|
||||
/*
|
||||
© 2011-2015 by Kornel Lesiński.
|
||||
|
||||
This file is part of libimagequant.
|
||||
|
||||
libimagequant is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
libimagequant is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with libimagequant. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "pam.h"
|
||||
#include "blur.h"
|
||||
|
||||
/*
|
||||
Blurs image horizontally (width 2*size+1) and writes it transposed to dst (called twice gives 2d blur)
|
||||
*/
|
||||
static void transposing_1d_blur(unsigned char *restrict src, unsigned char *restrict dst, unsigned int width, unsigned int height, const unsigned int size)
|
||||
{
|
||||
assert(size > 0);
|
||||
|
||||
for(unsigned int j=0; j < height; j++) {
|
||||
unsigned char *restrict row = src + j*width;
|
||||
|
||||
// accumulate sum for pixels outside line
|
||||
unsigned int sum;
|
||||
sum = row[0]*size;
|
||||
for(unsigned int i=0; i < size; i++) {
|
||||
sum += row[i];
|
||||
}
|
||||
|
||||
// blur with left side outside line
|
||||
for(unsigned int i=0; i < size; i++) {
|
||||
sum -= row[0];
|
||||
sum += row[i+size];
|
||||
|
||||
dst[i*height + j] = sum / (size*2);
|
||||
}
|
||||
|
||||
for(unsigned int i=size; i < width-size; i++) {
|
||||
sum -= row[i-size];
|
||||
sum += row[i+size];
|
||||
|
||||
dst[i*height + j] = sum / (size*2);
|
||||
}
|
||||
|
||||
// blur with right side outside line
|
||||
for(unsigned int i=width-size; i < width; i++) {
|
||||
sum -= row[i-size];
|
||||
sum += row[width-1];
|
||||
|
||||
dst[i*height + j] = sum / (size*2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks maximum of neighboring pixels (blur + lighten)
|
||||
*/
|
||||
LIQ_PRIVATE void liq_max3(unsigned char *src, unsigned char *dst, unsigned int width, unsigned int height)
|
||||
{
|
||||
for(unsigned int j=0; j < height; j++) {
|
||||
const unsigned char *row = src + j*width,
|
||||
*prevrow = src + (j > 1 ? j-1 : 0)*width,
|
||||
*nextrow = src + MIN(height-1,j+1)*width;
|
||||
|
||||
unsigned char prev,curr=row[0],next=row[0];
|
||||
|
||||
for(unsigned int i=0; i < width-1; i++) {
|
||||
prev=curr;
|
||||
curr=next;
|
||||
next=row[i+1];
|
||||
|
||||
unsigned char t1 = MAX(prev,next);
|
||||
unsigned char t2 = MAX(nextrow[i],prevrow[i]);
|
||||
*dst++ = MAX(curr,MAX(t1,t2));
|
||||
}
|
||||
unsigned char t1 = MAX(curr,next);
|
||||
unsigned char t2 = MAX(nextrow[width-1],prevrow[width-1]);
|
||||
*dst++ = MAX(t1,t2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks minimum of neighboring pixels (blur + darken)
|
||||
*/
|
||||
LIQ_PRIVATE void liq_min3(unsigned char *src, unsigned char *dst, unsigned int width, unsigned int height)
|
||||
{
|
||||
for(unsigned int j=0; j < height; j++) {
|
||||
const unsigned char *row = src + j*width,
|
||||
*prevrow = src + (j > 1 ? j-1 : 0)*width,
|
||||
*nextrow = src + MIN(height-1,j+1)*width;
|
||||
|
||||
unsigned char prev,curr=row[0],next=row[0];
|
||||
|
||||
for(unsigned int i=0; i < width-1; i++) {
|
||||
prev=curr;
|
||||
curr=next;
|
||||
next=row[i+1];
|
||||
|
||||
unsigned char t1 = MIN(prev,next);
|
||||
unsigned char t2 = MIN(nextrow[i],prevrow[i]);
|
||||
*dst++ = MIN(curr,MIN(t1,t2));
|
||||
}
|
||||
unsigned char t1 = MIN(curr,next);
|
||||
unsigned char t2 = MIN(nextrow[width-1],prevrow[width-1]);
|
||||
*dst++ = MIN(t1,t2);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Filters src image and saves it to dst, overwriting tmp in the process.
|
||||
Image must be width*height pixels high. Size controls radius of box blur.
|
||||
*/
|
||||
LIQ_PRIVATE void liq_blur(unsigned char *src, unsigned char *tmp, unsigned char *dst, unsigned int width, unsigned int height, unsigned int size)
|
||||
{
|
||||
assert(size > 0);
|
||||
if (width < 2*size+1 || height < 2*size+1) {
|
||||
return;
|
||||
}
|
||||
transposing_1d_blur(src, tmp, width, height, size);
|
||||
transposing_1d_blur(tmp, dst, height, width, size);
|
||||
}
|
8
CloverApp/libimagequant-2.12.6/blur.h
Normal file
8
CloverApp/libimagequant-2.12.6/blur.h
Normal file
@ -0,0 +1,8 @@
|
||||
#ifndef BLUR_H
|
||||
#define BLUR_H
|
||||
|
||||
LIQ_PRIVATE void liq_blur(unsigned char *src, unsigned char *tmp, unsigned char *dst, unsigned int width, unsigned int height, unsigned int size);
|
||||
LIQ_PRIVATE void liq_max3(unsigned char *src, unsigned char *dst, unsigned int width, unsigned int height);
|
||||
LIQ_PRIVATE void liq_min3(unsigned char *src, unsigned char *dst, unsigned int width, unsigned int height);
|
||||
|
||||
#endif
|
276
CloverApp/libimagequant-2.12.6/configure
vendored
Executable file
276
CloverApp/libimagequant-2.12.6/configure
vendored
Executable file
@ -0,0 +1,276 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
CONFIG="config.mk"
|
||||
PREFIX="/usr/local"
|
||||
LIBDIR="$PREFIX/lib"
|
||||
INCLUDEDIR="$PREFIX/include"
|
||||
PKGCONFIGDIR="$LIBDIR/pkgconfig"
|
||||
VERSION=$(grep LIQ_VERSION_STRING libimagequant.h | grep -Eo "2\.[0-9.]+")
|
||||
|
||||
DEBUG=
|
||||
QUIET=0
|
||||
SSE=auto
|
||||
OPENMP=
|
||||
EXTRA_CFLAGS=
|
||||
EXTRA_LDFLAGS=
|
||||
|
||||
# make gcc default compiler unless CC is already set
|
||||
CC=${CC:-gcc}
|
||||
|
||||
help() {
|
||||
printf "%4s %s\n" "" "$1"
|
||||
}
|
||||
|
||||
for i in "$@"; do
|
||||
case $i in
|
||||
--help|-h)
|
||||
echo
|
||||
help "--prefix=<dir> installation directory [$PREFIX]"
|
||||
help "--libdir=<dir> installation directory [$LIBDIR]"
|
||||
help "--includedir=<dir> installation directory [$INCLUDEDIR]"
|
||||
help "--pkgconfigdir=<dir> installation directory [$PKGCONFIGDIR]"
|
||||
help "--extra-cflags=<flags> append to CFLAGS"
|
||||
help "--extra-ldflags=<flags> append to LDFLAGS"
|
||||
echo
|
||||
help "--enable-debug"
|
||||
help "--enable-sse/--disable-sse enable/disable SSE instructions"
|
||||
echo
|
||||
help "--with-openmp=static compile with multicore support"
|
||||
echo
|
||||
help "CC=<compiler> use given compiler command"
|
||||
help "CFLAGS=<flags> pass options to the compiler"
|
||||
help "LDFLAGS=<flags> pass options to the linker"
|
||||
echo
|
||||
exit 0
|
||||
;;
|
||||
# Can be set before or after configure. Latter overrides former.
|
||||
CC=*)
|
||||
CC=${i#*=}
|
||||
;;
|
||||
CFLAGS=*)
|
||||
CFLAGS=${i#*=}
|
||||
;;
|
||||
LDFLAGS=*)
|
||||
LDFLAGS=${i#*=}
|
||||
;;
|
||||
--enable-debug)
|
||||
DEBUG=1
|
||||
;;
|
||||
--enable-sse)
|
||||
SSE=1
|
||||
;;
|
||||
--disable-sse)
|
||||
SSE=0
|
||||
;;
|
||||
--quiet)
|
||||
QUIET=1
|
||||
;;
|
||||
'')
|
||||
# allows a bash quirk
|
||||
;;
|
||||
--with-openmp)
|
||||
OPENMP=1
|
||||
;;
|
||||
--with-openmp=static)
|
||||
OPENMP=static
|
||||
;;
|
||||
--prefix=*)
|
||||
PREFIX=${i#*=}
|
||||
LIBDIR="$PREFIX/lib"
|
||||
INCLUDEDIR="$PREFIX/include"
|
||||
PKGCONFIGDIR="$LIBDIR/pkgconfig"
|
||||
;;
|
||||
--libdir=*)
|
||||
LIBDIR=${i#*=}
|
||||
PKGCONFIGDIR="$LIBDIR/pkgconfig"
|
||||
;;
|
||||
--includedir=*)
|
||||
INCLUDEDIR=${i#*=}
|
||||
;;
|
||||
--pkgconfigdir=*)
|
||||
PKGCONFIGDIR=${i#*=}
|
||||
;;
|
||||
# can be used multiple times or in quotes to set multiple flags
|
||||
--extra-cflags=*)
|
||||
EXTRA_CFLAGS="$EXTRA_CFLAGS ${i#*=}"
|
||||
;;
|
||||
--extra-ldflags=*)
|
||||
EXTRA_LDFLAGS="$EXTRA_LDFLAGS ${i#*=}"
|
||||
;;
|
||||
*)
|
||||
echo "warning: unknown switch '${i%%=*}' (see $0 --help for the list)"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# If someone runs sudo make install as very first command, and configure later,
|
||||
# $CONFIG cannot be overwritten, and must be deleted before continuing.
|
||||
if [[ -f "$CONFIG" && ! -w "$CONFIG" ]]; then
|
||||
echo "Cannot overwrite file $CONFIG! Please delete it."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cflags() {
|
||||
CFLAGS="$CFLAGS $1"
|
||||
}
|
||||
|
||||
lflags() {
|
||||
LDFLAGS="$LDFLAGS $1"
|
||||
}
|
||||
|
||||
status() {
|
||||
if [ "$QUIET" -ne 1 ]; then
|
||||
printf "%10s: %s\n" "$1" "$2"
|
||||
fi
|
||||
}
|
||||
|
||||
# Append to CFLAGS if compiler supports flag, with optional prerequisite.
|
||||
# Fails on errors and warnings.
|
||||
conditional_cflags() {
|
||||
if [ -z "$(echo | "$CC" -xc -S -o /dev/null $2 $1 - 2>&1)" ]; then
|
||||
cflags "$1"
|
||||
fi
|
||||
}
|
||||
|
||||
error() {
|
||||
status "$1" "error ... $2"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [ "$QUIET" -ne 1 ]; then
|
||||
echo
|
||||
fi
|
||||
|
||||
echo > pngquant-gcccheck.c "int main(){}"
|
||||
if ! "$CC" -std=c99 -o pngquant-gcccheck pngquant-gcccheck.c; then
|
||||
rm -f pngquant-gcccheck pngquant-gcccheck.c
|
||||
error "Compiler" "$CC failed to compile anything (make sure it's installed and supports C99)"
|
||||
fi
|
||||
rm -f pngquant-gcccheck pngquant-gcccheck.c
|
||||
|
||||
status "Compiler" "$CC"
|
||||
|
||||
# init flags
|
||||
CFLAGS=${CFLAGS:--fno-math-errno -funroll-loops -fomit-frame-pointer -Wall}
|
||||
cflags "-std=c99 -I."
|
||||
|
||||
# DEBUG
|
||||
if [ -z "$DEBUG" ]; then
|
||||
cflags "-O3 -DNDEBUG"
|
||||
status "Debug" "no"
|
||||
else
|
||||
cflags "-O1 -g -DDEBUG"
|
||||
status "Debug" "yes"
|
||||
fi
|
||||
|
||||
# SSE
|
||||
if [ "$SSE" = 'auto' ]; then
|
||||
SSE=0
|
||||
if type uname > /dev/null; then
|
||||
if [[ "$(uname -m)" =~ "amd64" || "$(uname -m)" =~ "x86_64" ||
|
||||
"$(grep -E -m1 "^flags" /proc/cpuinfo)" =~ "sse" ]]; then
|
||||
SSE=1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$SSE" -eq 1 ]; then
|
||||
status "SSE" "yes"
|
||||
cflags "-DUSE_SSE=1"
|
||||
cflags "-msse"
|
||||
# Silence a later ICC warning due to -msse working slightly different.
|
||||
conditional_cflags "-wd10121"
|
||||
# Must be set explicitly for GCC on x86_32. Other compilers imply it.
|
||||
conditional_cflags "-mfpmath=sse" "-msse"
|
||||
elif [ "$SSE" -eq 0 ]; then
|
||||
status "SSE" "no"
|
||||
cflags "-DUSE_SSE=0"
|
||||
fi
|
||||
|
||||
# OpenMP
|
||||
if [ -n "$OPENMP" ]; then
|
||||
if [ "static" = "$OPENMP" ]; then
|
||||
OPENMPFLAGS="-static-libgcc -Bstatic -fopenmp -Bdynamic"
|
||||
else
|
||||
OPENMPFLAGS="-fopenmp"
|
||||
fi
|
||||
if [[ "$("$CC" -xc -E $OPENMPFLAGS <(echo "#ifdef _OPENMP
|
||||
#include <omp.h>
|
||||
#endif") 2>&1)" =~ "omp_get_thread_num" ]]; then
|
||||
cflags "$OPENMPFLAGS"
|
||||
lflags "$OPENMPFLAGS"
|
||||
status "OpenMP" "yes"
|
||||
else
|
||||
error "OpenMP" "not supported by compiler (please install a compiler that supports OpenMP (e.g. gcc) and specify it with the CC= argument)"
|
||||
fi
|
||||
else
|
||||
# silence warnings about omp pragmas
|
||||
cflags "-Wno-unknown-pragmas"
|
||||
conditional_cflags "-wd3180" # ICC
|
||||
status "OpenMP" "no"
|
||||
fi
|
||||
|
||||
# Cocoa
|
||||
if [[ "$OSTYPE" =~ "darwin" ]]; then
|
||||
cflags "-mmacosx-version-min=10.7"
|
||||
lflags "-mmacosx-version-min=10.7"
|
||||
fi
|
||||
|
||||
if [[ "$OSTYPE" =~ "darwin" ]]; then
|
||||
SOLIBSUFFIX=dylib
|
||||
|
||||
# Search Developer SDK paths, since Apple seems to have dropped the standard Unixy ones
|
||||
XCODE_CMD="xcode-select"
|
||||
XCODE_PATH=$($XCODE_CMD -p)
|
||||
DIRS+=("$XCODE_PATH/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include $XCODE_PATH/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/lib")
|
||||
DIRS+=("$XCODE_PATH/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/usr/include $XCODE_PATH/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/usr/lib")
|
||||
elif [[ "$OSTYPE" =~ "msys" ]]; then
|
||||
SOLIBSUFFIX=dll
|
||||
else
|
||||
SOLIBSUFFIX=so
|
||||
fi
|
||||
|
||||
if [ "$QUIET" -ne 1 ]; then
|
||||
echo
|
||||
fi
|
||||
|
||||
# As of GCC 4.5, 387 fp math is significantly slower in C99 mode without this.
|
||||
# Note: CPUs without SSE2 use 387 for doubles, even when SSE fp math is set.
|
||||
conditional_cflags "-fexcess-precision=fast"
|
||||
|
||||
# Intel C++ Compiler
|
||||
|
||||
# ICC does usually only produce fast(er) code when it can optimize to the full
|
||||
# capabilites of the (Intel) CPU. This is equivalent to -march=native for GCC.
|
||||
conditional_cflags "-xHOST"
|
||||
|
||||
# Disable unsafe fp optimizations and enforce fp precision as set in the source.
|
||||
conditional_cflags "-fp-model source"
|
||||
|
||||
# Silence a gold linker warning about string misalignment.
|
||||
conditional_cflags "-falign-stack=maintain-16-byte"
|
||||
|
||||
lflags "-lm" # Ubuntu requires this library last, issue #38
|
||||
|
||||
if [ -n "$EXTRA_CFLAGS" ]; then
|
||||
cflags "$EXTRA_CFLAGS"
|
||||
fi
|
||||
|
||||
if [ -n "$EXTRA_LDFLAGS" ]; then
|
||||
lflags "$EXTRA_LDFLAGS"
|
||||
fi
|
||||
|
||||
# Overwrite previous configuration.
|
||||
echo "
|
||||
# auto-generated by configure
|
||||
PREFIX = $PREFIX
|
||||
LIBDIR = $LIBDIR
|
||||
INCLUDEDIR = $INCLUDEDIR
|
||||
PKGCONFIGDIR = $PKGCONFIGDIR
|
||||
VERSION = $VERSION
|
||||
CC = $CC
|
||||
CFLAGS = $CFLAGS
|
||||
LDFLAGS = $LDFLAGS
|
||||
SOLIBSUFFIX = $SOLIBSUFFIX
|
||||
" > "$CONFIG"
|
115
CloverApp/libimagequant-2.12.6/example.c
Normal file
115
CloverApp/libimagequant-2.12.6/example.c
Normal file
@ -0,0 +1,115 @@
|
||||
/**
|
||||
|
||||
This is an example how to write your own simple pngquant using libimagequant.
|
||||
|
||||
libimagequant works with any PNG library. This example uses lodepng, because it's easier to use than libpng.
|
||||
|
||||
To run this example, run these commands in the library directory:
|
||||
|
||||
make example
|
||||
./example /path/to/some_file.png
|
||||
|
||||
On "manually":
|
||||
|
||||
1. Get lodepng.c (download lodepng.cpp and rename it) and lodepng.h
|
||||
from http://lodev.org/lodepng/ and put them in this directry
|
||||
|
||||
2. Compile libimagequant (see README.md)
|
||||
|
||||
3. Compile and run the example:
|
||||
|
||||
gcc -O3 example.c libimagequant.a -o example
|
||||
./example truecolor_file.png
|
||||
|
||||
|
||||
This example code can be freely copied under CC0 (public domain) license.
|
||||
*/
|
||||
|
||||
#include "lodepng.h" // Get it from https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.h
|
||||
#include "lodepng.c" // Get it from https://raw.githubusercontent.com/lvandeve/lodepng/master/lodepng.cpp and rename
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "libimagequant.h"
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc < 2) {
|
||||
fprintf(stderr, "Please specify a path to a PNG file\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
const char *input_png_file_path = argv[1];
|
||||
|
||||
// Load PNG file and decode it as raw RGBA pixels
|
||||
// This uses lodepng library for PNG reading (not part of libimagequant)
|
||||
|
||||
unsigned int width, height;
|
||||
unsigned char *raw_rgba_pixels;
|
||||
unsigned int status = lodepng_decode32_file(&raw_rgba_pixels, &width, &height, input_png_file_path);
|
||||
if (status) {
|
||||
fprintf(stderr, "Can't load %s: %s\n", input_png_file_path, lodepng_error_text(status));
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
// Use libimagequant to make a palette for the RGBA pixels
|
||||
|
||||
liq_attr *handle = liq_attr_create();
|
||||
liq_image *input_image = liq_image_create_rgba(handle, raw_rgba_pixels, width, height, 0);
|
||||
// You could set more options here, like liq_set_quality
|
||||
liq_result *quantization_result;
|
||||
if (liq_image_quantize(input_image, handle, &quantization_result) != LIQ_OK) {
|
||||
fprintf(stderr, "Quantization failed\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
// Use libimagequant to make new image pixels from the palette
|
||||
|
||||
size_t pixels_size = width * height;
|
||||
unsigned char *raw_8bit_pixels = malloc(pixels_size);
|
||||
liq_set_dithering_level(quantization_result, 1.0);
|
||||
|
||||
liq_write_remapped_image(quantization_result, input_image, raw_8bit_pixels, pixels_size);
|
||||
const liq_palette *palette = liq_get_palette(quantization_result);
|
||||
|
||||
// Save converted pixels as a PNG file
|
||||
// This uses lodepng library for PNG writing (not part of libimagequant)
|
||||
|
||||
LodePNGState state;
|
||||
lodepng_state_init(&state);
|
||||
state.info_raw.colortype = LCT_PALETTE;
|
||||
state.info_raw.bitdepth = 8;
|
||||
state.info_png.color.colortype = LCT_PALETTE;
|
||||
state.info_png.color.bitdepth = 8;
|
||||
|
||||
for(int i=0; i < palette->count; i++) {
|
||||
lodepng_palette_add(&state.info_png.color, palette->entries[i].r, palette->entries[i].g, palette->entries[i].b, palette->entries[i].a);
|
||||
lodepng_palette_add(&state.info_raw, palette->entries[i].r, palette->entries[i].g, palette->entries[i].b, palette->entries[i].a);
|
||||
}
|
||||
|
||||
unsigned char *output_file_data;
|
||||
size_t output_file_size;
|
||||
unsigned int out_status = lodepng_encode(&output_file_data, &output_file_size, raw_8bit_pixels, width, height, &state);
|
||||
if (out_status) {
|
||||
fprintf(stderr, "Can't encode image: %s\n", lodepng_error_text(out_status));
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
const char *output_png_file_path = "quantized_example.png";
|
||||
FILE *fp = fopen(output_png_file_path, "wb");
|
||||
if (!fp) {
|
||||
fprintf(stderr, "Unable to write to %s\n", output_png_file_path);
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
fwrite(output_file_data, 1, output_file_size, fp);
|
||||
fclose(fp);
|
||||
|
||||
printf("Written %s\n", output_png_file_path);
|
||||
|
||||
// Done. Free memory.
|
||||
|
||||
liq_result_destroy(quantization_result); // Must be freed only after you're done using the palette
|
||||
liq_image_destroy(input_image);
|
||||
liq_attr_destroy(handle);
|
||||
|
||||
free(raw_8bit_pixels);
|
||||
lodepng_state_cleanup(&state);
|
||||
}
|
10
CloverApp/libimagequant-2.12.6/imagequant.pc.in
Normal file
10
CloverApp/libimagequant-2.12.6/imagequant.pc.in
Normal file
@ -0,0 +1,10 @@
|
||||
prefix=PREFIX
|
||||
includedir=${prefix}/include
|
||||
libdir=${prefix}/lib
|
||||
|
||||
Name: imagequant
|
||||
Description: Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images.
|
||||
URL: https://pngquant.org/lib/
|
||||
Version: VERSION
|
||||
Libs: -L${libdir} -limagequant
|
||||
Cflags: -I${includedir}
|
98
CloverApp/libimagequant-2.12.6/kmeans.c
Normal file
98
CloverApp/libimagequant-2.12.6/kmeans.c
Normal file
@ -0,0 +1,98 @@
|
||||
/*
|
||||
** © 2011-2016 by Kornel Lesiński.
|
||||
** See COPYRIGHT file for license.
|
||||
*/
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "pam.h"
|
||||
#include "kmeans.h"
|
||||
#include "nearest.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#ifdef _OPENMP
|
||||
#include <omp.h>
|
||||
#else
|
||||
#define omp_get_max_threads() 1
|
||||
#define omp_get_thread_num() 0
|
||||
#endif
|
||||
|
||||
/*
|
||||
* K-Means iteration: new palette color is computed from weighted average of colors that map to that palette entry.
|
||||
*/
|
||||
LIQ_PRIVATE void kmeans_init(const colormap *map, const unsigned int max_threads, kmeans_state average_color[])
|
||||
{
|
||||
memset(average_color, 0, sizeof(average_color[0])*(KMEANS_CACHE_LINE_GAP+map->colors)*max_threads);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void kmeans_update_color(const f_pixel acolor, const float value, const colormap *map, unsigned int match, const unsigned int thread, kmeans_state average_color[])
|
||||
{
|
||||
match += thread * (KMEANS_CACHE_LINE_GAP+map->colors);
|
||||
average_color[match].a += acolor.a * value;
|
||||
average_color[match].r += acolor.r * value;
|
||||
average_color[match].g += acolor.g * value;
|
||||
average_color[match].b += acolor.b * value;
|
||||
average_color[match].total += value;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void kmeans_finalize(colormap *map, const unsigned int max_threads, const kmeans_state average_color[])
|
||||
{
|
||||
for (unsigned int i=0; i < map->colors; i++) {
|
||||
double a=0, r=0, g=0, b=0, total=0;
|
||||
|
||||
// Aggregate results from all threads
|
||||
for(unsigned int t=0; t < max_threads; t++) {
|
||||
const unsigned int offset = (KMEANS_CACHE_LINE_GAP+map->colors) * t + i;
|
||||
|
||||
a += average_color[offset].a;
|
||||
r += average_color[offset].r;
|
||||
g += average_color[offset].g;
|
||||
b += average_color[offset].b;
|
||||
total += average_color[offset].total;
|
||||
}
|
||||
|
||||
if (total && !map->palette[i].fixed) {
|
||||
map->palette[i].acolor = (f_pixel){
|
||||
.a = a / total,
|
||||
.r = r / total,
|
||||
.g = g / total,
|
||||
.b = b / total,
|
||||
};
|
||||
map->palette[i].popularity = total;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LIQ_PRIVATE double kmeans_do_iteration(histogram *hist, colormap *const map, kmeans_callback callback)
|
||||
{
|
||||
const unsigned int max_threads = omp_get_max_threads();
|
||||
LIQ_ARRAY(kmeans_state, average_color, (KMEANS_CACHE_LINE_GAP+map->colors) * max_threads);
|
||||
kmeans_init(map, max_threads, average_color);
|
||||
struct nearest_map *const n = nearest_init(map);
|
||||
hist_item *const achv = hist->achv;
|
||||
const int hist_size = hist->size;
|
||||
|
||||
double total_diff=0;
|
||||
#if __GNUC__ >= 9
|
||||
#pragma omp parallel for if (hist_size > 2000) \
|
||||
schedule(static) default(none) shared(achv,average_color,callback,hist_size,map,n) reduction(+:total_diff)
|
||||
#else
|
||||
#pragma omp parallel for if (hist_size > 2000) \
|
||||
schedule(static) default(none) shared(average_color,callback) reduction(+:total_diff)
|
||||
#endif
|
||||
for(int j=0; j < hist_size; j++) {
|
||||
float diff;
|
||||
unsigned int match = nearest_search(n, &achv[j].acolor, achv[j].tmp.likely_colormap_index, &diff);
|
||||
achv[j].tmp.likely_colormap_index = match;
|
||||
total_diff += diff * achv[j].perceptual_weight;
|
||||
|
||||
kmeans_update_color(achv[j].acolor, achv[j].perceptual_weight, map, match, omp_get_thread_num(), average_color);
|
||||
|
||||
if (callback) callback(&achv[j], diff);
|
||||
}
|
||||
|
||||
nearest_free(n);
|
||||
kmeans_finalize(map, max_threads, average_color);
|
||||
|
||||
return total_diff / hist->total_perceptual_weight;
|
||||
}
|
19
CloverApp/libimagequant-2.12.6/kmeans.h
Normal file
19
CloverApp/libimagequant-2.12.6/kmeans.h
Normal file
@ -0,0 +1,19 @@
|
||||
|
||||
#ifndef KMEANS_H
|
||||
#define KMEANS_H
|
||||
|
||||
// Spread memory touched by different threads at least 64B apart which I assume is the cache line size. This should avoid memory write contention.
|
||||
#define KMEANS_CACHE_LINE_GAP ((64+sizeof(kmeans_state)-1)/sizeof(kmeans_state))
|
||||
|
||||
typedef struct {
|
||||
double a, r, g, b, total;
|
||||
} kmeans_state;
|
||||
|
||||
typedef void (*kmeans_callback)(hist_item *item, float diff);
|
||||
|
||||
LIQ_PRIVATE void kmeans_init(const colormap *map, const unsigned int max_threads, kmeans_state state[]);
|
||||
LIQ_PRIVATE void kmeans_update_color(const f_pixel acolor, const float value, const colormap *map, unsigned int match, const unsigned int thread, kmeans_state average_color[]);
|
||||
LIQ_PRIVATE void kmeans_finalize(colormap *map, const unsigned int max_threads, const kmeans_state state[]);
|
||||
LIQ_PRIVATE double kmeans_do_iteration(histogram *hist, colormap *const map, kmeans_callback callback);
|
||||
|
||||
#endif
|
@ -0,0 +1,232 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 50;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
5F65D41723A04D7B003E3A5B /* nearest.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41023A04D7B003E3A5B /* nearest.c */; };
|
||||
5F65D41823A04D7B003E3A5B /* pam.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41123A04D7B003E3A5B /* pam.c */; };
|
||||
5F65D41923A04D7B003E3A5B /* mempool.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41223A04D7B003E3A5B /* mempool.c */; };
|
||||
5F65D41A23A04D7B003E3A5B /* mediancut.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41323A04D7B003E3A5B /* mediancut.c */; };
|
||||
5F65D41B23A04D7B003E3A5B /* kmeans.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41423A04D7B003E3A5B /* kmeans.c */; };
|
||||
5F65D41C23A04D7B003E3A5B /* libimagequant.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41523A04D7B003E3A5B /* libimagequant.c */; };
|
||||
5F65D41D23A04D7B003E3A5B /* blur.c in Sources */ = {isa = PBXBuildFile; fileRef = 5F65D41623A04D7B003E3A5B /* blur.c */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
5FB37C7723A04C7300942532 /* CopyFiles */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = "include/$(PRODUCT_NAME)";
|
||||
dstSubfolderSpec = 16;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
5F65D41023A04D7B003E3A5B /* nearest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = nearest.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41123A04D7B003E3A5B /* pam.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = pam.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41223A04D7B003E3A5B /* mempool.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mempool.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41323A04D7B003E3A5B /* mediancut.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mediancut.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41423A04D7B003E3A5B /* kmeans.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = kmeans.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41523A04D7B003E3A5B /* libimagequant.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = libimagequant.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41623A04D7B003E3A5B /* blur.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = blur.c; sourceTree = SOURCE_ROOT; };
|
||||
5F65D41E23A04D93003E3A5B /* libimagequant.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = libimagequant.h; sourceTree = SOURCE_ROOT; };
|
||||
5FB37C7923A04C7300942532 /* libimagequant.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libimagequant.a; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
5FB37C7623A04C7300942532 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
5FB37C7023A04C7300942532 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5FB37C7B23A04C7300942532 /* imagequant */,
|
||||
5FB37C7A23A04C7300942532 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5FB37C7A23A04C7300942532 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5FB37C7923A04C7300942532 /* libimagequant.a */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5FB37C7B23A04C7300942532 /* imagequant */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5F65D41E23A04D93003E3A5B /* libimagequant.h */,
|
||||
5F65D41623A04D7B003E3A5B /* blur.c */,
|
||||
5F65D41423A04D7B003E3A5B /* kmeans.c */,
|
||||
5F65D41523A04D7B003E3A5B /* libimagequant.c */,
|
||||
5F65D41323A04D7B003E3A5B /* mediancut.c */,
|
||||
5F65D41223A04D7B003E3A5B /* mempool.c */,
|
||||
5F65D41023A04D7B003E3A5B /* nearest.c */,
|
||||
5F65D41123A04D7B003E3A5B /* pam.c */,
|
||||
);
|
||||
path = imagequant;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
5FB37C7823A04C7300942532 /* imagequant */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 5FB37C8223A04C7300942532 /* Build configuration list for PBXNativeTarget "imagequant" */;
|
||||
buildPhases = (
|
||||
5FB37C7523A04C7300942532 /* Sources */,
|
||||
5FB37C7623A04C7300942532 /* Frameworks */,
|
||||
5FB37C7723A04C7300942532 /* CopyFiles */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = imagequant;
|
||||
productName = imagequant;
|
||||
productReference = 5FB37C7923A04C7300942532 /* libimagequant.a */;
|
||||
productType = "com.apple.product-type.library.static";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
5FB37C7123A04C7300942532 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastUpgradeCheck = 1120;
|
||||
ORGANIZATIONNAME = "ImageOptim Ltd.";
|
||||
TargetAttributes = {
|
||||
5FB37C7823A04C7300942532 = {
|
||||
CreatedOnToolsVersion = 11.2;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 5FB37C7423A04C7300942532 /* Build configuration list for PBXProject "libimagequant-ios" */;
|
||||
compatibilityVersion = "Xcode 9.3";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = 5FB37C7023A04C7300942532;
|
||||
productRefGroup = 5FB37C7A23A04C7300942532 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
5FB37C7823A04C7300942532 /* imagequant */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
5FB37C7523A04C7300942532 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5F65D41B23A04D7B003E3A5B /* kmeans.c in Sources */,
|
||||
5F65D41923A04D7B003E3A5B /* mempool.c in Sources */,
|
||||
5F65D41823A04D7B003E3A5B /* pam.c in Sources */,
|
||||
5F65D41C23A04D7B003E3A5B /* libimagequant.c in Sources */,
|
||||
5F65D41A23A04D7B003E3A5B /* mediancut.c in Sources */,
|
||||
5F65D41723A04D7B003E3A5B /* nearest.c in Sources */,
|
||||
5F65D41D23A04D7B003E3A5B /* blur.c in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
5FB37C8023A04C7300942532 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
5FB37C8123A04C7300942532 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = "NDEBUG=1";
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
|
||||
SDKROOT = iphoneos;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
5FB37C8323A04C7300942532 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
5FB37C8423A04C7300942532 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
5FB37C7423A04C7300942532 /* Build configuration list for PBXProject "libimagequant-ios" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
5FB37C8023A04C7300942532 /* Debug */,
|
||||
5FB37C8123A04C7300942532 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
5FB37C8223A04C7300942532 /* Build configuration list for PBXNativeTarget "imagequant" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
5FB37C8323A04C7300942532 /* Debug */,
|
||||
5FB37C8423A04C7300942532 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 5FB37C7123A04C7300942532 /* Project object */;
|
||||
}
|
@ -0,0 +1,223 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 50;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
5FF4F4CD23A04EF500A3FFB5 /* libimagequant.h in Headers */ = {isa = PBXBuildFile; fileRef = 5FF4F4C523A04EF500A3FFB5 /* libimagequant.h */; };
|
||||
5FF4F4CE23A04EF500A3FFB5 /* libimagequant.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4C623A04EF500A3FFB5 /* libimagequant.c */; };
|
||||
5FF4F4CF23A04EF500A3FFB5 /* kmeans.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4C723A04EF500A3FFB5 /* kmeans.c */; };
|
||||
5FF4F4D023A04EF500A3FFB5 /* blur.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4C823A04EF500A3FFB5 /* blur.c */; };
|
||||
5FF4F4D123A04EF500A3FFB5 /* mempool.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4C923A04EF500A3FFB5 /* mempool.c */; };
|
||||
5FF4F4D223A04EF500A3FFB5 /* nearest.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4CA23A04EF500A3FFB5 /* nearest.c */; };
|
||||
5FF4F4D323A04EF500A3FFB5 /* pam.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4CB23A04EF500A3FFB5 /* pam.c */; };
|
||||
5FF4F4D423A04EF500A3FFB5 /* mediancut.c in Sources */ = {isa = PBXBuildFile; fileRef = 5FF4F4CC23A04EF500A3FFB5 /* mediancut.c */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
5FF4F4BE23A04ED500A3FFB5 /* libimagequant.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libimagequant.a; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
5FF4F4C523A04EF500A3FFB5 /* libimagequant.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = libimagequant.h; path = ../../www/pngquant/lib/libimagequant.h; sourceTree = "<group>"; };
|
||||
5FF4F4C623A04EF500A3FFB5 /* libimagequant.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = libimagequant.c; path = ../../www/pngquant/lib/libimagequant.c; sourceTree = "<group>"; };
|
||||
5FF4F4C723A04EF500A3FFB5 /* kmeans.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = kmeans.c; path = ../../www/pngquant/lib/kmeans.c; sourceTree = "<group>"; };
|
||||
5FF4F4C823A04EF500A3FFB5 /* blur.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = blur.c; path = ../../www/pngquant/lib/blur.c; sourceTree = "<group>"; };
|
||||
5FF4F4C923A04EF500A3FFB5 /* mempool.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = mempool.c; path = ../../www/pngquant/lib/mempool.c; sourceTree = "<group>"; };
|
||||
5FF4F4CA23A04EF500A3FFB5 /* nearest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = nearest.c; path = ../../www/pngquant/lib/nearest.c; sourceTree = "<group>"; };
|
||||
5FF4F4CB23A04EF500A3FFB5 /* pam.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = pam.c; path = ../../www/pngquant/lib/pam.c; sourceTree = "<group>"; };
|
||||
5FF4F4CC23A04EF500A3FFB5 /* mediancut.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = mediancut.c; path = ../../www/pngquant/lib/mediancut.c; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
5FF4F4BC23A04ED500A3FFB5 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
5FF4F4B523A04ED500A3FFB5 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5FF4F4C823A04EF500A3FFB5 /* blur.c */,
|
||||
5FF4F4C723A04EF500A3FFB5 /* kmeans.c */,
|
||||
5FF4F4C623A04EF500A3FFB5 /* libimagequant.c */,
|
||||
5FF4F4C523A04EF500A3FFB5 /* libimagequant.h */,
|
||||
5FF4F4CC23A04EF500A3FFB5 /* mediancut.c */,
|
||||
5FF4F4C923A04EF500A3FFB5 /* mempool.c */,
|
||||
5FF4F4CA23A04EF500A3FFB5 /* nearest.c */,
|
||||
5FF4F4CB23A04EF500A3FFB5 /* pam.c */,
|
||||
5FF4F4BF23A04ED500A3FFB5 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5FF4F4BF23A04ED500A3FFB5 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5FF4F4BE23A04ED500A3FFB5 /* libimagequant.a */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXHeadersBuildPhase section */
|
||||
5FF4F4BA23A04ED500A3FFB5 /* Headers */ = {
|
||||
isa = PBXHeadersBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5FF4F4CD23A04EF500A3FFB5 /* libimagequant.h in Headers */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXHeadersBuildPhase section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
5FF4F4BD23A04ED500A3FFB5 /* imagequant */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 5FF4F4C223A04ED500A3FFB5 /* Build configuration list for PBXNativeTarget "imagequant" */;
|
||||
buildPhases = (
|
||||
5FF4F4BA23A04ED500A3FFB5 /* Headers */,
|
||||
5FF4F4BB23A04ED500A3FFB5 /* Sources */,
|
||||
5FF4F4BC23A04ED500A3FFB5 /* Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = imagequant;
|
||||
productName = imagequant;
|
||||
productReference = 5FF4F4BE23A04ED500A3FFB5 /* libimagequant.a */;
|
||||
productType = "com.apple.product-type.library.static";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
5FF4F4B623A04ED500A3FFB5 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastUpgradeCheck = 1120;
|
||||
ORGANIZATIONNAME = "ImageOptim Ltd.";
|
||||
TargetAttributes = {
|
||||
5FF4F4BD23A04ED500A3FFB5 = {
|
||||
CreatedOnToolsVersion = 11.2;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 5FF4F4B923A04ED500A3FFB5 /* Build configuration list for PBXProject "imagequant" */;
|
||||
compatibilityVersion = "Xcode 9.3";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = 5FF4F4B523A04ED500A3FFB5;
|
||||
productRefGroup = 5FF4F4BF23A04ED500A3FFB5 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
5FF4F4BD23A04ED500A3FFB5 /* imagequant */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
5FF4F4BB23A04ED500A3FFB5 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5FF4F4D323A04EF500A3FFB5 /* pam.c in Sources */,
|
||||
5FF4F4D023A04EF500A3FFB5 /* blur.c in Sources */,
|
||||
5FF4F4D223A04EF500A3FFB5 /* nearest.c in Sources */,
|
||||
5FF4F4CF23A04EF500A3FFB5 /* kmeans.c in Sources */,
|
||||
5FF4F4CE23A04EF500A3FFB5 /* libimagequant.c in Sources */,
|
||||
5FF4F4D423A04EF500A3FFB5 /* mediancut.c in Sources */,
|
||||
5FF4F4D123A04EF500A3FFB5 /* mempool.c in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
5FF4F4C023A04ED500A3FFB5 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = macosx;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
5FF4F4C123A04ED500A3FFB5 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu11;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = "NDEBUG=1";
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.9;
|
||||
SDKROOT = macosx;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
5FF4F4C323A04ED500A3FFB5 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
EXECUTABLE_PREFIX = lib;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
5FF4F4C423A04ED500A3FFB5 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
EXECUTABLE_PREFIX = lib;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SKIP_INSTALL = YES;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
5FF4F4B923A04ED500A3FFB5 /* Build configuration list for PBXProject "imagequant" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
5FF4F4C023A04ED500A3FFB5 /* Debug */,
|
||||
5FF4F4C123A04ED500A3FFB5 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
5FF4F4C223A04ED500A3FFB5 /* Build configuration list for PBXNativeTarget "imagequant" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
5FF4F4C323A04ED500A3FFB5 /* Debug */,
|
||||
5FF4F4C423A04ED500A3FFB5 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 5FF4F4B623A04ED500A3FFB5 /* Project object */;
|
||||
}
|
2166
CloverApp/libimagequant-2.12.6/libimagequant.c
Normal file
2166
CloverApp/libimagequant-2.12.6/libimagequant.c
Normal file
File diff suppressed because it is too large
Load Diff
164
CloverApp/libimagequant-2.12.6/libimagequant.cs
Normal file
164
CloverApp/libimagequant-2.12.6/libimagequant.cs
Normal file
@ -0,0 +1,164 @@
|
||||
/*
|
||||
This is an example demonstrating use of libimagequant from C#.
|
||||
|
||||
This example code can be freely copied under CC0 (public domain) license.
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct liq_color
|
||||
{
|
||||
public byte r, g, b, a;
|
||||
};
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct liq_palette
|
||||
{
|
||||
public int count;
|
||||
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
|
||||
public liq_color[] entries;
|
||||
};
|
||||
|
||||
enum liq_error
|
||||
{
|
||||
LIQ_OK = 0,
|
||||
LIQ_QUALITY_TOO_LOW = 99,
|
||||
LIQ_VALUE_OUT_OF_RANGE = 100,
|
||||
LIQ_OUT_OF_MEMORY,
|
||||
LIQ_ABORTED,
|
||||
LIQ_BITMAP_NOT_AVAILABLE,
|
||||
LIQ_BUFFER_TOO_SMALL,
|
||||
LIQ_INVALID_POINTER,
|
||||
};
|
||||
|
||||
namespace liq
|
||||
{
|
||||
using liq_attr_ptr = IntPtr;
|
||||
using liq_image_ptr = IntPtr;
|
||||
using liq_result_ptr = IntPtr;
|
||||
using size_t = UIntPtr;
|
||||
|
||||
class Liq
|
||||
{
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_attr_ptr liq_attr_create();
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_attr_ptr liq_attr_copy(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern void liq_attr_destroy(liq_attr_ptr attr);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_max_colors(liq_attr_ptr attr, int colors);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_max_colors(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_speed(liq_attr_ptr attr, int speed);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_speed(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_min_opacity(liq_attr_ptr attr, int min);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_min_opacity(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_min_posterization(liq_attr_ptr attr, int bits);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_min_posterization(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_quality(liq_attr_ptr attr, int minimum, int maximum);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_min_quality(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_max_quality(liq_attr_ptr attr);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern void liq_set_last_index_transparent(liq_attr_ptr attr, int is_last);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_image_ptr liq_image_create_rgba(liq_attr_ptr attr, [In, MarshalAs(UnmanagedType.LPArray)] byte[] bitmap, int width, int height, double gamma);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_image_set_memory_ownership(liq_image_ptr image, int ownership_flags);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_image_add_fixed_color(liq_image_ptr img, liq_color color);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_image_get_width(liq_image_ptr img);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_image_get_height(liq_image_ptr img);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern void liq_image_destroy(liq_image_ptr img);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_result_ptr liq_quantize_image(liq_attr_ptr attr, liq_image_ptr input_image);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_dithering_level(liq_result_ptr res, float dither_level);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_set_output_gamma(liq_result_ptr res, double gamma);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern double liq_get_output_gamma(liq_result_ptr res);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern IntPtr liq_get_palette(liq_result_ptr res);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern liq_error liq_write_remapped_image(liq_result_ptr res, liq_image_ptr input_image, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] buffer, size_t buffer_size);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern double liq_get_quantization_error(liq_result_ptr res);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_quantization_quality(liq_result_ptr res);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern double liq_get_remapping_error(liq_result_ptr res);
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_get_remapping_quality(liq_result_ptr res);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern void liq_result_destroy(liq_result_ptr res);
|
||||
|
||||
[DllImport(@"imagequant.dll")]
|
||||
public static extern int liq_version();
|
||||
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Console.WriteLine("library version: {0}", liq_version());
|
||||
|
||||
int width = 3;
|
||||
int height = 1;
|
||||
|
||||
var attr = liq_attr_create();
|
||||
if (attr == IntPtr.Zero) throw new Exception("can't create attr");
|
||||
|
||||
byte[] bitmap = { // R, G, B, A, R, G, B, A, ...
|
||||
111, 222, 33, 255,
|
||||
255, 0, 255, 255,
|
||||
255, 0, 255, 255,
|
||||
};
|
||||
var img = liq_image_create_rgba(attr, bitmap, width, height, 0);
|
||||
if (img == IntPtr.Zero) throw new Exception("can't create image");
|
||||
|
||||
var res = liq_quantize_image(attr, img);
|
||||
if (res == IntPtr.Zero) throw new Exception("can't quantize image");
|
||||
|
||||
var buffer_size = width * height;
|
||||
var remapped = new byte[buffer_size];
|
||||
|
||||
var err = liq_write_remapped_image(res, img, remapped, (UIntPtr)buffer_size);
|
||||
if (err != liq_error.LIQ_OK)
|
||||
{
|
||||
throw new Exception("remapping error");
|
||||
}
|
||||
|
||||
Console.WriteLine("first pixel is {0}th palette entry", remapped[0]);
|
||||
|
||||
liq_palette pal = (liq_palette)Marshal.PtrToStructure(liq_get_palette(res), typeof(liq_palette));
|
||||
|
||||
Console.WriteLine("palette entries: {0}; red of first entry: {1}", pal.count, pal.entries[0].r);
|
||||
|
||||
liq_image_destroy(img);
|
||||
liq_result_destroy(res);
|
||||
liq_attr_destroy(attr);
|
||||
}
|
||||
}
|
||||
}
|
151
CloverApp/libimagequant-2.12.6/libimagequant.h
Normal file
151
CloverApp/libimagequant-2.12.6/libimagequant.h
Normal file
@ -0,0 +1,151 @@
|
||||
/*
|
||||
* https://pngquant.org
|
||||
*/
|
||||
|
||||
#ifndef LIBIMAGEQUANT_H
|
||||
#define LIBIMAGEQUANT_H
|
||||
|
||||
#ifdef IMAGEQUANT_EXPORTS
|
||||
#define LIQ_EXPORT __declspec(dllexport)
|
||||
#endif
|
||||
|
||||
#ifndef LIQ_EXPORT
|
||||
#define LIQ_EXPORT extern
|
||||
#endif
|
||||
|
||||
#define LIQ_VERSION 21206
|
||||
#define LIQ_VERSION_STRING "2.12.6"
|
||||
|
||||
#ifndef LIQ_PRIVATE
|
||||
#if defined(__GNUC__) || defined (__llvm__)
|
||||
#define LIQ_PRIVATE __attribute__((visibility("hidden")))
|
||||
#define LIQ_NONNULL __attribute__((nonnull))
|
||||
#define LIQ_USERESULT __attribute__((warn_unused_result))
|
||||
#else
|
||||
#define LIQ_PRIVATE
|
||||
#define LIQ_NONNULL
|
||||
#define LIQ_USERESULT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
typedef struct liq_attr liq_attr;
|
||||
typedef struct liq_image liq_image;
|
||||
typedef struct liq_result liq_result;
|
||||
typedef struct liq_histogram liq_histogram;
|
||||
|
||||
typedef struct liq_color {
|
||||
unsigned char r, g, b, a;
|
||||
} liq_color;
|
||||
|
||||
typedef struct liq_palette {
|
||||
unsigned int count;
|
||||
liq_color entries[256];
|
||||
} liq_palette;
|
||||
|
||||
typedef enum liq_error {
|
||||
LIQ_OK = 0,
|
||||
LIQ_QUALITY_TOO_LOW = 99,
|
||||
LIQ_VALUE_OUT_OF_RANGE = 100,
|
||||
LIQ_OUT_OF_MEMORY,
|
||||
LIQ_ABORTED,
|
||||
LIQ_BITMAP_NOT_AVAILABLE,
|
||||
LIQ_BUFFER_TOO_SMALL,
|
||||
LIQ_INVALID_POINTER,
|
||||
LIQ_UNSUPPORTED,
|
||||
} liq_error;
|
||||
|
||||
enum liq_ownership {
|
||||
LIQ_OWN_ROWS=4,
|
||||
LIQ_OWN_PIXELS=8,
|
||||
LIQ_COPY_PIXELS=16,
|
||||
};
|
||||
|
||||
typedef struct liq_histogram_entry {
|
||||
liq_color color;
|
||||
unsigned int count;
|
||||
} liq_histogram_entry;
|
||||
|
||||
LIQ_EXPORT LIQ_USERESULT liq_attr* liq_attr_create(void);
|
||||
LIQ_EXPORT LIQ_USERESULT liq_attr* liq_attr_create_with_allocator(void* (*malloc)(size_t), void (*free)(void*));
|
||||
LIQ_EXPORT LIQ_USERESULT liq_attr* liq_attr_copy(const liq_attr *orig) LIQ_NONNULL;
|
||||
LIQ_EXPORT void liq_attr_destroy(liq_attr *attr) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT LIQ_USERESULT liq_histogram* liq_histogram_create(const liq_attr* attr);
|
||||
LIQ_EXPORT liq_error liq_histogram_add_image(liq_histogram *hist, const liq_attr *attr, liq_image* image) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_histogram_add_colors(liq_histogram *hist, const liq_attr *attr, const liq_histogram_entry entries[], int num_entries, double gamma) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_histogram_add_fixed_color(liq_histogram *hist, liq_color color, double gamma) LIQ_NONNULL;
|
||||
LIQ_EXPORT void liq_histogram_destroy(liq_histogram *hist) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT liq_error liq_set_max_colors(liq_attr* attr, int colors) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_max_colors(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_set_speed(liq_attr* attr, int speed) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_speed(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_set_min_opacity(liq_attr* attr, int min) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_min_opacity(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_set_min_posterization(liq_attr* attr, int bits) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_min_posterization(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_set_quality(liq_attr* attr, int minimum, int maximum) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_min_quality(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_get_max_quality(const liq_attr* attr) LIQ_NONNULL;
|
||||
LIQ_EXPORT void liq_set_last_index_transparent(liq_attr* attr, int is_last) LIQ_NONNULL;
|
||||
|
||||
typedef void liq_log_callback_function(const liq_attr*, const char *message, void* user_info);
|
||||
typedef void liq_log_flush_callback_function(const liq_attr*, void* user_info);
|
||||
LIQ_EXPORT void liq_set_log_callback(liq_attr*, liq_log_callback_function*, void* user_info);
|
||||
LIQ_EXPORT void liq_set_log_flush_callback(liq_attr*, liq_log_flush_callback_function*, void* user_info);
|
||||
|
||||
typedef int liq_progress_callback_function(float progress_percent, void* user_info);
|
||||
LIQ_EXPORT void liq_attr_set_progress_callback(liq_attr*, liq_progress_callback_function*, void* user_info);
|
||||
LIQ_EXPORT void liq_result_set_progress_callback(liq_result*, liq_progress_callback_function*, void* user_info);
|
||||
|
||||
// The rows and their data are not modified. The type of `rows` is non-const only due to a bug in C's typesystem design.
|
||||
LIQ_EXPORT LIQ_USERESULT liq_image *liq_image_create_rgba_rows(const liq_attr *attr, void *const rows[], int width, int height, double gamma) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT liq_image *liq_image_create_rgba(const liq_attr *attr, const void *bitmap, int width, int height, double gamma) LIQ_NONNULL;
|
||||
|
||||
typedef void liq_image_get_rgba_row_callback(liq_color row_out[], int row, int width, void* user_info);
|
||||
LIQ_EXPORT LIQ_USERESULT liq_image *liq_image_create_custom(const liq_attr *attr, liq_image_get_rgba_row_callback *row_callback, void* user_info, int width, int height, double gamma);
|
||||
|
||||
LIQ_EXPORT liq_error liq_image_set_memory_ownership(liq_image *image, int ownership_flags) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_image_set_background(liq_image *img, liq_image *background_image) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_image_set_importance_map(liq_image *img, unsigned char buffer[], size_t buffer_size, enum liq_ownership memory_handling) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_image_add_fixed_color(liq_image *img, liq_color color) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_image_get_width(const liq_image *img) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT int liq_image_get_height(const liq_image *img) LIQ_NONNULL;
|
||||
LIQ_EXPORT void liq_image_destroy(liq_image *img) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT LIQ_USERESULT liq_error liq_histogram_quantize(liq_histogram *const input_hist, liq_attr *const options, liq_result **result_output) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT liq_error liq_image_quantize(liq_image *const input_image, liq_attr *const options, liq_result **result_output) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT liq_error liq_set_dithering_level(liq_result *res, float dither_level) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_set_output_gamma(liq_result* res, double gamma) LIQ_NONNULL;
|
||||
LIQ_EXPORT LIQ_USERESULT double liq_get_output_gamma(const liq_result *result) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT LIQ_USERESULT const liq_palette *liq_get_palette(liq_result *result) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT liq_error liq_write_remapped_image(liq_result *result, liq_image *input_image, void *buffer, size_t buffer_size) LIQ_NONNULL;
|
||||
LIQ_EXPORT liq_error liq_write_remapped_image_rows(liq_result *result, liq_image *input_image, unsigned char **row_pointers) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT double liq_get_quantization_error(const liq_result *result) LIQ_NONNULL;
|
||||
LIQ_EXPORT int liq_get_quantization_quality(const liq_result *result) LIQ_NONNULL;
|
||||
LIQ_EXPORT double liq_get_remapping_error(const liq_result *result) LIQ_NONNULL;
|
||||
LIQ_EXPORT int liq_get_remapping_quality(const liq_result *result) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT void liq_result_destroy(liq_result *) LIQ_NONNULL;
|
||||
|
||||
LIQ_EXPORT int liq_version(void);
|
||||
|
||||
|
||||
// Deprecated
|
||||
LIQ_EXPORT LIQ_USERESULT liq_result *liq_quantize_image(liq_attr *options, liq_image *input_image) LIQ_NONNULL;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
464
CloverApp/libimagequant-2.12.6/mediancut.c
Normal file
464
CloverApp/libimagequant-2.12.6/mediancut.c
Normal file
@ -0,0 +1,464 @@
|
||||
/*
|
||||
** © 2009-2018 by Kornel Lesiński.
|
||||
** © 1989, 1991 by Jef Poskanzer.
|
||||
** © 1997, 2000, 2002 by Greg Roelofs; based on an idea by Stefan Schneider.
|
||||
**
|
||||
** See COPYRIGHT file for license.
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "pam.h"
|
||||
#include "mediancut.h"
|
||||
|
||||
#define index_of_channel(ch) (offsetof(f_pixel,ch)/sizeof(float))
|
||||
|
||||
static f_pixel averagepixels(unsigned int clrs, const hist_item achv[]);
|
||||
|
||||
struct box {
|
||||
f_pixel color;
|
||||
f_pixel variance;
|
||||
double sum, total_error, max_error;
|
||||
unsigned int ind;
|
||||
unsigned int colors;
|
||||
};
|
||||
|
||||
ALWAYS_INLINE static double variance_diff(double val, const double good_enough);
|
||||
inline static double variance_diff(double val, const double good_enough)
|
||||
{
|
||||
val *= val;
|
||||
if (val < good_enough*good_enough) return val*0.25;
|
||||
return val;
|
||||
}
|
||||
|
||||
/** Weighted per-channel variance of the box. It's used to decide which channel to split by */
|
||||
static f_pixel box_variance(const hist_item achv[], const struct box *box)
|
||||
{
|
||||
f_pixel mean = box->color;
|
||||
double variancea=0, variancer=0, varianceg=0, varianceb=0;
|
||||
|
||||
for(unsigned int i = 0; i < box->colors; ++i) {
|
||||
const f_pixel px = achv[box->ind + i].acolor;
|
||||
double weight = achv[box->ind + i].adjusted_weight;
|
||||
variancea += variance_diff(mean.a - px.a, 2.0/256.0)*weight;
|
||||
variancer += variance_diff(mean.r - px.r, 1.0/256.0)*weight;
|
||||
varianceg += variance_diff(mean.g - px.g, 1.0/256.0)*weight;
|
||||
varianceb += variance_diff(mean.b - px.b, 1.0/256.0)*weight;
|
||||
}
|
||||
|
||||
return (f_pixel){
|
||||
.a = variancea*(4.0/16.0),
|
||||
.r = variancer*(7.0/16.0),
|
||||
.g = varianceg*(9.0/16.0),
|
||||
.b = varianceb*(5.0/16.0),
|
||||
};
|
||||
}
|
||||
|
||||
static double box_max_error(const hist_item achv[], const struct box *box)
|
||||
{
|
||||
f_pixel mean = box->color;
|
||||
double max_error = 0;
|
||||
|
||||
for(unsigned int i = 0; i < box->colors; ++i) {
|
||||
const double diff = colordifference(mean, achv[box->ind + i].acolor);
|
||||
if (diff > max_error) {
|
||||
max_error = diff;
|
||||
}
|
||||
}
|
||||
return max_error;
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static double color_weight(f_pixel median, hist_item h);
|
||||
|
||||
static inline void hist_item_swap(hist_item *l, hist_item *r)
|
||||
{
|
||||
if (l != r) {
|
||||
hist_item t = *l;
|
||||
*l = *r;
|
||||
*r = t;
|
||||
}
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static unsigned int qsort_pivot(const hist_item *const base, const unsigned int len);
|
||||
inline static unsigned int qsort_pivot(const hist_item *const base, const unsigned int len)
|
||||
{
|
||||
if (len < 32) {
|
||||
return len/2;
|
||||
}
|
||||
|
||||
const unsigned int aidx=8, bidx=len/2, cidx=len-1;
|
||||
const unsigned int a=base[aidx].tmp.sort_value, b=base[bidx].tmp.sort_value, c=base[cidx].tmp.sort_value;
|
||||
return (a < b) ? ((b < c) ? bidx : ((a < c) ? cidx : aidx ))
|
||||
: ((b > c) ? bidx : ((a < c) ? aidx : cidx ));
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static unsigned int qsort_partition(hist_item *const base, const unsigned int len);
|
||||
inline static unsigned int qsort_partition(hist_item *const base, const unsigned int len)
|
||||
{
|
||||
unsigned int l = 1, r = len;
|
||||
if (len >= 8) {
|
||||
hist_item_swap(&base[0], &base[qsort_pivot(base,len)]);
|
||||
}
|
||||
|
||||
const unsigned int pivot_value = base[0].tmp.sort_value;
|
||||
while (l < r) {
|
||||
if (base[l].tmp.sort_value >= pivot_value) {
|
||||
l++;
|
||||
} else {
|
||||
while(l < --r && base[r].tmp.sort_value <= pivot_value) {}
|
||||
hist_item_swap(&base[l], &base[r]);
|
||||
}
|
||||
}
|
||||
l--;
|
||||
hist_item_swap(&base[0], &base[l]);
|
||||
|
||||
return l;
|
||||
}
|
||||
|
||||
/** quick select algorithm */
|
||||
static void hist_item_sort_range(hist_item base[], unsigned int len, unsigned int sort_start)
|
||||
{
|
||||
for(;;) {
|
||||
const unsigned int l = qsort_partition(base, len), r = l+1;
|
||||
|
||||
if (l > 0 && sort_start < l) {
|
||||
len = l;
|
||||
}
|
||||
else if (r < len && sort_start > r) {
|
||||
base += r; len -= r; sort_start -= r;
|
||||
}
|
||||
else break;
|
||||
}
|
||||
}
|
||||
|
||||
/** sorts array to make sum of weights lower than halfvar one side, returns edge between <halfvar and >halfvar parts of the set */
|
||||
static hist_item *hist_item_sort_halfvar(hist_item base[], unsigned int len, double *const lowervar, const double halfvar)
|
||||
{
|
||||
do {
|
||||
const unsigned int l = qsort_partition(base, len), r = l+1;
|
||||
|
||||
// check if sum of left side is smaller than half,
|
||||
// if it is, then it doesn't need to be sorted
|
||||
unsigned int t = 0; double tmpsum = *lowervar;
|
||||
while (t <= l && tmpsum < halfvar) tmpsum += base[t++].color_weight;
|
||||
|
||||
if (tmpsum < halfvar) {
|
||||
*lowervar = tmpsum;
|
||||
} else {
|
||||
if (l > 0) {
|
||||
hist_item *res = hist_item_sort_halfvar(base, l, lowervar, halfvar);
|
||||
if (res) return res;
|
||||
} else {
|
||||
// End of left recursion. This will be executed in order from the first element.
|
||||
*lowervar += base[0].color_weight;
|
||||
if (*lowervar > halfvar) return &base[0];
|
||||
}
|
||||
}
|
||||
|
||||
if (len > r) {
|
||||
base += r; len -= r; // tail-recursive "call"
|
||||
} else {
|
||||
*lowervar += base[r].color_weight;
|
||||
return (*lowervar > halfvar) ? &base[r] : NULL;
|
||||
}
|
||||
} while(1);
|
||||
}
|
||||
|
||||
static f_pixel get_median(const struct box *b, hist_item achv[]);
|
||||
|
||||
typedef struct {
|
||||
unsigned int chan; float variance;
|
||||
} channelvariance;
|
||||
|
||||
static int comparevariance(const void *ch1, const void *ch2)
|
||||
{
|
||||
return ((const channelvariance*)ch1)->variance > ((const channelvariance*)ch2)->variance ? -1 :
|
||||
(((const channelvariance*)ch1)->variance < ((const channelvariance*)ch2)->variance ? 1 : 0);
|
||||
}
|
||||
|
||||
/** Finds which channels need to be sorted first and preproceses achv for fast sort */
|
||||
static double prepare_sort(struct box *b, hist_item achv[])
|
||||
{
|
||||
/*
|
||||
** Sort dimensions by their variance, and then sort colors first by dimension with highest variance
|
||||
*/
|
||||
channelvariance channels[4] = {
|
||||
{index_of_channel(a), b->variance.a},
|
||||
{index_of_channel(r), b->variance.r},
|
||||
{index_of_channel(g), b->variance.g},
|
||||
{index_of_channel(b), b->variance.b},
|
||||
};
|
||||
|
||||
qsort(channels, 4, sizeof(channels[0]), comparevariance);
|
||||
|
||||
const unsigned int ind1 = b->ind;
|
||||
const unsigned int colors = b->colors;
|
||||
#if __GNUC__ >= 9
|
||||
#pragma omp parallel for if (colors > 25000) \
|
||||
schedule(static) default(none) shared(achv, channels, colors, ind1)
|
||||
#else
|
||||
#pragma omp parallel for if (colors > 25000) \
|
||||
schedule(static) default(none) shared(achv, channels)
|
||||
#endif
|
||||
for(unsigned int i=0; i < colors; i++) {
|
||||
const float *chans = (const float *)&achv[ind1 + i].acolor;
|
||||
// Only the first channel really matters. When trying median cut many times
|
||||
// with different histogram weights, I don't want sort randomness to influence outcome.
|
||||
achv[ind1 + i].tmp.sort_value = ((unsigned int)(chans[channels[0].chan]*65535.0)<<16) |
|
||||
(unsigned int)((chans[channels[2].chan] + chans[channels[1].chan]/2.0 + chans[channels[3].chan]/4.0)*65535.0);
|
||||
}
|
||||
|
||||
const f_pixel median = get_median(b, achv);
|
||||
|
||||
// box will be split to make color_weight of each side even
|
||||
const unsigned int ind = b->ind, end = ind+b->colors;
|
||||
double totalvar = 0;
|
||||
#pragma omp parallel for if (end - ind > 15000) \
|
||||
schedule(static) default(shared) reduction(+:totalvar)
|
||||
for(unsigned int j=ind; j < end; j++) totalvar += (achv[j].color_weight = color_weight(median, achv[j]));
|
||||
return totalvar / 2.0;
|
||||
}
|
||||
|
||||
/** finds median in unsorted set by sorting only minimum required */
|
||||
static f_pixel get_median(const struct box *b, hist_item achv[])
|
||||
{
|
||||
const unsigned int median_start = (b->colors-1)/2;
|
||||
|
||||
hist_item_sort_range(&(achv[b->ind]), b->colors,
|
||||
median_start);
|
||||
|
||||
if (b->colors&1) return achv[b->ind + median_start].acolor;
|
||||
|
||||
// technically the second color is not guaranteed to be sorted correctly
|
||||
// but most of the time it is good enough to be useful
|
||||
return averagepixels(2, &achv[b->ind + median_start]);
|
||||
}
|
||||
|
||||
/*
|
||||
** Find the best splittable box. -1 if no boxes are splittable.
|
||||
*/
|
||||
static int best_splittable_box(struct box bv[], unsigned int boxes, const double max_mse)
|
||||
{
|
||||
int bi=-1; double maxsum=0;
|
||||
for(unsigned int i=0; i < boxes; i++) {
|
||||
if (bv[i].colors < 2) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// looks only at max variance, because it's only going to split by it
|
||||
const double cv = MAX(bv[i].variance.r, MAX(bv[i].variance.g,bv[i].variance.b));
|
||||
double thissum = bv[i].sum * MAX(bv[i].variance.a, cv);
|
||||
|
||||
if (bv[i].max_error > max_mse) {
|
||||
thissum = thissum* bv[i].max_error/max_mse;
|
||||
}
|
||||
|
||||
if (thissum > maxsum) {
|
||||
maxsum = thissum;
|
||||
bi = i;
|
||||
}
|
||||
}
|
||||
return bi;
|
||||
}
|
||||
|
||||
inline static double color_weight(f_pixel median, hist_item h)
|
||||
{
|
||||
float diff = colordifference(median, h.acolor);
|
||||
return sqrt(diff) * (sqrt(1.0+h.adjusted_weight)-1.0);
|
||||
}
|
||||
|
||||
static void set_colormap_from_boxes(colormap *map, struct box bv[], unsigned int boxes, hist_item *achv);
|
||||
static void adjust_histogram(hist_item *achv, const struct box bv[], unsigned int boxes);
|
||||
|
||||
static double box_error(const struct box *box, const hist_item achv[])
|
||||
{
|
||||
f_pixel avg = box->color;
|
||||
|
||||
double total_error=0;
|
||||
for (unsigned int i = 0; i < box->colors; ++i) {
|
||||
total_error += colordifference(avg, achv[box->ind + i].acolor) * achv[box->ind + i].perceptual_weight;
|
||||
}
|
||||
|
||||
return total_error;
|
||||
}
|
||||
|
||||
|
||||
static bool total_box_error_below_target(double target_mse, struct box bv[], unsigned int boxes, const histogram *hist)
|
||||
{
|
||||
target_mse *= hist->total_perceptual_weight;
|
||||
double total_error=0;
|
||||
|
||||
for(unsigned int i=0; i < boxes; i++) {
|
||||
// error is (re)calculated lazily
|
||||
if (bv[i].total_error >= 0) {
|
||||
total_error += bv[i].total_error;
|
||||
}
|
||||
if (total_error > target_mse) return false;
|
||||
}
|
||||
|
||||
for(unsigned int i=0; i < boxes; i++) {
|
||||
if (bv[i].total_error < 0) {
|
||||
bv[i].total_error = box_error(&bv[i], hist->achv);
|
||||
total_error += bv[i].total_error;
|
||||
}
|
||||
if (total_error > target_mse) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static void box_init(struct box *box, const hist_item *achv, const unsigned int ind, const unsigned int colors, const double sum) {
|
||||
box->ind = ind;
|
||||
box->colors = colors;
|
||||
box->sum = sum;
|
||||
box->total_error = -1;
|
||||
|
||||
box->color = averagepixels(colors, &achv[ind]);
|
||||
box->variance = box_variance(achv, box);
|
||||
box->max_error = box_max_error(achv, box);
|
||||
}
|
||||
|
||||
/*
|
||||
** Here is the fun part, the median-cut colormap generator. This is based
|
||||
** on Paul Heckbert's paper, "Color Image Quantization for Frame Buffer
|
||||
** Display," SIGGRAPH 1982 Proceedings, page 297.
|
||||
*/
|
||||
LIQ_PRIVATE colormap *mediancut(histogram *hist, unsigned int newcolors, const double target_mse, const double max_mse, void* (*malloc)(size_t), void (*free)(void*))
|
||||
{
|
||||
hist_item *achv = hist->achv;
|
||||
LIQ_ARRAY(struct box, bv, newcolors);
|
||||
unsigned int boxes = 1;
|
||||
|
||||
/*
|
||||
** Set up the initial box.
|
||||
*/
|
||||
{
|
||||
double sum = 0;
|
||||
for(unsigned int i=0; i < hist->size; i++) {
|
||||
sum += achv[i].adjusted_weight;
|
||||
}
|
||||
box_init(&bv[0], achv, 0, hist->size, sum);
|
||||
|
||||
|
||||
/*
|
||||
** Main loop: split boxes until we have enough.
|
||||
*/
|
||||
while (boxes < newcolors) {
|
||||
|
||||
// first splits boxes that exceed quality limit (to have colors for things like odd green pixel),
|
||||
// later raises the limit to allow large smooth areas/gradients get colors.
|
||||
const double current_max_mse = max_mse + (boxes/(double)newcolors)*16.0*max_mse;
|
||||
const int bi = best_splittable_box(bv, boxes, current_max_mse);
|
||||
if (bi < 0) {
|
||||
break; /* ran out of colors! */
|
||||
}
|
||||
|
||||
unsigned int indx = bv[bi].ind;
|
||||
unsigned int clrs = bv[bi].colors;
|
||||
|
||||
/*
|
||||
Classic implementation tries to get even number of colors or pixels in each subdivision.
|
||||
|
||||
Here, instead of popularity I use (sqrt(popularity)*variance) metric.
|
||||
Each subdivision balances number of pixels (popular colors) and low variance -
|
||||
boxes can be large if they have similar colors. Later boxes with high variance
|
||||
will be more likely to be split.
|
||||
|
||||
Median used as expected value gives much better results than mean.
|
||||
*/
|
||||
|
||||
const double halfvar = prepare_sort(&bv[bi], achv);
|
||||
double lowervar=0;
|
||||
|
||||
// hist_item_sort_halfvar sorts and sums lowervar at the same time
|
||||
// returns item to break at …minus one, which does smell like an off-by-one error.
|
||||
hist_item *break_p = hist_item_sort_halfvar(&achv[indx], clrs, &lowervar, halfvar);
|
||||
unsigned int break_at = MIN(clrs-1, (unsigned int)(break_p - &achv[indx] + 1));
|
||||
|
||||
/*
|
||||
** Split the box.
|
||||
*/
|
||||
double sm = bv[bi].sum;
|
||||
double lowersum = 0;
|
||||
for(unsigned int i=0; i < break_at; i++) lowersum += achv[indx + i].adjusted_weight;
|
||||
|
||||
box_init(&bv[bi], achv, indx, break_at, lowersum);
|
||||
box_init(&bv[boxes], achv, indx + break_at, clrs - break_at, sm - lowersum);
|
||||
|
||||
++boxes;
|
||||
|
||||
if (total_box_error_below_target(target_mse, bv, boxes, hist)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
colormap *map = pam_colormap(boxes, malloc, free);
|
||||
set_colormap_from_boxes(map, bv, boxes, achv);
|
||||
|
||||
adjust_histogram(achv, bv, boxes);
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
static void set_colormap_from_boxes(colormap *map, struct box* bv, unsigned int boxes, hist_item *achv)
|
||||
{
|
||||
/*
|
||||
** Ok, we've got enough boxes. Now choose a representative color for
|
||||
** each box. There are a number of possible ways to make this choice.
|
||||
** One would be to choose the center of the box; this ignores any structure
|
||||
** within the boxes. Another method would be to average all the colors in
|
||||
** the box - this is the method specified in Heckbert's paper.
|
||||
*/
|
||||
|
||||
for(unsigned int bi = 0; bi < boxes; ++bi) {
|
||||
map->palette[bi].acolor = bv[bi].color;
|
||||
|
||||
/* store total color popularity (perceptual_weight is approximation of it) */
|
||||
map->palette[bi].popularity = 0;
|
||||
for(unsigned int i=bv[bi].ind; i < bv[bi].ind+bv[bi].colors; i++) {
|
||||
map->palette[bi].popularity += achv[i].perceptual_weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* increase histogram popularity by difference from the final color (this is used as part of feedback loop) */
|
||||
static void adjust_histogram(hist_item *achv, const struct box* bv, unsigned int boxes)
|
||||
{
|
||||
for(unsigned int bi = 0; bi < boxes; ++bi) {
|
||||
for(unsigned int i=bv[bi].ind; i < bv[bi].ind+bv[bi].colors; i++) {
|
||||
achv[i].tmp.likely_colormap_index = bi;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static f_pixel averagepixels(unsigned int clrs, const hist_item achv[])
|
||||
{
|
||||
double r = 0, g = 0, b = 0, a = 0, sum = 0;
|
||||
|
||||
#pragma omp parallel for if (clrs > 25000) \
|
||||
schedule(static) default(shared) reduction(+:a) reduction(+:r) reduction(+:g) reduction(+:b) reduction(+:sum)
|
||||
for(unsigned int i = 0; i < clrs; i++) {
|
||||
const f_pixel px = achv[i].acolor;
|
||||
const double weight = achv[i].adjusted_weight;
|
||||
|
||||
sum += weight;
|
||||
a += px.a * weight;
|
||||
r += px.r * weight;
|
||||
g += px.g * weight;
|
||||
b += px.b * weight;
|
||||
}
|
||||
|
||||
if (sum) {
|
||||
a /= sum;
|
||||
r /= sum;
|
||||
g /= sum;
|
||||
b /= sum;
|
||||
}
|
||||
|
||||
assert(!isnan(r) && !isnan(g) && !isnan(b) && !isnan(a));
|
||||
|
||||
return (f_pixel){.r=r, .g=g, .b=b, .a=a};
|
||||
}
|
6
CloverApp/libimagequant-2.12.6/mediancut.h
Normal file
6
CloverApp/libimagequant-2.12.6/mediancut.h
Normal file
@ -0,0 +1,6 @@
|
||||
#ifndef MEDIANCUT_H
|
||||
#define MEDIANCUT_H
|
||||
|
||||
LIQ_PRIVATE colormap *mediancut(histogram *hist, unsigned int newcolors, const double target_mse, const double max_mse, void* (*malloc)(size_t), void (*free)(void*));
|
||||
|
||||
#endif
|
70
CloverApp/libimagequant-2.12.6/mempool.c
Normal file
70
CloverApp/libimagequant-2.12.6/mempool.c
Normal file
@ -0,0 +1,70 @@
|
||||
/*
|
||||
** © 2009-2017 by Kornel Lesiński.
|
||||
** © 1989, 1991 by Jef Poskanzer.
|
||||
** © 1997, 2000, 2002 by Greg Roelofs; based on an idea by Stefan Schneider.
|
||||
**
|
||||
** See COPYRIGHT file for license.
|
||||
*/
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "mempool.h"
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include <assert.h>
|
||||
|
||||
#define ALIGN_MASK 15UL
|
||||
#define MEMPOOL_RESERVED ((sizeof(struct mempool)+ALIGN_MASK) & ~ALIGN_MASK)
|
||||
|
||||
struct mempool {
|
||||
unsigned int used, size;
|
||||
void* (*malloc)(size_t);
|
||||
void (*free)(void*);
|
||||
struct mempool *next;
|
||||
};
|
||||
LIQ_PRIVATE void* mempool_create(mempoolptr *mptr, const unsigned int size, unsigned int max_size, void* (*malloc)(size_t), void (*free)(void*))
|
||||
{
|
||||
if (*mptr && ((*mptr)->used+size) <= (*mptr)->size) {
|
||||
unsigned int prevused = (*mptr)->used;
|
||||
(*mptr)->used += (size+15UL) & ~0xFUL;
|
||||
return ((char*)(*mptr)) + prevused;
|
||||
}
|
||||
|
||||
mempoolptr old = *mptr;
|
||||
if (!max_size) max_size = (1<<17);
|
||||
max_size = size+ALIGN_MASK > max_size ? size+ALIGN_MASK : max_size;
|
||||
|
||||
*mptr = malloc(MEMPOOL_RESERVED + max_size);
|
||||
if (!*mptr) return NULL;
|
||||
**mptr = (struct mempool){
|
||||
.malloc = malloc,
|
||||
.free = free,
|
||||
.size = MEMPOOL_RESERVED + max_size,
|
||||
.used = sizeof(struct mempool),
|
||||
.next = old,
|
||||
};
|
||||
uintptr_t mptr_used_start = (uintptr_t)(*mptr) + (*mptr)->used;
|
||||
(*mptr)->used += (ALIGN_MASK + 1 - (mptr_used_start & ALIGN_MASK)) & ALIGN_MASK; // reserve bytes required to make subsequent allocations aligned
|
||||
assert(!(((uintptr_t)(*mptr) + (*mptr)->used) & ALIGN_MASK));
|
||||
|
||||
return mempool_alloc(mptr, size, size);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void* mempool_alloc(mempoolptr *mptr, const unsigned int size, const unsigned int max_size)
|
||||
{
|
||||
if (((*mptr)->used+size) <= (*mptr)->size) {
|
||||
unsigned int prevused = (*mptr)->used;
|
||||
(*mptr)->used += (size + ALIGN_MASK) & ~ALIGN_MASK;
|
||||
return ((char*)(*mptr)) + prevused;
|
||||
}
|
||||
|
||||
return mempool_create(mptr, size, max_size, (*mptr)->malloc, (*mptr)->free);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void mempool_destroy(mempoolptr m)
|
||||
{
|
||||
while (m) {
|
||||
mempoolptr next = m->next;
|
||||
m->free(m);
|
||||
m = next;
|
||||
}
|
||||
}
|
13
CloverApp/libimagequant-2.12.6/mempool.h
Normal file
13
CloverApp/libimagequant-2.12.6/mempool.h
Normal file
@ -0,0 +1,13 @@
|
||||
#ifndef MEMPOOL_H
|
||||
#define MEMPOOL_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
struct mempool;
|
||||
typedef struct mempool *mempoolptr;
|
||||
|
||||
LIQ_PRIVATE void* mempool_create(mempoolptr *mptr, const unsigned int size, unsigned int capacity, void* (*malloc)(size_t), void (*free)(void*));
|
||||
LIQ_PRIVATE void* mempool_alloc(mempoolptr *mptr, const unsigned int size, const unsigned int capacity);
|
||||
LIQ_PRIVATE void mempool_destroy(mempoolptr m);
|
||||
|
||||
#endif
|
195
CloverApp/libimagequant-2.12.6/nearest.c
Normal file
195
CloverApp/libimagequant-2.12.6/nearest.c
Normal file
@ -0,0 +1,195 @@
|
||||
/*
|
||||
** © 2009-2015 by Kornel Lesiński.
|
||||
** © 1989, 1991 by Jef Poskanzer.
|
||||
** © 1997, 2000, 2002 by Greg Roelofs; based on an idea by Stefan Schneider.
|
||||
**
|
||||
** See COPYRIGHT file for license.
|
||||
*/
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "pam.h"
|
||||
#include "nearest.h"
|
||||
#include "mempool.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct vp_sort_tmp {
|
||||
float distance_squared;
|
||||
unsigned int idx;
|
||||
} vp_sort_tmp;
|
||||
|
||||
typedef struct vp_search_tmp {
|
||||
float distance;
|
||||
unsigned int idx;
|
||||
int exclude;
|
||||
} vp_search_tmp;
|
||||
|
||||
typedef struct vp_node {
|
||||
struct vp_node *near, *far;
|
||||
f_pixel vantage_point;
|
||||
float radius;
|
||||
unsigned int idx;
|
||||
} vp_node;
|
||||
|
||||
struct nearest_map {
|
||||
vp_node *root;
|
||||
const colormap_item *palette;
|
||||
float nearest_other_color_dist[256];
|
||||
mempoolptr mempool;
|
||||
};
|
||||
|
||||
static void vp_search_node(const vp_node *node, const f_pixel *const needle, vp_search_tmp *const best_candidate);
|
||||
|
||||
static int vp_compare_distance(const void *ap, const void *bp) {
|
||||
float a = ((const vp_sort_tmp*)ap)->distance_squared;
|
||||
float b = ((const vp_sort_tmp*)bp)->distance_squared;
|
||||
return a > b ? 1 : -1;
|
||||
}
|
||||
|
||||
static void vp_sort_indexes_by_distance(const f_pixel vantage_point, vp_sort_tmp indexes[], int num_indexes, const colormap_item items[]) {
|
||||
for(int i=0; i < num_indexes; i++) {
|
||||
indexes[i].distance_squared = colordifference(vantage_point, items[indexes[i].idx].acolor);
|
||||
}
|
||||
qsort(indexes, num_indexes, sizeof(indexes[0]), vp_compare_distance);
|
||||
}
|
||||
|
||||
/*
|
||||
* Usually it should pick farthest point, but picking most popular point seems to make search quicker anyway
|
||||
*/
|
||||
static int vp_find_best_vantage_point_index(vp_sort_tmp indexes[], int num_indexes, const colormap_item items[]) {
|
||||
int best = 0;
|
||||
float best_popularity = items[indexes[0].idx].popularity;
|
||||
for(int i = 1; i < num_indexes; i++) {
|
||||
if (items[indexes[i].idx].popularity > best_popularity) {
|
||||
best_popularity = items[indexes[i].idx].popularity;
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
static vp_node *vp_create_node(mempoolptr *m, vp_sort_tmp indexes[], int num_indexes, const colormap_item items[]) {
|
||||
if (num_indexes <= 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
vp_node *node = mempool_alloc(m, sizeof(node[0]), 0);
|
||||
|
||||
if (num_indexes == 1) {
|
||||
*node = (vp_node){
|
||||
.vantage_point = items[indexes[0].idx].acolor,
|
||||
.idx = indexes[0].idx,
|
||||
.radius = MAX_DIFF,
|
||||
};
|
||||
return node;
|
||||
}
|
||||
|
||||
const int ref = vp_find_best_vantage_point_index(indexes, num_indexes, items);
|
||||
const int ref_idx = indexes[ref].idx;
|
||||
|
||||
// Removes the `ref_idx` item from remaining items, because it's included in the current node
|
||||
num_indexes -= 1;
|
||||
indexes[ref] = indexes[num_indexes];
|
||||
|
||||
vp_sort_indexes_by_distance(items[ref_idx].acolor, indexes, num_indexes, items);
|
||||
|
||||
// Remaining items are split by the median distance
|
||||
const int half_idx = num_indexes/2;
|
||||
|
||||
*node = (vp_node){
|
||||
.vantage_point = items[ref_idx].acolor,
|
||||
.idx = ref_idx,
|
||||
.radius = sqrtf(indexes[half_idx].distance_squared),
|
||||
};
|
||||
node->near = vp_create_node(m, indexes, half_idx, items);
|
||||
node->far = vp_create_node(m, &indexes[half_idx], num_indexes - half_idx, items);
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE struct nearest_map *nearest_init(const colormap *map) {
|
||||
mempoolptr m = NULL;
|
||||
struct nearest_map *handle = mempool_create(&m, sizeof(handle[0]), sizeof(handle[0]) + sizeof(vp_node)*map->colors+16, map->malloc, map->free);
|
||||
|
||||
LIQ_ARRAY(vp_sort_tmp, indexes, map->colors);
|
||||
|
||||
for(unsigned int i=0; i < map->colors; i++) {
|
||||
indexes[i].idx = i;
|
||||
}
|
||||
|
||||
vp_node *root = vp_create_node(&m, indexes, map->colors, map->palette);
|
||||
*handle = (struct nearest_map){
|
||||
.root = root,
|
||||
.palette = map->palette,
|
||||
.mempool = m,
|
||||
};
|
||||
|
||||
for(unsigned int i=0; i < map->colors; i++) {
|
||||
vp_search_tmp best = {
|
||||
.distance = MAX_DIFF,
|
||||
.exclude = i,
|
||||
};
|
||||
vp_search_node(root, &map->palette[i].acolor, &best);
|
||||
handle->nearest_other_color_dist[i] = best.distance * best.distance / 4.0; // half of squared distance
|
||||
}
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
static void vp_search_node(const vp_node *node, const f_pixel *const needle, vp_search_tmp *const best_candidate) {
|
||||
do {
|
||||
const float distance = sqrtf(colordifference(node->vantage_point, *needle));
|
||||
|
||||
if (distance < best_candidate->distance && best_candidate->exclude != node->idx) {
|
||||
best_candidate->distance = distance;
|
||||
best_candidate->idx = node->idx;
|
||||
}
|
||||
|
||||
// Recurse towards most likely candidate first to narrow best candidate's distance as soon as possible
|
||||
if (distance < node->radius) {
|
||||
if (node->near) {
|
||||
vp_search_node(node->near, needle, best_candidate);
|
||||
}
|
||||
// The best node (final answer) may be just ouside the radius, but not farther than
|
||||
// the best distance we know so far. The vp_search_node above should have narrowed
|
||||
// best_candidate->distance, so this path is rarely taken.
|
||||
if (node->far && distance >= node->radius - best_candidate->distance) {
|
||||
node = node->far; // Fast tail recursion
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (node->far) {
|
||||
vp_search_node(node->far, needle, best_candidate);
|
||||
}
|
||||
if (node->near && distance <= node->radius + best_candidate->distance) {
|
||||
node = node->near; // Fast tail recursion
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} while(true);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE unsigned int nearest_search(const struct nearest_map *handle, const f_pixel *px, const int likely_colormap_index, float *diff) {
|
||||
const float guess_diff = colordifference(handle->palette[likely_colormap_index].acolor, *px);
|
||||
if (guess_diff < handle->nearest_other_color_dist[likely_colormap_index]) {
|
||||
if (diff) *diff = guess_diff;
|
||||
return likely_colormap_index;
|
||||
}
|
||||
|
||||
vp_search_tmp best_candidate = {
|
||||
.distance = sqrtf(guess_diff),
|
||||
.idx = likely_colormap_index,
|
||||
.exclude = -1,
|
||||
};
|
||||
vp_search_node(handle->root, px, &best_candidate);
|
||||
if (diff) {
|
||||
*diff = best_candidate.distance * best_candidate.distance;
|
||||
}
|
||||
return best_candidate.idx;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void nearest_free(struct nearest_map *centroids)
|
||||
{
|
||||
mempool_destroy(centroids->mempool);
|
||||
}
|
14
CloverApp/libimagequant-2.12.6/nearest.h
Normal file
14
CloverApp/libimagequant-2.12.6/nearest.h
Normal file
@ -0,0 +1,14 @@
|
||||
//
|
||||
// nearest.h
|
||||
// pngquant
|
||||
//
|
||||
|
||||
#ifndef NEAREST_H
|
||||
#define NEAREST_H
|
||||
|
||||
struct nearest_map;
|
||||
LIQ_PRIVATE struct nearest_map *nearest_init(const colormap *palette);
|
||||
LIQ_PRIVATE unsigned int nearest_search(const struct nearest_map *map, const f_pixel *px, const int palette_index_guess, float *diff);
|
||||
LIQ_PRIVATE void nearest_free(struct nearest_map *map);
|
||||
|
||||
#endif
|
74
CloverApp/libimagequant-2.12.6/org/pngquant/Image.java
Normal file
74
CloverApp/libimagequant-2.12.6/org/pngquant/Image.java
Normal file
@ -0,0 +1,74 @@
|
||||
package org.pngquant;
|
||||
|
||||
import org.pngquant.*;
|
||||
import java.awt.image.*;
|
||||
|
||||
/**
|
||||
* PngQuant's representation of an Image constructed from BufferedImage.
|
||||
*/
|
||||
public class Image extends LiqObject {
|
||||
|
||||
/**
|
||||
* Converts BufferedImage to internal representation (pixel data is copied).
|
||||
* It's best to use BufferedImage in RGB/RGBA format backed by DataBufferByte.
|
||||
* Throws if conversion fails.
|
||||
*/
|
||||
public Image(BufferedImage image) throws PngQuantException {
|
||||
this(new PngQuant(), image);
|
||||
}
|
||||
|
||||
public Image(PngQuant attr, BufferedImage image) throws PngQuantException {
|
||||
handle = handleFromImage(attr, image);
|
||||
|
||||
if (handle == 0) {
|
||||
BufferedImage converted = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
|
||||
converted.getGraphics().drawImage(image, 0, 0, null);
|
||||
handle = handleFromImage(attr, converted);
|
||||
|
||||
if (handle == 0) {
|
||||
throw new PngQuantException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarantees presence of the given color in the palette (subject to setMaxColors())
|
||||
* if this image is used for quantization.
|
||||
*/
|
||||
public native boolean addFixedColor(int r, int g, int b, int a);
|
||||
public boolean addFixedColor(int r, int g, int b) {
|
||||
return addFixedColor(r, g, b, 255);
|
||||
}
|
||||
public native int getWidth();
|
||||
public native int getHeight();
|
||||
|
||||
public void close() {
|
||||
if (handle != 0) {
|
||||
liq_image_destroy(handle);
|
||||
handle = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static long handleFromImage(PngQuant attr, BufferedImage image) {
|
||||
// The JNI wrapper will accept non-premultiplied ABGR and BGR only.
|
||||
int type = image.getType();
|
||||
if (type != BufferedImage.TYPE_3BYTE_BGR &&
|
||||
type != BufferedImage.TYPE_4BYTE_ABGR &&
|
||||
type != BufferedImage.TYPE_4BYTE_ABGR_PRE) return 0;
|
||||
|
||||
WritableRaster raster = image.getRaster();
|
||||
ColorModel color = image.getColorModel();
|
||||
if (type == BufferedImage.TYPE_4BYTE_ABGR_PRE) color.coerceData(raster, false);
|
||||
|
||||
DataBuffer buffer = raster.getDataBuffer();
|
||||
if (buffer instanceof DataBufferByte) {
|
||||
byte[] imageData = ((DataBufferByte)buffer).getData();
|
||||
return liq_image_create(attr.handle, imageData,
|
||||
raster.getWidth(), raster.getHeight(), color.getNumComponents());
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static native long liq_image_create(long attr, byte[] bitmap, int width, int height, int components);
|
||||
private static native void liq_image_destroy(long handle);
|
||||
}
|
19
CloverApp/libimagequant-2.12.6/org/pngquant/LiqObject.java
Normal file
19
CloverApp/libimagequant-2.12.6/org/pngquant/LiqObject.java
Normal file
@ -0,0 +1,19 @@
|
||||
package org.pngquant;
|
||||
|
||||
abstract class LiqObject {
|
||||
static {
|
||||
// libimagequant.jnilib or libimagequant.so must be in java.library.path
|
||||
System.loadLibrary("imagequant");
|
||||
}
|
||||
|
||||
long handle;
|
||||
|
||||
/**
|
||||
* Free memory used by the library. The object must not be used after this call.
|
||||
*/
|
||||
abstract public void close();
|
||||
|
||||
protected void finalize() throws Throwable {
|
||||
close();
|
||||
}
|
||||
}
|
156
CloverApp/libimagequant-2.12.6/org/pngquant/PngQuant.c
Normal file
156
CloverApp/libimagequant-2.12.6/org/pngquant/PngQuant.c
Normal file
@ -0,0 +1,156 @@
|
||||
#include "org/pngquant/PngQuant.h"
|
||||
#include "org/pngquant/Image.h"
|
||||
#include "org/pngquant/Result.h"
|
||||
#include "libimagequant.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct {
|
||||
liq_image *image;
|
||||
jbyte *data;
|
||||
} liq_jni_image;
|
||||
|
||||
static void *handle(JNIEnv *env, jobject obj) {
|
||||
jlong h = (*env)->GetLongField(env, obj, (*env)->GetFieldID(env, (*env)->GetObjectClass(env, obj), "handle", "J"));
|
||||
return (void*)h;
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_org_pngquant_PngQuant_liq_1attr_1create(JNIEnv *env, jclass class) {
|
||||
return (jlong)liq_attr_create();
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_org_pngquant_PngQuant_liq_1attr_1copy(JNIEnv *env, jclass class, jlong attr) {
|
||||
return (jlong)liq_attr_copy((liq_attr*)attr);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_pngquant_PngQuant_liq_1attr_1destroy(JNIEnv *env, jclass class, jlong attr) {
|
||||
return liq_attr_destroy((liq_attr*)attr);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setMaxColors(JNIEnv *env, jobject obj, jint colors) {
|
||||
return LIQ_OK == liq_set_max_colors(handle(env, obj), colors);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setSpeed(JNIEnv *env, jobject obj, jint speed) {
|
||||
return LIQ_OK == liq_set_speed(handle(env, obj), speed);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setMinPosterization(JNIEnv *env, jobject obj, jint p) {
|
||||
return LIQ_OK == liq_set_min_posterization(handle(env, obj), p);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setQuality__I(JNIEnv *env, jobject obj, jint q) {
|
||||
return LIQ_OK == liq_set_quality(handle(env, obj), q/2, q);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_PngQuant_setQuality__II(JNIEnv *env, jobject obj, jint qmin, jint qmax) {
|
||||
return LIQ_OK == liq_set_quality(handle(env, obj), qmin, qmax);
|
||||
}
|
||||
|
||||
static void convert_abgr(liq_color row_out[], int row_index, int width, void* user_info) {
|
||||
liq_jni_image *jniimg = user_info;
|
||||
int column_index;
|
||||
for(column_index=0; column_index < width; column_index++) {
|
||||
row_out[column_index].r = jniimg->data[4*(width*row_index + column_index) + 3];
|
||||
row_out[column_index].g = jniimg->data[4*(width*row_index + column_index) + 2];
|
||||
row_out[column_index].b = jniimg->data[4*(width*row_index + column_index) + 1];
|
||||
row_out[column_index].a = jniimg->data[4*(width*row_index + column_index) + 0];
|
||||
}
|
||||
}
|
||||
|
||||
static void convert_bgr(liq_color row_out[], int row_index, int width, void* user_info) {
|
||||
liq_jni_image *jniimg = user_info;
|
||||
int column_index;
|
||||
for(column_index=0; column_index < width; column_index++) {
|
||||
row_out[column_index].r = jniimg->data[3*(width*row_index + column_index) + 2];
|
||||
row_out[column_index].g = jniimg->data[3*(width*row_index + column_index) + 1];
|
||||
row_out[column_index].b = jniimg->data[3*(width*row_index + column_index) + 0];
|
||||
row_out[column_index].a = 255;
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_org_pngquant_Image_liq_1image_1create(JNIEnv *env, jclass class, jlong attr, jbyteArray bytearray, jint w, jint h, jint components) {
|
||||
/* liq_image needs to be wrapped to keep track of allocated buffer */
|
||||
liq_jni_image *jniimg = malloc(sizeof(liq_jni_image));
|
||||
|
||||
/* copying buffer, since ReleaseByteArrayElements was crashing when called from finalize() */
|
||||
jsize size = (*env)->GetArrayLength(env, bytearray);
|
||||
jniimg->data = malloc(size);
|
||||
(*env)->GetByteArrayRegion(env, bytearray, 0, size, jniimg->data);
|
||||
|
||||
jniimg->image = liq_image_create_custom((liq_attr*)attr, components == 4 ? convert_abgr : convert_bgr, jniimg, w, h, 0);
|
||||
|
||||
if (!jniimg->image) {
|
||||
free(jniimg->data);
|
||||
free(jniimg);
|
||||
return 0;
|
||||
}
|
||||
return (jlong)jniimg;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_Image_addFixedColor(JNIEnv *env, jobject obj, jint r, jint g, jint b, jint a) {
|
||||
liq_color c = {r,g,b,a};
|
||||
return LIQ_OK == liq_image_add_fixed_color(((liq_jni_image*)handle(env,obj))->image, c);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_org_pngquant_Image_getWidth(JNIEnv *env, jobject obj) {
|
||||
return liq_image_get_width(((liq_jni_image*)handle(env,obj))->image);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_org_pngquant_Image_getHeight(JNIEnv *env, jobject obj) {
|
||||
return liq_image_get_height(((liq_jni_image*)handle(env,obj))->image);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_pngquant_Image_liq_1image_1destroy(JNIEnv *env, jclass class, jlong handle) {
|
||||
liq_jni_image *jniimg = (liq_jni_image*)handle;
|
||||
liq_image_destroy(jniimg->image);
|
||||
free(jniimg->data);
|
||||
free(jniimg);
|
||||
}
|
||||
|
||||
JNIEXPORT jlong JNICALL Java_org_pngquant_Result_liq_1quantize_1image(JNIEnv *env, jclass class, jlong attr, jlong handle) {
|
||||
return (jlong)liq_quantize_image((liq_attr*)attr, ((liq_jni_image*)handle)->image);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_Result_setDitheringLevel(JNIEnv *env, jobject obj, jfloat l) {
|
||||
return LIQ_OK == liq_set_dithering_level(handle(env, obj), l);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_Result_setGamma(JNIEnv *env, jobject obj, jdouble gamma) {
|
||||
return LIQ_OK == liq_set_output_gamma(handle(env, obj), gamma);
|
||||
}
|
||||
|
||||
JNIEXPORT jdouble JNICALL Java_org_pngquant_Result_getGamma(JNIEnv *env, jobject obj) {
|
||||
return liq_get_output_gamma(handle(env, obj));
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_pngquant_Result_liq_1write_1remapped_1image(JNIEnv *env, jclass class, jlong result, jlong image_handle, jbyteArray bytearray) {
|
||||
jsize size = (*env)->GetArrayLength(env, bytearray);
|
||||
|
||||
jbyte *bitmap = (*env)->GetByteArrayElements(env, bytearray, 0);
|
||||
liq_error err = liq_write_remapped_image((liq_result*)result, ((liq_jni_image*)image_handle)->image, bitmap, size);
|
||||
(*env)->ReleaseByteArrayElements(env, bytearray, bitmap, 0);
|
||||
|
||||
return LIQ_OK == err;
|
||||
}
|
||||
|
||||
JNIEXPORT jdouble JNICALL Java_org_pngquant_Result_getMeanSquareError(JNIEnv *env, jobject obj) {
|
||||
return liq_get_quantization_error(handle(env, obj));
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_org_pngquant_Result_getQuality(JNIEnv *env, jobject obj) {
|
||||
return liq_get_quantization_quality(handle(env, obj));
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_pngquant_Result_liq_1result_1destroy(JNIEnv *env, jclass class, jlong result) {
|
||||
return liq_result_destroy((liq_result*)result);
|
||||
}
|
||||
|
||||
JNIEXPORT jbyteArray JNICALL Java_org_pngquant_Result_liq_1get_1palette(JNIEnv *env, jclass class, jlong result) {
|
||||
const liq_palette *pal = liq_get_palette((liq_result*)result);
|
||||
jbyteArray arr = (*env)->NewByteArray(env, pal->count * 4);
|
||||
int i;
|
||||
for(i=0; i < pal->count; i++) {
|
||||
(*env)->SetByteArrayRegion(env, arr, i*4, 4, ((jbyte*)&pal->entries[i]));
|
||||
}
|
||||
return arr;
|
||||
}
|
111
CloverApp/libimagequant-2.12.6/org/pngquant/PngQuant.java
Normal file
111
CloverApp/libimagequant-2.12.6/org/pngquant/PngQuant.java
Normal file
@ -0,0 +1,111 @@
|
||||
package org.pngquant;
|
||||
|
||||
import org.pngquant.*;
|
||||
import java.awt.image.*;
|
||||
|
||||
/**
|
||||
* Starting point for the library. Holds configuration. Equivalent of liq_attr* in libimagequant.
|
||||
*/
|
||||
public class PngQuant extends LiqObject {
|
||||
|
||||
/**
|
||||
* Single instance can be "recycled" for many remappings.
|
||||
*/
|
||||
public PngQuant() {
|
||||
handle = liq_attr_create();
|
||||
}
|
||||
|
||||
public PngQuant(PngQuant other) {
|
||||
handle = liq_attr_copy(other.handle);
|
||||
}
|
||||
|
||||
/**
|
||||
* 1-shot quantization and remapping with current settings.
|
||||
* @see quantize()
|
||||
*
|
||||
* @return 8-bit indexed image or null on failure
|
||||
*/
|
||||
public BufferedImage getRemapped(BufferedImage bufimg) {
|
||||
try {
|
||||
Image liqimg = new Image(this, bufimg);
|
||||
BufferedImage remapped = getRemapped(liqimg);
|
||||
liqimg.close();
|
||||
return remapped;
|
||||
} catch(PngQuantException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** @return remapped image or null on failure */
|
||||
public BufferedImage getRemapped(Image liqimg) {
|
||||
Result result = quantize(liqimg);
|
||||
if (result == null) return null;
|
||||
BufferedImage remapped = result.getRemapped(liqimg);
|
||||
result.close();
|
||||
return remapped;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs quantization (chooses optimal palette for the given Image).
|
||||
* Returned object can be used to customize remapping and reused to remap other images to the same palette.
|
||||
* @link http://pngquant.org/lib/#liq_quantize_image
|
||||
*
|
||||
* @return null on failure
|
||||
*/
|
||||
public Result quantize(Image img) {
|
||||
try {
|
||||
return new Result(this, img);
|
||||
} catch(PngQuantException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remapped images won't use more than given number of colors (may use less if setQuality() is used)
|
||||
*
|
||||
* @link http://pngquant.org/lib/#liq_set_max_colors
|
||||
*/
|
||||
public native boolean setMaxColors(int colors);
|
||||
|
||||
/**
|
||||
* Equivalent of setQuality(target/2, target)
|
||||
*
|
||||
* @link http://pngquant.org/lib/#liq_set_quality
|
||||
*/
|
||||
public native boolean setQuality(int target);
|
||||
|
||||
/**
|
||||
* Quality in range 0-100. Quantization will fail if minimum quality cannot
|
||||
* be achieved with given number of colors.
|
||||
*
|
||||
* @link http://pngquant.org/lib/#liq_set_quality
|
||||
*/
|
||||
public native boolean setQuality(int min, int max);
|
||||
|
||||
/**
|
||||
* Speed in range 1 (slowest) and 11 (fastest). 3 is the optimum.
|
||||
* Higher speeds quantize quicker, but at cost of quality and sometimes larger images.
|
||||
*
|
||||
* @link http://pngquant.org/lib/#liq_set_speed
|
||||
*/
|
||||
public native boolean setSpeed(int speed);
|
||||
|
||||
/**
|
||||
* Reduces color precision by truncating number of least significant bits.
|
||||
* Slightly improves speed and helps generating images for low-fidelity displays/textures.
|
||||
*
|
||||
* @link http://pngquant.org/lib/#liq_set_min_posterization
|
||||
*/
|
||||
public native boolean setMinPosterization(int bits);
|
||||
|
||||
public void close() {
|
||||
if (handle != 0) {
|
||||
liq_attr_destroy(handle);
|
||||
handle = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static native long liq_attr_create();
|
||||
private static native long liq_attr_copy(long orig);
|
||||
private static native void liq_attr_destroy(long handle);
|
||||
}
|
@ -0,0 +1,4 @@
|
||||
package org.pngquant;
|
||||
|
||||
public class PngQuantException extends Exception {
|
||||
}
|
90
CloverApp/libimagequant-2.12.6/org/pngquant/Result.java
Normal file
90
CloverApp/libimagequant-2.12.6/org/pngquant/Result.java
Normal file
@ -0,0 +1,90 @@
|
||||
package org.pngquant;
|
||||
|
||||
import org.pngquant.*;
|
||||
import java.awt.image.*;
|
||||
|
||||
/**
|
||||
* Quantization result that holds palette and options for remapping.
|
||||
*/
|
||||
public class Result extends LiqObject {
|
||||
|
||||
/**
|
||||
* Throws when quantization fails (e.g. due to failing to achieve minimum quality)
|
||||
*/
|
||||
public Result(PngQuant pngquant, Image image) throws PngQuantException {
|
||||
handle = liq_quantize_image(pngquant.handle, image.handle);
|
||||
if (handle == 0) {
|
||||
throw new PngQuantException();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BufferedImage remapped to palette this Result has been created with or null on failure.
|
||||
*/
|
||||
public BufferedImage getRemapped(Image orig_image) {
|
||||
byte[] pal = liq_get_palette(handle);
|
||||
IndexColorModel color = new IndexColorModel(8, pal.length/4, pal, 0, true);
|
||||
BufferedImage img = new BufferedImage(
|
||||
orig_image.getWidth(), orig_image.getHeight(),
|
||||
BufferedImage.TYPE_BYTE_INDEXED, color);
|
||||
|
||||
byte[] data = get8bitDataFromImage(img);
|
||||
if (data == null) return null;
|
||||
|
||||
if (!liq_write_remapped_image(handle, orig_image.handle, data)) return null;
|
||||
|
||||
return img;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dithering strength. Floyd-Steinberg is always used and in
|
||||
* speed settings 1-5 high-quality adaptive dithering is used.
|
||||
* @see PngQuant.setSpeed()
|
||||
* @link http://pngquant.org/lib/#liq_set_dithering_level
|
||||
*
|
||||
* @param dither_level Dithering in range 0 (none) and 1 (full)
|
||||
*/
|
||||
public native boolean setDitheringLevel(float dither_level);
|
||||
|
||||
/**
|
||||
* The default is 0.45455 (1/2.2) which is PNG's approximation of sRGB.
|
||||
*/
|
||||
public native boolean setGamma(double gamma);
|
||||
public native double getGamma();
|
||||
|
||||
/**
|
||||
* Mean Square Error of remapping of image used to create this result.
|
||||
* @link http://pngquant.org/lib/#liq_get_quantization_error
|
||||
*
|
||||
* @return MSE or -1 if not available
|
||||
*/
|
||||
public native double getMeanSquareError();
|
||||
|
||||
/**
|
||||
* @link http://pngquant.org/lib/#liq_get_quantization_quality
|
||||
* @return Actually achieved quality in 0-100 range on scale compatible with PngQuant.setQuality()
|
||||
*/
|
||||
public native int getQuality();
|
||||
|
||||
public void close() {
|
||||
if (handle != 0) {
|
||||
liq_result_destroy(handle);
|
||||
handle = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] get8bitDataFromImage(BufferedImage image) {
|
||||
if (image.getType() == BufferedImage.TYPE_BYTE_INDEXED) {
|
||||
DataBuffer buffer = image.getRaster().getDataBuffer();
|
||||
if (buffer instanceof DataBufferByte) {
|
||||
return ((DataBufferByte)buffer).getData();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static native byte[] liq_get_palette(long handle);
|
||||
private static native long liq_quantize_image(long attr, long image);
|
||||
private static native boolean liq_write_remapped_image(long handle, long image, byte[] buffer);
|
||||
private static native void liq_result_destroy(long handle);
|
||||
}
|
286
CloverApp/libimagequant-2.12.6/pam.c
Normal file
286
CloverApp/libimagequant-2.12.6/pam.c
Normal file
@ -0,0 +1,286 @@
|
||||
/* pam.c - pam (portable alpha map) utility library
|
||||
**
|
||||
** © 2009-2017 by Kornel Lesiński.
|
||||
** © 1989, 1991 by Jef Poskanzer.
|
||||
** © 1997, 2000, 2002 by Greg Roelofs; based on an idea by Stefan Schneider.
|
||||
**
|
||||
** See COPYRIGHT file for license.
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "libimagequant.h"
|
||||
#include "pam.h"
|
||||
#include "mempool.h"
|
||||
|
||||
LIQ_PRIVATE bool pam_computeacolorhash(struct acolorhash_table *acht, const rgba_pixel *const pixels[], unsigned int cols, unsigned int rows, const unsigned char *importance_map)
|
||||
{
|
||||
const unsigned int ignorebits = acht->ignorebits;
|
||||
const unsigned int channel_mask = 255U>>ignorebits<<ignorebits;
|
||||
const unsigned int channel_hmask = (255U>>ignorebits) ^ 0xFFU;
|
||||
const unsigned int posterize_mask = channel_mask << 24 | channel_mask << 16 | channel_mask << 8 | channel_mask;
|
||||
const unsigned int posterize_high_mask = channel_hmask << 24 | channel_hmask << 16 | channel_hmask << 8 | channel_hmask;
|
||||
|
||||
const unsigned int hash_size = acht->hash_size;
|
||||
|
||||
/* Go through the entire image, building a hash table of colors. */
|
||||
for(unsigned int row = 0; row < rows; ++row) {
|
||||
|
||||
for(unsigned int col = 0; col < cols; ++col) {
|
||||
unsigned int boost;
|
||||
|
||||
// RGBA color is casted to long for easier hasing/comparisons
|
||||
union rgba_as_int px = {pixels[row][col]};
|
||||
unsigned int hash;
|
||||
if (!px.rgba.a) {
|
||||
// "dirty alpha" has different RGBA values that end up being the same fully transparent color
|
||||
px.l=0; hash=0;
|
||||
|
||||
boost = 2000;
|
||||
if (importance_map) {
|
||||
importance_map++;
|
||||
}
|
||||
} else {
|
||||
// mask posterizes all 4 channels in one go
|
||||
px.l = (px.l & posterize_mask) | ((px.l & posterize_high_mask) >> (8-ignorebits));
|
||||
// fancier hashing algorithms didn't improve much
|
||||
hash = px.l % hash_size;
|
||||
|
||||
if (importance_map) {
|
||||
boost = *importance_map++;
|
||||
} else {
|
||||
boost = 255;
|
||||
}
|
||||
}
|
||||
|
||||
if (!pam_add_to_hash(acht, hash, boost, px, row, rows)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
acht->cols = cols;
|
||||
acht->rows += rows;
|
||||
return true;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE bool pam_add_to_hash(struct acolorhash_table *acht, unsigned int hash, unsigned int boost, union rgba_as_int px, unsigned int row, unsigned int rows)
|
||||
{
|
||||
/* head of the hash function stores first 2 colors inline (achl->used = 1..2),
|
||||
to reduce number of allocations of achl->other_items.
|
||||
*/
|
||||
struct acolorhist_arr_head *achl = &acht->buckets[hash];
|
||||
if (achl->inline1.color.l == px.l && achl->used) {
|
||||
achl->inline1.perceptual_weight += boost;
|
||||
return true;
|
||||
}
|
||||
if (achl->used) {
|
||||
if (achl->used > 1) {
|
||||
if (achl->inline2.color.l == px.l) {
|
||||
achl->inline2.perceptual_weight += boost;
|
||||
return true;
|
||||
}
|
||||
// other items are stored as an array (which gets reallocated if needed)
|
||||
struct acolorhist_arr_item *other_items = achl->other_items;
|
||||
unsigned int i = 0;
|
||||
for (; i < achl->used-2; i++) {
|
||||
if (other_items[i].color.l == px.l) {
|
||||
other_items[i].perceptual_weight += boost;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// the array was allocated with spare items
|
||||
if (i < achl->capacity) {
|
||||
other_items[i] = (struct acolorhist_arr_item){
|
||||
.color = px,
|
||||
.perceptual_weight = boost,
|
||||
};
|
||||
achl->used++;
|
||||
++acht->colors;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (++acht->colors > acht->maxcolors) {
|
||||
return false;
|
||||
}
|
||||
|
||||
struct acolorhist_arr_item *new_items;
|
||||
unsigned int capacity;
|
||||
if (!other_items) { // there was no array previously, alloc "small" array
|
||||
capacity = 8;
|
||||
if (acht->freestackp <= 0) {
|
||||
// estimate how many colors are going to be + headroom
|
||||
const size_t mempool_size = ((acht->rows + rows-row) * 2 * acht->colors / (acht->rows + row + 1) + 1024) * sizeof(struct acolorhist_arr_item);
|
||||
new_items = mempool_alloc(&acht->mempool, sizeof(struct acolorhist_arr_item)*capacity, (unsigned int)mempool_size);
|
||||
} else {
|
||||
// freestack stores previously freed (reallocated) arrays that can be reused
|
||||
// (all pesimistically assumed to be capacity = 8)
|
||||
new_items = acht->freestack[--acht->freestackp];
|
||||
}
|
||||
} else {
|
||||
const unsigned int stacksize = sizeof(acht->freestack)/sizeof(acht->freestack[0]);
|
||||
|
||||
// simply reallocs and copies array to larger capacity
|
||||
capacity = achl->capacity*2 + 16;
|
||||
if (acht->freestackp < stacksize-1) {
|
||||
acht->freestack[acht->freestackp++] = other_items;
|
||||
}
|
||||
const size_t mempool_size = ((acht->rows + rows-row) * 2 * acht->colors / (acht->rows + row + 1) + 32*capacity) * sizeof(struct acolorhist_arr_item);
|
||||
new_items = mempool_alloc(&acht->mempool, sizeof(struct acolorhist_arr_item)*capacity, (unsigned int)mempool_size);
|
||||
if (!new_items) return false;
|
||||
memcpy(new_items, other_items, sizeof(other_items[0])*achl->capacity);
|
||||
}
|
||||
|
||||
achl->other_items = new_items;
|
||||
achl->capacity = capacity;
|
||||
new_items[i] = (struct acolorhist_arr_item){
|
||||
.color = px,
|
||||
.perceptual_weight = boost,
|
||||
};
|
||||
achl->used++;
|
||||
} else {
|
||||
// these are elses for first checks whether first and second inline-stored colors are used
|
||||
achl->inline2.color.l = px.l;
|
||||
achl->inline2.perceptual_weight = boost;
|
||||
achl->used = 2;
|
||||
++acht->colors;
|
||||
}
|
||||
} else {
|
||||
achl->inline1.color.l = px.l;
|
||||
achl->inline1.perceptual_weight = boost;
|
||||
achl->used = 1;
|
||||
++acht->colors;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE struct acolorhash_table *pam_allocacolorhash(unsigned int maxcolors, unsigned int surface, unsigned int ignorebits, void* (*malloc)(size_t), void (*free)(void*))
|
||||
{
|
||||
const size_t estimated_colors = MIN(maxcolors, surface/(ignorebits + (surface > 512*512 ? 6 : 5)));
|
||||
const size_t hash_size = estimated_colors < 66000 ? 6673 : (estimated_colors < 200000 ? 12011 : 24019);
|
||||
|
||||
mempoolptr m = NULL;
|
||||
const size_t buckets_size = hash_size * sizeof(struct acolorhist_arr_head);
|
||||
const size_t mempool_size = sizeof(struct acolorhash_table) + buckets_size + estimated_colors * sizeof(struct acolorhist_arr_item);
|
||||
struct acolorhash_table *t = mempool_create(&m, (unsigned int)(sizeof(*t) + buckets_size), (unsigned int)mempool_size, malloc, free);
|
||||
if (!t) return NULL;
|
||||
*t = (struct acolorhash_table){
|
||||
.mempool = m,
|
||||
.hash_size = (unsigned int)hash_size,
|
||||
.maxcolors = maxcolors,
|
||||
.ignorebits = ignorebits,
|
||||
};
|
||||
memset(t->buckets, 0, buckets_size);
|
||||
return t;
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static float pam_add_to_hist(const float *gamma_lut, hist_item *achv, unsigned int *j, const struct acolorhist_arr_item *entry, const float max_perceptual_weight)
|
||||
{
|
||||
if (entry->perceptual_weight == 0) {
|
||||
return 0;
|
||||
}
|
||||
const float w = MIN(entry->perceptual_weight/128.f, max_perceptual_weight);
|
||||
achv[*j].adjusted_weight = achv[*j].perceptual_weight = w;
|
||||
achv[*j].acolor = rgba_to_f(gamma_lut, entry->color.rgba);
|
||||
*j += 1;
|
||||
return w;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE histogram *pam_acolorhashtoacolorhist(const struct acolorhash_table *acht, const double gamma, void* (*malloc)(size_t), void (*free)(void*))
|
||||
{
|
||||
histogram *hist = malloc(sizeof(hist[0]));
|
||||
if (!hist || !acht) return NULL;
|
||||
*hist = (histogram){
|
||||
.achv = malloc(MAX(1,acht->colors) * sizeof(hist->achv[0])),
|
||||
.size = acht->colors,
|
||||
.free = free,
|
||||
.ignorebits = acht->ignorebits,
|
||||
};
|
||||
if (!hist->achv) return NULL;
|
||||
|
||||
float gamma_lut[256];
|
||||
to_f_set_gamma(gamma_lut, gamma);
|
||||
|
||||
/* Limit perceptual weight to 1/10th of the image surface area to prevent
|
||||
a single color from dominating all others. */
|
||||
float max_perceptual_weight = 0.1f * acht->cols * acht->rows;
|
||||
double total_weight = 0;
|
||||
|
||||
unsigned int j=0;
|
||||
for(unsigned int i=0; i < acht->hash_size; ++i) {
|
||||
const struct acolorhist_arr_head *const achl = &acht->buckets[i];
|
||||
if (achl->used) {
|
||||
total_weight += pam_add_to_hist(gamma_lut, hist->achv, &j, &achl->inline1, max_perceptual_weight);
|
||||
|
||||
if (achl->used > 1) {
|
||||
total_weight += pam_add_to_hist(gamma_lut, hist->achv, &j, &achl->inline2, max_perceptual_weight);
|
||||
|
||||
for(unsigned int k=0; k < achl->used-2; k++) {
|
||||
total_weight += pam_add_to_hist(gamma_lut, hist->achv, &j, &achl->other_items[k], max_perceptual_weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hist->size = j;
|
||||
hist->total_perceptual_weight = total_weight;
|
||||
if (!j) {
|
||||
pam_freeacolorhist(hist);
|
||||
return NULL;
|
||||
}
|
||||
return hist;
|
||||
}
|
||||
|
||||
|
||||
LIQ_PRIVATE void pam_freeacolorhash(struct acolorhash_table *acht)
|
||||
{
|
||||
if (acht) {
|
||||
mempool_destroy(acht->mempool);
|
||||
}
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void pam_freeacolorhist(histogram *hist)
|
||||
{
|
||||
hist->free(hist->achv);
|
||||
hist->free(hist);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE colormap *pam_colormap(unsigned int colors, void* (*malloc)(size_t), void (*free)(void*))
|
||||
{
|
||||
assert(colors > 0 && colors < 65536);
|
||||
|
||||
colormap *map;
|
||||
const size_t colors_size = colors * sizeof(map->palette[0]);
|
||||
map = malloc(sizeof(colormap) + colors_size);
|
||||
if (!map) return NULL;
|
||||
*map = (colormap){
|
||||
.malloc = malloc,
|
||||
.free = free,
|
||||
.colors = colors,
|
||||
};
|
||||
memset(map->palette, 0, colors_size);
|
||||
return map;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE colormap *pam_duplicate_colormap(colormap *map)
|
||||
{
|
||||
colormap *dupe = pam_colormap(map->colors, map->malloc, map->free);
|
||||
for(unsigned int i=0; i < map->colors; i++) {
|
||||
dupe->palette[i] = map->palette[i];
|
||||
}
|
||||
return dupe;
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void pam_freecolormap(colormap *c)
|
||||
{
|
||||
c->free(c);
|
||||
}
|
||||
|
||||
LIQ_PRIVATE void to_f_set_gamma(float gamma_lut[], const double gamma)
|
||||
{
|
||||
for(int i=0; i < 256; i++) {
|
||||
gamma_lut[i] = pow((double)i/255.0, internal_gamma/gamma);
|
||||
}
|
||||
}
|
||||
|
283
CloverApp/libimagequant-2.12.6/pam.h
Normal file
283
CloverApp/libimagequant-2.12.6/pam.h
Normal file
@ -0,0 +1,283 @@
|
||||
/* pam.h - pam (portable alpha map) utility library
|
||||
**
|
||||
** Colormap routines.
|
||||
**
|
||||
** Copyright (C) 1989, 1991 by Jef Poskanzer.
|
||||
** Copyright (C) 1997 by Greg Roelofs.
|
||||
**
|
||||
** Permission to use, copy, modify, and distribute this software and its
|
||||
** documentation for any purpose and without fee is hereby granted, provided
|
||||
** that the above copyright notice appear in all copies and that both that
|
||||
** copyright notice and this permission notice appear in supporting
|
||||
** documentation. This software is provided "as is" without express or
|
||||
** implied warranty.
|
||||
*/
|
||||
|
||||
#ifndef PAM_H
|
||||
#define PAM_H
|
||||
|
||||
// accidental debug assertions make color search much slower,
|
||||
// so force assertions off if there's no explicit setting
|
||||
#if !defined(NDEBUG) && !defined(DEBUG)
|
||||
#define NDEBUG
|
||||
#endif
|
||||
|
||||
#include <math.h>
|
||||
#include <assert.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifndef MAX
|
||||
# define MAX(a,b) ((a) > (b)? (a) : (b))
|
||||
# define MIN(a,b) ((a) < (b)? (a) : (b))
|
||||
#endif
|
||||
|
||||
#define MAX_DIFF 1e20
|
||||
|
||||
#ifndef USE_SSE
|
||||
# if defined(__SSE__) && (defined(__amd64__) || defined(__X86_64__) || defined(_WIN64) || defined(WIN32) || defined(__WIN32__))
|
||||
# define USE_SSE 1
|
||||
# else
|
||||
# define USE_SSE 0
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#if USE_SSE
|
||||
# include <xmmintrin.h>
|
||||
# ifdef _MSC_VER
|
||||
# include <intrin.h>
|
||||
# define SSE_ALIGN
|
||||
# else
|
||||
# define SSE_ALIGN __attribute__ ((aligned (16)))
|
||||
# if defined(__i386__) && defined(__PIC__)
|
||||
# define cpuid(func,ax,bx,cx,dx)\
|
||||
__asm__ __volatile__ ( \
|
||||
"push %%ebx\n" \
|
||||
"cpuid\n" \
|
||||
"mov %%ebx, %1\n" \
|
||||
"pop %%ebx\n" \
|
||||
: "=a" (ax), "=r" (bx), "=c" (cx), "=d" (dx) \
|
||||
: "a" (func));
|
||||
# else
|
||||
# define cpuid(func,ax,bx,cx,dx)\
|
||||
__asm__ __volatile__ ("cpuid":\
|
||||
"=a" (ax), "=b" (bx), "=c" (cx), "=d" (dx) : "a" (func));
|
||||
# endif
|
||||
#endif
|
||||
#else
|
||||
# define SSE_ALIGN
|
||||
#endif
|
||||
|
||||
#ifndef _MSC_VER
|
||||
#define LIQ_ARRAY(type, var, count) type var[count]
|
||||
#else
|
||||
#define LIQ_ARRAY(type, var, count) type* var = (type*)_alloca(sizeof(type)*(count))
|
||||
#endif
|
||||
|
||||
#if defined(__GNUC__) || defined (__llvm__)
|
||||
#define ALWAYS_INLINE __attribute__((always_inline)) inline
|
||||
#define NEVER_INLINE __attribute__ ((noinline))
|
||||
#elif defined(_MSC_VER)
|
||||
#define inline __inline
|
||||
#define restrict __restrict
|
||||
#define ALWAYS_INLINE __forceinline
|
||||
#define NEVER_INLINE __declspec(noinline)
|
||||
#else
|
||||
#define ALWAYS_INLINE inline
|
||||
#define NEVER_INLINE
|
||||
#endif
|
||||
|
||||
/* from pam.h */
|
||||
|
||||
typedef struct {
|
||||
unsigned char r, g, b, a;
|
||||
} rgba_pixel;
|
||||
|
||||
typedef struct {
|
||||
float a, r, g, b;
|
||||
} SSE_ALIGN f_pixel;
|
||||
|
||||
static const float internal_gamma = 0.5499f;
|
||||
|
||||
LIQ_PRIVATE void to_f_set_gamma(float gamma_lut[], const double gamma);
|
||||
|
||||
/**
|
||||
Converts 8-bit color to internal gamma and premultiplied alpha.
|
||||
(premultiplied color space is much better for blending of semitransparent colors)
|
||||
*/
|
||||
ALWAYS_INLINE static f_pixel rgba_to_f(const float gamma_lut[], const rgba_pixel px);
|
||||
inline static f_pixel rgba_to_f(const float gamma_lut[], const rgba_pixel px)
|
||||
{
|
||||
float a = px.a/255.f;
|
||||
|
||||
return (f_pixel) {
|
||||
.a = a,
|
||||
.r = gamma_lut[px.r]*a,
|
||||
.g = gamma_lut[px.g]*a,
|
||||
.b = gamma_lut[px.b]*a,
|
||||
};
|
||||
}
|
||||
|
||||
inline static rgba_pixel f_to_rgb(const float gamma, const f_pixel px)
|
||||
{
|
||||
if (px.a < 1.f/256.f) {
|
||||
return (rgba_pixel){0,0,0,0};
|
||||
}
|
||||
|
||||
float r = px.r / px.a,
|
||||
g = px.g / px.a,
|
||||
b = px.b / px.a,
|
||||
a = px.a;
|
||||
|
||||
r = powf(r, gamma/internal_gamma);
|
||||
g = powf(g, gamma/internal_gamma);
|
||||
b = powf(b, gamma/internal_gamma);
|
||||
|
||||
// 256, because numbers are in range 1..255.9999… rounded down
|
||||
r *= 256.f;
|
||||
g *= 256.f;
|
||||
b *= 256.f;
|
||||
a *= 256.f;
|
||||
|
||||
return (rgba_pixel){
|
||||
.r = r>=255.f ? 255 : r,
|
||||
.g = g>=255.f ? 255 : g,
|
||||
.b = b>=255.f ? 255 : b,
|
||||
.a = a>=255.f ? 255 : a,
|
||||
};
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static double colordifference_ch(const double x, const double y, const double alphas);
|
||||
inline static double colordifference_ch(const double x, const double y, const double alphas)
|
||||
{
|
||||
// maximum of channel blended on white, and blended on black
|
||||
// premultiplied alpha and backgrounds 0/1 shorten the formula
|
||||
const double black = x-y, white = black+alphas;
|
||||
return MAX(black*black, white*white);
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static float colordifference_stdc(const f_pixel px, const f_pixel py);
|
||||
inline static float colordifference_stdc(const f_pixel px, const f_pixel py)
|
||||
{
|
||||
// px_b.rgb = px.rgb + 0*(1-px.a) // blend px on black
|
||||
// px_b.a = px.a + 1*(1-px.a)
|
||||
// px_w.rgb = px.rgb + 1*(1-px.a) // blend px on white
|
||||
// px_w.a = px.a + 1*(1-px.a)
|
||||
|
||||
// px_b.rgb = px.rgb // difference same as in opaque RGB
|
||||
// px_b.a = 1
|
||||
// px_w.rgb = px.rgb - px.a // difference simplifies to formula below
|
||||
// px_w.a = 1
|
||||
|
||||
// (px.rgb - px.a) - (py.rgb - py.a)
|
||||
// (px.rgb - py.rgb) + (py.a - px.a)
|
||||
|
||||
const double alphas = py.a-px.a;
|
||||
return colordifference_ch(px.r, py.r, alphas) +
|
||||
colordifference_ch(px.g, py.g, alphas) +
|
||||
colordifference_ch(px.b, py.b, alphas);
|
||||
}
|
||||
|
||||
ALWAYS_INLINE static float colordifference(f_pixel px, f_pixel py);
|
||||
inline static float colordifference(f_pixel px, f_pixel py)
|
||||
{
|
||||
#if USE_SSE
|
||||
const __m128 vpx = _mm_load_ps((const float*)&px);
|
||||
const __m128 vpy = _mm_load_ps((const float*)&py);
|
||||
|
||||
// y.a - x.a
|
||||
__m128 alphas = _mm_sub_ss(vpy, vpx);
|
||||
alphas = _mm_shuffle_ps(alphas,alphas,0); // copy first to all four
|
||||
|
||||
__m128 onblack = _mm_sub_ps(vpx, vpy); // x - y
|
||||
__m128 onwhite = _mm_add_ps(onblack, alphas); // x - y + (y.a - x.a)
|
||||
|
||||
onblack = _mm_mul_ps(onblack, onblack);
|
||||
onwhite = _mm_mul_ps(onwhite, onwhite);
|
||||
const __m128 max = _mm_max_ps(onwhite, onblack);
|
||||
|
||||
// add rgb, not a
|
||||
const __m128 maxhl = _mm_movehl_ps(max, max);
|
||||
const __m128 tmp = _mm_add_ps(max, maxhl);
|
||||
const __m128 sum = _mm_add_ss(maxhl, _mm_shuffle_ps(tmp, tmp, 1));
|
||||
|
||||
const float res = _mm_cvtss_f32(sum);
|
||||
assert(fabs(res - colordifference_stdc(px,py)) < 0.001);
|
||||
return res;
|
||||
#else
|
||||
return colordifference_stdc(px,py);
|
||||
#endif
|
||||
}
|
||||
|
||||
/* from pamcmap.h */
|
||||
union rgba_as_int {
|
||||
rgba_pixel rgba;
|
||||
unsigned int l;
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
f_pixel acolor;
|
||||
float adjusted_weight, // perceptual weight changed to tweak how mediancut selects colors
|
||||
perceptual_weight; // number of pixels weighted by importance of different areas of the picture
|
||||
|
||||
float color_weight; // these two change every time histogram subset is sorted
|
||||
union {
|
||||
unsigned int sort_value;
|
||||
unsigned char likely_colormap_index;
|
||||
} tmp;
|
||||
} hist_item;
|
||||
|
||||
typedef struct {
|
||||
hist_item *achv;
|
||||
void (*free)(void*);
|
||||
double total_perceptual_weight;
|
||||
unsigned int size;
|
||||
unsigned int ignorebits;
|
||||
} histogram;
|
||||
|
||||
typedef struct {
|
||||
f_pixel acolor;
|
||||
float popularity;
|
||||
bool fixed; // if true it's user-supplied and must not be changed (e.g in K-Means iteration)
|
||||
} colormap_item;
|
||||
|
||||
typedef struct colormap {
|
||||
unsigned int colors;
|
||||
void* (*malloc)(size_t);
|
||||
void (*free)(void*);
|
||||
colormap_item palette[];
|
||||
} colormap;
|
||||
|
||||
struct acolorhist_arr_item {
|
||||
union rgba_as_int color;
|
||||
unsigned int perceptual_weight;
|
||||
};
|
||||
|
||||
struct acolorhist_arr_head {
|
||||
struct acolorhist_arr_item inline1, inline2;
|
||||
unsigned int used, capacity;
|
||||
struct acolorhist_arr_item *other_items;
|
||||
};
|
||||
|
||||
struct acolorhash_table {
|
||||
struct mempool *mempool;
|
||||
unsigned int ignorebits, maxcolors, colors, cols, rows;
|
||||
unsigned int hash_size;
|
||||
unsigned int freestackp;
|
||||
struct acolorhist_arr_item *freestack[512];
|
||||
struct acolorhist_arr_head buckets[];
|
||||
};
|
||||
|
||||
LIQ_PRIVATE void pam_freeacolorhash(struct acolorhash_table *acht);
|
||||
LIQ_PRIVATE struct acolorhash_table *pam_allocacolorhash(unsigned int maxcolors, unsigned int surface, unsigned int ignorebits, void* (*malloc)(size_t), void (*free)(void*));
|
||||
LIQ_PRIVATE histogram *pam_acolorhashtoacolorhist(const struct acolorhash_table *acht, const double gamma, void* (*malloc)(size_t), void (*free)(void*));
|
||||
LIQ_PRIVATE bool pam_computeacolorhash(struct acolorhash_table *acht, const rgba_pixel *const pixels[], unsigned int cols, unsigned int rows, const unsigned char *importance_map);
|
||||
LIQ_PRIVATE bool pam_add_to_hash(struct acolorhash_table *acht, unsigned int hash, unsigned int boost, union rgba_as_int px, unsigned int row, unsigned int rows);
|
||||
|
||||
LIQ_PRIVATE void pam_freeacolorhist(histogram *h);
|
||||
|
||||
LIQ_PRIVATE colormap *pam_colormap(unsigned int colors, void* (*malloc)(size_t), void (*free)(void*));
|
||||
LIQ_PRIVATE colormap *pam_duplicate_colormap(colormap *map);
|
||||
LIQ_PRIVATE void pam_freecolormap(colormap *c);
|
||||
|
||||
#endif
|
87
CloverApp/libimagequant-2.12.6/pom.xml
Normal file
87
CloverApp/libimagequant-2.12.6/pom.xml
Normal file
@ -0,0 +1,87 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.pngquant</groupId>
|
||||
<artifactId>libimagequant</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>2.1.1</version>
|
||||
<name>pngquant</name>
|
||||
<url>http://pngquant.org</url>
|
||||
<build>
|
||||
<sourceDirectory>.</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>1.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>build</id>
|
||||
<phase>compile</phase>
|
||||
<goals><goal>exec</goal></goals>
|
||||
<configuration>
|
||||
<executable>make</executable>
|
||||
<arguments>
|
||||
<argument>-j8</argument>
|
||||
<argument>USE_SSE=1</argument>
|
||||
<argument>java</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>clean</id>
|
||||
<phase>clean</phase>
|
||||
<goals><goal>exec</goal></goals>
|
||||
<configuration>
|
||||
<executable>make</executable>
|
||||
<arguments>
|
||||
<argument>clean</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>mac-x64</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>Mac</family>
|
||||
<arch>x64</arch>
|
||||
</os>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.pngquant</groupId>
|
||||
<artifactId>libimagequant-jni</artifactId>
|
||||
<version>1</version>
|
||||
<type>jnilib</type>
|
||||
<classifier>mac-x64</classifier>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>linux-x64</id>
|
||||
<activation>
|
||||
<os>
|
||||
<family>unix</family>
|
||||
<name>Linux</name>
|
||||
<arch>x64</arch>
|
||||
</os>
|
||||
</activation>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.pngquant</groupId>
|
||||
<artifactId>libimagequant-jni</artifactId>
|
||||
<type>so</type>
|
||||
<version>1</version>
|
||||
<classifier>linux-x64</classifier>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</profile>
|
||||
</profiles>
|
||||
<dependencies>
|
||||
</dependencies>
|
||||
</project>
|
2
CloverApp/libimagequant-2.12.6/rust-api/.gitignore
vendored
Normal file
2
CloverApp/libimagequant-2.12.6/rust-api/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
target/
|
||||
Cargo.lock
|
635
CloverApp/libimagequant-2.12.6/rust-api/COPYRIGHT
Normal file
635
CloverApp/libimagequant-2.12.6/rust-api/COPYRIGHT
Normal file
@ -0,0 +1,635 @@
|
||||
https://raw.githubusercontent.com/ImageOptim/libimagequant/master/COPYRIGHT
|
||||
|
||||
libimagequant © 2009-2016 by Kornel Lesiński.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||
|
||||
© 1989, 1991 by Jef Poskanzer.
|
||||
© 1997, 2000, 2002 by Greg Roelofs.
|
||||
|
||||
Permission to use, copy, modify, and distribute this software and its
|
||||
documentation for any purpose and without fee is hereby granted, provided
|
||||
that the above copyright notice appear in all copies and that both that
|
||||
copyright notice and this permission notice appear in supporting
|
||||
documentation. This software is provided "as is" without express or
|
||||
implied warranty.
|
27
CloverApp/libimagequant-2.12.6/rust-api/Cargo.toml
Normal file
27
CloverApp/libimagequant-2.12.6/rust-api/Cargo.toml
Normal file
@ -0,0 +1,27 @@
|
||||
[package]
|
||||
categories = ["multimedia::images"]
|
||||
description = "Convert 24/32-bit images to 8-bit palette with alpha channel.\nBindings for libimagequant that powers pngquant lossy PNG compressor.\n\nDual-licensed like pngquant. See https://pngquant.org for details."
|
||||
documentation = "https://docs.rs/imagequant"
|
||||
homepage = "https://pngquant.org/lib/"
|
||||
include = ["src/*", "examples/*", "COPYRIGHT", "Cargo.toml", "README.md"]
|
||||
keywords = ["quantization", "palette", "image", "pngquant", "compression"]
|
||||
authors = [ "Kornel <kornel@pngquant.org>" ]
|
||||
license = "GPL-3.0+"
|
||||
name = "imagequant"
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/ImageOptim/libimagequant"
|
||||
version = "2.12.6"
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
imagequant-sys = { version = "2.12.6", path = "../" }
|
||||
libc = "0.2.60"
|
||||
|
||||
[features]
|
||||
default = ["sse"]
|
||||
sse = ["imagequant-sys/sse"]
|
||||
openmp = ["imagequant-sys/openmp"]
|
||||
openmp-static = ["openmp", "imagequant-sys/openmp-static"]
|
||||
|
||||
[lib]
|
||||
name = "imagequant"
|
15
CloverApp/libimagequant-2.12.6/rust-api/README.md
Normal file
15
CloverApp/libimagequant-2.12.6/rust-api/README.md
Normal file
@ -0,0 +1,15 @@
|
||||
# [libimagequant](https://pngquant.org/lib/) bindings for [Rust](https://www.rust-lang.org/)
|
||||
|
||||
Imagequant library converts RGBA images to 8-bit indexed images with palette, *including* alpha component.
|
||||
It's ideal for generating tiny PNG images (although [image I/O](https://github.com/kornelski/lodepng-rust) isn't handled by the library itself).
|
||||
|
||||
This wrapper makes the library usable from Rust.
|
||||
|
||||
Rust API closely follows the C API, but is slightly OO-ified:
|
||||
|
||||
liq_set_dithering_level(result, 1.0);
|
||||
↓
|
||||
result.set_dithering_level(1.0);
|
||||
|
||||
For more details see [libimagequant documentation](https://pngquant.org/lib/) and [Rust function reference](https://kornelski.github.io/libimagequant-rust/imagequant/).
|
||||
|
32
CloverApp/libimagequant-2.12.6/rust-api/examples/basic.rs
Normal file
32
CloverApp/libimagequant-2.12.6/rust-api/examples/basic.rs
Normal file
@ -0,0 +1,32 @@
|
||||
// Don't forget to add -L . (or whatever dir has .rlib) to rustc!
|
||||
|
||||
fn main() {
|
||||
// Image loading/saving is outside scope of this library
|
||||
let width = 10usize;
|
||||
let height = 10usize;
|
||||
let fakebitmap = vec![255u8; 4 * width * height];
|
||||
|
||||
// http://pngquant.org/lib/
|
||||
|
||||
// Configure the library
|
||||
let mut liq = imagequant::new();
|
||||
liq.set_speed(5);
|
||||
liq.set_quality(70, 99);
|
||||
|
||||
// Describe the bitmap
|
||||
let ref mut img = liq.new_image(&fakebitmap[..], width, height, 0.0).unwrap();
|
||||
|
||||
// The magic happens in quantize()
|
||||
let mut res = match liq.quantize(img) {
|
||||
Ok(res) => res,
|
||||
Err(err) => panic!("Quantization failed, because: {:?}", err),
|
||||
};
|
||||
|
||||
// Enable dithering for subsequent remappings
|
||||
res.set_dithering_level(1.0);
|
||||
|
||||
// You can reuse the result to generate several images with the same palette
|
||||
let (palette, pixels) = res.remapped(img).unwrap();
|
||||
|
||||
println!("Done! Got palette {:?} and {} pixels with {}% quality", palette, pixels.len(), res.quantization_quality());
|
||||
}
|
566
CloverApp/libimagequant-2.12.6/rust-api/src/lib.rs
Normal file
566
CloverApp/libimagequant-2.12.6/rust-api/src/lib.rs
Normal file
@ -0,0 +1,566 @@
|
||||
//! https://pngquant.org/lib/
|
||||
//!
|
||||
//! Converts RGBA images to 8-bit with alpha channel.
|
||||
//!
|
||||
//! This is based on imagequant library, which generates very high quality images.
|
||||
//!
|
||||
//! See `examples/` directory for example code.
|
||||
#![doc(html_logo_url = "https://pngquant.org/pngquant-logo.png")]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
extern crate imagequant_sys as ffi;
|
||||
|
||||
pub use crate::ffi::liq_error;
|
||||
pub use crate::ffi::liq_error::*;
|
||||
use std::fmt;
|
||||
use std::marker;
|
||||
use std::mem;
|
||||
use std::os::raw::c_int;
|
||||
use std::ptr;
|
||||
|
||||
/// 8-bit RGBA. This is the only color format used by the library.
|
||||
pub type Color = ffi::liq_color;
|
||||
|
||||
/// Number of pixels in a given color
|
||||
///
|
||||
/// Used if you're building histogram manually. Otherwise see `add_image()`
|
||||
pub type HistogramEntry = ffi::liq_histogram_entry;
|
||||
|
||||
/// Settings for the conversion proces. Start here.
|
||||
pub struct Attributes {
|
||||
handle: *mut ffi::liq_attr,
|
||||
}
|
||||
|
||||
/// Describes image dimensions for the library.
|
||||
pub struct Image<'a> {
|
||||
handle: *mut ffi::liq_image,
|
||||
/// Holds row pointers for images with stride
|
||||
_marker: marker::PhantomData<&'a [u8]>,
|
||||
}
|
||||
|
||||
/// Palette inside.
|
||||
pub struct QuantizationResult {
|
||||
handle: *mut ffi::liq_result,
|
||||
}
|
||||
|
||||
/// Generate one shared palette for multiple images.
|
||||
pub struct Histogram<'a> {
|
||||
attr: &'a Attributes,
|
||||
handle: *mut ffi::liq_histogram,
|
||||
}
|
||||
|
||||
impl Drop for Attributes {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
if !self.handle.is_null() {
|
||||
ffi::liq_attr_destroy(&mut *self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Drop for Image<'a> {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ffi::liq_image_destroy(&mut *self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for QuantizationResult {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ffi::liq_result_destroy(&mut *self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Drop for Histogram<'a> {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ffi::liq_histogram_destroy(&mut *self.handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Attributes {
|
||||
fn clone(&self) -> Attributes {
|
||||
unsafe { Attributes { handle: ffi::liq_attr_copy(&*self.handle) } }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Attributes {
|
||||
fn default() -> Attributes {
|
||||
Attributes::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Attributes {
|
||||
/// New handle for library configuration
|
||||
///
|
||||
/// See also `new_image()`
|
||||
pub fn new() -> Self {
|
||||
let handle = unsafe { ffi::liq_attr_create() };
|
||||
assert!(!handle.is_null(), "SSE-capable CPU is required for this build.");
|
||||
Attributes { handle }
|
||||
}
|
||||
|
||||
/// It's better to use `set_quality()`
|
||||
pub fn set_max_colors(&mut self, value: i32) -> liq_error {
|
||||
unsafe { ffi::liq_set_max_colors(&mut *self.handle, value) }
|
||||
}
|
||||
|
||||
/// Number of least significant bits to ignore.
|
||||
///
|
||||
/// Useful for generating palettes for VGA, 15-bit textures, or other retro platforms.
|
||||
pub fn set_min_posterization(&mut self, value: i32) -> liq_error {
|
||||
unsafe { ffi::liq_set_min_posterization(&mut *self.handle, value) }
|
||||
}
|
||||
|
||||
/// Returns number of bits of precision truncated
|
||||
pub fn min_posterization(&mut self) -> i32 {
|
||||
unsafe { ffi::liq_get_min_posterization(&*self.handle) }
|
||||
}
|
||||
|
||||
/// Range 0-100, roughly like JPEG.
|
||||
///
|
||||
/// If minimum quality can't be met, quantization will fail.
|
||||
///
|
||||
/// Default is min 0, max 100.
|
||||
pub fn set_quality(&mut self, min: u32, max: u32) -> liq_error {
|
||||
unsafe { ffi::liq_set_quality(&mut *self.handle, min as c_int, max as c_int) }
|
||||
}
|
||||
|
||||
/// Reads values set with `set_quality`
|
||||
pub fn quality(&mut self) -> (u32, u32) {
|
||||
unsafe {
|
||||
(ffi::liq_get_min_quality(&*self.handle) as u32,
|
||||
ffi::liq_get_max_quality(&*self.handle) as u32)
|
||||
}
|
||||
}
|
||||
|
||||
/// 1-10.
|
||||
///
|
||||
/// Faster speeds generate images of lower quality, but may be useful
|
||||
/// for real-time generation of images.
|
||||
pub fn set_speed(&mut self, value: i32) -> liq_error {
|
||||
unsafe { ffi::liq_set_speed(&mut *self.handle, value) }
|
||||
}
|
||||
|
||||
/// Move transparent color to the last entry in the palette
|
||||
///
|
||||
/// This is less efficient for PNG, but required by some broken software
|
||||
pub fn set_last_index_transparent(&mut self, value: bool) {
|
||||
unsafe { ffi::liq_set_last_index_transparent(&mut *self.handle, value as c_int) }
|
||||
}
|
||||
|
||||
/// Return currently set speed/quality trade-off setting
|
||||
pub fn speed(&mut self) -> i32 {
|
||||
unsafe { ffi::liq_get_speed(&*self.handle) }
|
||||
}
|
||||
|
||||
/// Return max number of colors set
|
||||
pub fn max_colors(&mut self) -> i32 {
|
||||
unsafe { ffi::liq_get_max_colors(&*self.handle) }
|
||||
}
|
||||
|
||||
/// Describe dimensions of a slice of RGBA pixels
|
||||
///
|
||||
/// Use 0.0 for gamma if the image is sRGB (most images are).
|
||||
pub fn new_image<'a, RGBA: Copy>(&self, bitmap: &'a [RGBA], width: usize, height: usize, gamma: f64) -> Result<Image<'a>, liq_error> {
|
||||
Image::new(self, bitmap, width, height, gamma)
|
||||
}
|
||||
|
||||
/// Stride is in pixels. Allows defining regions of larger images or images with padding without copying.
|
||||
pub fn new_image_stride<'a, RGBA: Copy>(&self, bitmap: &'a [RGBA], width: usize, height: usize, stride: usize, gamma: f64) -> Result<Image<'a>, liq_error> {
|
||||
Image::new_stride(self, bitmap, width, height, stride, gamma)
|
||||
}
|
||||
|
||||
/// Create new histogram
|
||||
///
|
||||
/// Use to make one palette suitable for many images
|
||||
pub fn new_histogram(&self) -> Histogram<'_> {
|
||||
Histogram::new(&self)
|
||||
}
|
||||
|
||||
/// Generate palette for the image
|
||||
pub fn quantize(&mut self, image: &Image<'_>) -> Result<QuantizationResult, liq_error> {
|
||||
unsafe {
|
||||
let mut h = ptr::null_mut();
|
||||
match ffi::liq_image_quantize(&*image.handle, &*self.handle, &mut h) {
|
||||
liq_error::LIQ_OK if !h.is_null() => Ok(QuantizationResult { handle: h }),
|
||||
err => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Start here: creates new handle for library configuration
|
||||
pub fn new() -> Attributes {
|
||||
Attributes::new()
|
||||
}
|
||||
|
||||
impl<'a> Histogram<'a> {
|
||||
/// Creates histogram object that will be used to collect color statistics from multiple images.
|
||||
///
|
||||
/// All options should be set on `attr` before the histogram object is created. Options changed later may not have effect.
|
||||
pub fn new(attr: &'a Attributes) -> Self {
|
||||
Histogram {
|
||||
attr,
|
||||
handle: unsafe { ffi::liq_histogram_create(&*attr.handle) },
|
||||
}
|
||||
}
|
||||
|
||||
/// "Learns" colors from the image, which will be later used to generate the palette.
|
||||
///
|
||||
/// Fixed colors added to the image are also added to the histogram. If total number of fixed colors exceeds 256, this function will fail with `LIQ_BUFFER_TOO_SMALL`.
|
||||
pub fn add_image(&mut self, image: &mut Image<'_>) -> liq_error {
|
||||
unsafe { ffi::liq_histogram_add_image(&mut *self.handle, &*self.attr.handle, &mut *image.handle) }
|
||||
}
|
||||
|
||||
/// Alternative to `add_image()`. Intead of counting colors in an image, it directly takes an array of colors and their counts.
|
||||
///
|
||||
/// This function is only useful if you already have a histogram of the image from another source.
|
||||
pub fn add_colors(&mut self, colors: &[HistogramEntry], gamma: f64) -> liq_error {
|
||||
unsafe {
|
||||
ffi::liq_histogram_add_colors(&mut *self.handle, &*self.attr.handle, colors.as_ptr(), colors.len() as c_int, gamma)
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate palette for all images/colors added to the histogram.
|
||||
///
|
||||
/// Palette generated using this function won't be improved during remapping.
|
||||
/// If you're generating palette for only one image, it's better not to use the `Histogram`.
|
||||
pub fn quantize(&mut self) -> Result<QuantizationResult, liq_error> {
|
||||
unsafe {
|
||||
let mut h = ptr::null_mut();
|
||||
match ffi::liq_histogram_quantize(&*self.handle, &*self.attr.handle, &mut h) {
|
||||
liq_error::LIQ_OK if !h.is_null() => Ok(QuantizationResult { handle: h }),
|
||||
err => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate image row on the fly
|
||||
///
|
||||
/// `output_row` is an array `width` RGBA elements wide.
|
||||
/// `y` is the row (0-indexed) to write to the `output_row`
|
||||
/// `user_data` is the data given to `Image::new_unsafe_fn()`
|
||||
pub type ConvertRowUnsafeFn<UserData> = unsafe extern "C" fn(output_row: *mut Color, y: c_int, width: c_int, user_data: *mut UserData);
|
||||
|
||||
impl<'bitmap> Image<'bitmap> {
|
||||
/// Describe dimensions of a slice of RGBA pixels.
|
||||
///
|
||||
/// `bitmap` must be either `&[u8]` or a slice with one element per pixel (`&[RGBA]`).
|
||||
///
|
||||
/// Use `0.` for gamma if the image is sRGB (most images are).
|
||||
#[inline]
|
||||
pub fn new<PixelType: Copy>(attr: &Attributes, bitmap: &'bitmap [PixelType], width: usize, height: usize, gamma: f64) -> Result<Self, liq_error> {
|
||||
Self::new_stride(attr, bitmap, width, height, width, gamma)
|
||||
}
|
||||
|
||||
/// Generate rows on demand using a callback function.
|
||||
///
|
||||
/// The callback function must be cheap (e.g. just byte-swap pixels).
|
||||
/// It will be called multiple times per row. May be called in any order from any thread.
|
||||
///
|
||||
/// The user data must be compatible with a primitive pointer
|
||||
/// (i.e. not a slice, not a Trait object. `Box` it if you must).
|
||||
pub fn new_unsafe_fn<CustomData: Send + Sync + 'bitmap>(attr: &Attributes, convert_row_fn: ConvertRowUnsafeFn<CustomData>, user_data: *mut CustomData, width: usize, height: usize, gamma: f64) -> Result<Self, liq_error> {
|
||||
unsafe {
|
||||
match ffi::liq_image_create_custom(&*attr.handle, mem::transmute(convert_row_fn), user_data as *mut _, width as c_int, height as c_int, gamma) {
|
||||
handle if !handle.is_null() => Ok(Image { handle, _marker: marker::PhantomData }),
|
||||
_ => Err(LIQ_INVALID_POINTER),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stride is in pixels. Allows defining regions of larger images or images with padding without copying.
|
||||
pub fn new_stride<PixelType: Copy>(attr: &Attributes, bitmap: &'bitmap [PixelType], width: usize, height: usize, stride: usize, gamma: f64) -> Result<Self, liq_error> {
|
||||
let bytes_per_pixel = mem::size_of::<PixelType>();
|
||||
match bytes_per_pixel {
|
||||
1 | 4 => {}
|
||||
_ => return Err(LIQ_UNSUPPORTED),
|
||||
}
|
||||
if bitmap.len() * bytes_per_pixel < (stride * height + width - stride) * 4 {
|
||||
eprintln!("Buffer length is {}×{} bytes, which is not enough for {}×{}×4 RGBA bytes", bitmap.len(), bytes_per_pixel, stride, height);
|
||||
return Err(LIQ_BUFFER_TOO_SMALL);
|
||||
}
|
||||
unsafe {
|
||||
let rows = Self::malloc_image_rows(bitmap, stride, height, bytes_per_pixel);
|
||||
match ffi::liq_image_create_rgba_rows(&*attr.handle, rows, width as c_int, height as c_int, gamma) {
|
||||
h if !h.is_null() && ffi::liq_image_set_memory_ownership(&*h, ffi::liq_ownership::LIQ_OWN_ROWS).is_ok() => {
|
||||
Ok(Image {
|
||||
handle: h,
|
||||
_marker: marker::PhantomData,
|
||||
})
|
||||
},
|
||||
_ => {
|
||||
libc::free(rows as *mut _);
|
||||
Err(LIQ_INVALID_POINTER)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// For arbitrary stride libimagequant requires rows. It's most convenient if they're allocated using libc,
|
||||
/// so they can be owned and freed automatically by the C library.
|
||||
unsafe fn malloc_image_rows<PixelType: Copy>(bitmap: &'bitmap [PixelType], stride: usize, height: usize, bytes_per_pixel: usize) -> *mut *const u8 {
|
||||
let mut byte_ptr = bitmap.as_ptr() as *const u8;
|
||||
let stride_bytes = (stride * bytes_per_pixel) as isize;
|
||||
let rows = libc::malloc(mem::size_of::<*const u8>() * height) as *mut *const u8;
|
||||
for y in 0..height as isize {
|
||||
*rows.offset(y) = byte_ptr;
|
||||
byte_ptr = byte_ptr.offset(stride_bytes);
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Width of the image in pixels
|
||||
pub fn width(&self) -> usize {
|
||||
unsafe { ffi::liq_image_get_width(&*self.handle) as usize }
|
||||
}
|
||||
|
||||
/// Height of the image in pixels
|
||||
pub fn height(&self) -> usize {
|
||||
unsafe { ffi::liq_image_get_height(&*self.handle) as usize }
|
||||
}
|
||||
|
||||
/// Reserves a color in the output palette created from this image. It behaves as if the given color was used in the image and was very important.
|
||||
///
|
||||
/// RGB values of liq_color are assumed to have the same gamma as the image.
|
||||
///
|
||||
/// It must be called before the image is quantized.
|
||||
///
|
||||
/// Returns error if more than 256 colors are added. If image is quantized to fewer colors than the number of fixed colors added, then excess fixed colors will be ignored.
|
||||
pub fn add_fixed_color(&mut self, color: ffi::liq_color) -> liq_error {
|
||||
unsafe {
|
||||
ffi::liq_image_add_fixed_color(&mut *self.handle, color)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remap pixels assuming they will be displayed on this background.
|
||||
///
|
||||
/// Pixels that match the background color will be made transparent if there's a fully transparent color available in the palette.
|
||||
///
|
||||
/// The background image's pixels must outlive this image
|
||||
pub fn set_background<'own, 'bg: 'own>(&'own mut self, background: Image<'bg>) -> Result<(), liq_error> {
|
||||
unsafe {
|
||||
ffi::liq_image_set_background(&mut *self.handle, background.into_raw()).ok()
|
||||
}
|
||||
}
|
||||
|
||||
/// Set which pixels are more important (and more likely to get a palette entry)
|
||||
///
|
||||
/// The map must be `width`×`height` pixels large. Higher numbers = more important.
|
||||
pub fn set_importance_map(&mut self, map: &[u8]) -> Result<(), liq_error> {
|
||||
unsafe {
|
||||
ffi::liq_image_set_importance_map(&mut *self.handle, map.as_ptr() as *mut _, map.len(), ffi::liq_ownership::LIQ_COPY_PIXELS).ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn into_raw(mut self) -> *mut ffi::liq_image {
|
||||
let handle = self.handle;
|
||||
self.handle = ptr::null_mut();
|
||||
handle
|
||||
}
|
||||
}
|
||||
|
||||
impl QuantizationResult {
|
||||
/// Set to 1.0 to get nice smooth image
|
||||
pub fn set_dithering_level(&mut self, value: f32) -> liq_error {
|
||||
unsafe { ffi::liq_set_dithering_level(&mut *self.handle, value) }
|
||||
}
|
||||
|
||||
/// The default is sRGB gamma (~1/2.2)
|
||||
pub fn set_output_gamma(&mut self, value: f64) -> liq_error {
|
||||
unsafe { ffi::liq_set_output_gamma(&mut *self.handle, value) }
|
||||
}
|
||||
|
||||
/// Approximate gamma correction value used for the output
|
||||
///
|
||||
/// Colors are converted from input gamma to this gamma
|
||||
pub fn output_gamma(&mut self) -> f64 {
|
||||
unsafe { ffi::liq_get_output_gamma(&*self.handle) }
|
||||
}
|
||||
|
||||
/// Number 0-100 guessing how nice the input image will look if remapped to this palette
|
||||
pub fn quantization_quality(&self) -> i32 {
|
||||
unsafe { ffi::liq_get_quantization_quality(&*self.handle) as i32 }
|
||||
}
|
||||
|
||||
/// Approximate mean square error of the palette
|
||||
pub fn quantization_error(&self) -> Option<f64> {
|
||||
match unsafe { ffi::liq_get_quantization_error(&*self.handle) } {
|
||||
x if x < 0. => None,
|
||||
x => Some(x),
|
||||
}
|
||||
}
|
||||
|
||||
/// Final palette
|
||||
///
|
||||
/// It's slighly better if you get palette from the `remapped()` call instead
|
||||
pub fn palette(&mut self) -> Vec<Color> {
|
||||
unsafe {
|
||||
let pal = &*ffi::liq_get_palette(&mut *self.handle);
|
||||
pal.entries.iter().cloned().take(pal.count as usize).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Remap image
|
||||
///
|
||||
/// Returns palette and 1-byte-per-pixel uncompresed bitmap
|
||||
pub fn remapped(&mut self, image: &mut Image<'_>) -> Result<(Vec<Color>, Vec<u8>), liq_error> {
|
||||
let len = image.width() * image.height();
|
||||
let mut buf = Vec::with_capacity(len);
|
||||
unsafe {
|
||||
buf.set_len(len); // Creates uninitialized buffer
|
||||
match ffi::liq_write_remapped_image(&mut *self.handle, &mut *image.handle, buf.as_mut_ptr(), buf.len()) {
|
||||
LIQ_OK => Ok((self.palette(), buf)),
|
||||
err => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for QuantizationResult {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "QuantizationResult(q={})", self.quantization_quality())
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for Attributes {}
|
||||
unsafe impl Send for QuantizationResult {}
|
||||
unsafe impl<'bitmap> Send for Image<'bitmap> {}
|
||||
unsafe impl<'a> Send for Histogram<'a> {}
|
||||
|
||||
#[test]
|
||||
fn takes_rgba() {
|
||||
let liq = Attributes::new();
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct RGBA {r:u8, g:u8, b:u8, a:u8};
|
||||
let img = vec![RGBA {r:0, g:0, b:0, a:0}; 8];
|
||||
|
||||
|
||||
liq.new_image(&img, 1, 1, 0.0).unwrap();
|
||||
liq.new_image(&img, 4, 2, 0.0).unwrap();
|
||||
liq.new_image(&img, 8, 1, 0.0).unwrap();
|
||||
assert!(liq.new_image(&img, 9, 1, 0.0).is_err());
|
||||
assert!(liq.new_image(&img, 4, 3, 0.0).is_err());
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct RGB {r:u8, g:u8, b:u8};
|
||||
let badimg = vec![RGB {r:0, g:0, b:0}; 8];
|
||||
assert!(liq.new_image(&badimg, 1, 1, 0.0).is_err());
|
||||
assert!(liq.new_image(&badimg, 100, 100, 0.0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram() {
|
||||
let attr = Attributes::new();
|
||||
let mut hist = attr.new_histogram();
|
||||
|
||||
let bitmap1 = vec![0u8; 4];
|
||||
let mut image1 = attr.new_image(&bitmap1[..], 1, 1, 0.0).unwrap();
|
||||
hist.add_image(&mut image1);
|
||||
|
||||
let bitmap2 = vec![255u8; 4];
|
||||
let mut image2 = attr.new_image(&bitmap2[..], 1, 1, 0.0).unwrap();
|
||||
hist.add_image(&mut image2);
|
||||
|
||||
hist.add_colors(&[HistogramEntry{
|
||||
color: Color::new(255,128,255,128),
|
||||
count: 10,
|
||||
}], 0.0);
|
||||
|
||||
let mut res = hist.quantize().unwrap();
|
||||
let pal = res.palette();
|
||||
assert_eq!(3, pal.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn poke_it() {
|
||||
let width = 10usize;
|
||||
let height = 10usize;
|
||||
let mut fakebitmap = vec![255u8; 4*width*height];
|
||||
|
||||
fakebitmap[0] = 0x55;
|
||||
fakebitmap[1] = 0x66;
|
||||
fakebitmap[2] = 0x77;
|
||||
|
||||
// Configure the library
|
||||
let mut liq = Attributes::new();
|
||||
liq.set_speed(5);
|
||||
liq.set_quality(70, 99);
|
||||
liq.set_min_posterization(1);
|
||||
assert_eq!(1, liq.min_posterization());
|
||||
liq.set_min_posterization(0);
|
||||
|
||||
// Describe the bitmap
|
||||
let ref mut img = liq.new_image(&fakebitmap[..], width, height, 0.0).unwrap();
|
||||
|
||||
// The magic happens in quantize()
|
||||
let mut res = match liq.quantize(img) {
|
||||
Ok(res) => res,
|
||||
Err(err) => panic!("Quantization failed, because: {:?}", err),
|
||||
};
|
||||
|
||||
// Enable dithering for subsequent remappings
|
||||
res.set_dithering_level(1.0);
|
||||
|
||||
// You can reuse the result to generate several images with the same palette
|
||||
let (palette, pixels) = res.remapped(img).unwrap();
|
||||
|
||||
assert_eq!(width * height, pixels.len());
|
||||
assert_eq!(100, res.quantization_quality());
|
||||
assert_eq!(Color { r: 255, g: 255, b: 255, a: 255 }, palette[0]);
|
||||
assert_eq!(Color { r: 0x55, g: 0x66, b: 0x77, a: 255 }, palette[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_importance_map() {
|
||||
use crate::ffi::liq_color as RGBA;
|
||||
let mut liq = new();
|
||||
let bitmap = &[RGBA::new(255, 0, 0, 255), RGBA::new(0u8, 0, 255, 255)];
|
||||
let ref mut img = liq.new_image(&bitmap[..], 2, 1, 0.).unwrap();
|
||||
let map = &[255, 0];
|
||||
img.set_importance_map(map).unwrap();
|
||||
let mut res = liq.quantize(img).unwrap();
|
||||
let pal = res.palette();
|
||||
assert_eq!(1, pal.len());
|
||||
assert_eq!(bitmap[0], pal[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread() {
|
||||
let liq = Attributes::new();
|
||||
std::thread::spawn(move || {
|
||||
let b = vec![0u8;4];
|
||||
liq.new_image(&b, 1, 1, 0.).unwrap();
|
||||
}).join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_test() {
|
||||
let mut called = 0;
|
||||
let mut res = {
|
||||
let mut a = new();
|
||||
unsafe extern "C" fn get_row(output_row: *mut Color, y: c_int, width: c_int, user_data: *mut i32) {
|
||||
assert!(y >= 0 && y < 5);
|
||||
assert_eq!(123, width);
|
||||
for i in 0..width as isize {
|
||||
let n = i as u8;
|
||||
*output_row.offset(i as isize) = Color::new(n,n,n,n);
|
||||
}
|
||||
*user_data += 1;
|
||||
}
|
||||
let mut img = Image::new_unsafe_fn(&a, get_row, &mut called, 123, 5, 0.).unwrap();
|
||||
a.quantize(&mut img).unwrap()
|
||||
};
|
||||
assert!(called > 5 && called < 50);
|
||||
assert_eq!(123, res.palette().len());
|
||||
}
|
63
CloverApp/libimagequant-2.12.6/rust-sys/build.rs
Normal file
63
CloverApp/libimagequant-2.12.6/rust-sys/build.rs
Normal file
@ -0,0 +1,63 @@
|
||||
//! This is a build script for Cargo https://crates.io/
|
||||
//! It produces a static library that can be used by C or Rust.
|
||||
|
||||
extern crate cc;
|
||||
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::fs::canonicalize;
|
||||
|
||||
fn main() {
|
||||
let mut cc = cc::Build::new();
|
||||
let compiler = cc.get_compiler();
|
||||
cc.warnings(false);
|
||||
|
||||
if env::var("PROFILE").map(|p|p != "debug").unwrap_or(true) {
|
||||
cc.define("NDEBUG", Some("1"));
|
||||
} else {
|
||||
cc.define("DEBUG", Some("1"));
|
||||
}
|
||||
|
||||
if cfg!(feature = "openmp") {
|
||||
cc.flag(&env::var("DEP_OPENMP_FLAG").unwrap());
|
||||
}
|
||||
|
||||
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").expect("Needs CARGO_CFG_TARGET_ARCH");
|
||||
if target_arch =="x86_64" ||
|
||||
(target_arch == "x86" && cfg!(feature = "sse")) {
|
||||
cc.flag(if compiler.is_like_msvc() {"/arch:SSE2"} else {"-msse"});
|
||||
cc.define("USE_SSE", Some("1"));
|
||||
}
|
||||
|
||||
let outdated_c_compiler = env::var("TARGET").unwrap().contains("windows-msvc");
|
||||
let has_msvc_files = PathBuf::from("msvc-dist/libimagequant.c").exists();
|
||||
|
||||
if outdated_c_compiler && has_msvc_files {
|
||||
println!("cargo:include={}", canonicalize("msvc-dist").unwrap().display());
|
||||
cc.file("msvc-dist/libimagequant.c")
|
||||
.file("msvc-dist/nearest.c")
|
||||
.file("msvc-dist/kmeans.c")
|
||||
.file("msvc-dist/mediancut.c")
|
||||
.file("msvc-dist/mempool.c")
|
||||
.file("msvc-dist/pam.c")
|
||||
.file("msvc-dist/blur.c");
|
||||
} else {
|
||||
// This is so that I don't forget to publish MSVC version as well
|
||||
if !has_msvc_files {
|
||||
println!("cargo:warning=msvc-dist/ directory not present. MSVC builds may fail");
|
||||
}
|
||||
println!("cargo:include={}", canonicalize(".").unwrap().display());
|
||||
if !compiler.is_like_msvc() {
|
||||
cc.flag("-std=c99");
|
||||
}
|
||||
cc.file("libimagequant.c")
|
||||
.file("nearest.c")
|
||||
.file("kmeans.c")
|
||||
.file("mediancut.c")
|
||||
.file("mempool.c")
|
||||
.file("pam.c")
|
||||
.file("blur.c");
|
||||
}
|
||||
|
||||
cc.compile("libimagequant.a");
|
||||
}
|
307
CloverApp/libimagequant-2.12.6/rust-sys/libimagequant.rs
Normal file
307
CloverApp/libimagequant-2.12.6/rust-sys/libimagequant.rs
Normal file
@ -0,0 +1,307 @@
|
||||
//! Small, portable C library for high-quality conversion of RGBA images to 8-bit indexed-color (palette) images.
|
||||
//! It's powering [pngquant2](https://pngquant.org).
|
||||
//!
|
||||
//! This is a low-level crate exposing a C API. If you're looking for a Rust library, see [imagequant](https://crates.io/crates/imagequant).
|
||||
//!
|
||||
//! ## License
|
||||
//!
|
||||
//! Libimagequant is dual-licensed:
|
||||
//!
|
||||
//! * For Free/Libre Open Source Software it's available under [GPL v3 or later](https://raw.github.com/ImageOptim/libimagequant/master/COPYRIGHT) with additional copyright notices for older parts of the code.
|
||||
//!
|
||||
//! * For use in non-GPL software (e.g. closed-source or App Store distribution) please ask kornel@pngquant.org for a commercial license.
|
||||
//!
|
||||
//! ## Overview
|
||||
//!
|
||||
//! The basic flow is:
|
||||
//!
|
||||
//! 1. Create attributes object and configure the library.
|
||||
//! 2. Create image object from RGBA pixels or data source.
|
||||
//! 3. Perform quantization (generate palette).
|
||||
//! 4. Store remapped image and final palette.
|
||||
//! 5. Free memory.
|
||||
//!
|
||||
//! Please note that libimagequant only handles raw uncompressed arrays of pixels in memory and is completely independent of any file format.
|
||||
//!
|
||||
//! There are 3 ways to create image object for quantization:
|
||||
//!
|
||||
//! * `liq_image_create_rgba()` for simple, contiguous RGBA pixel arrays (width×height×4 bytes large bitmap).
|
||||
//! * `liq_image_create_rgba_rows()` for non-contiguous RGBA pixel arrays (that have padding between rows or reverse order, e.g. BMP).
|
||||
//! * `liq_image_create_custom()` for RGB, ABGR, YUV and all other formats that can be converted on-the-fly to RGBA (you have to supply the conversion function).
|
||||
//!
|
||||
//! Note that "image" here means raw uncompressed pixels. If you have a compressed image file, such as PNG, you must use another library (e.g. lodepng) to decode it first.
|
||||
|
||||
#![allow(non_camel_case_types)]
|
||||
|
||||
#[cfg(feature = "openmp")]
|
||||
extern crate openmp_sys;
|
||||
|
||||
use std::os::raw::{c_int, c_uint, c_char, c_void};
|
||||
use std::error;
|
||||
use std::fmt;
|
||||
use std::error::Error;
|
||||
|
||||
pub enum liq_attr {}
|
||||
pub enum liq_image {}
|
||||
pub enum liq_result {}
|
||||
pub enum liq_histogram {}
|
||||
pub type liq_color = rgb::RGBA8;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
||||
pub enum liq_error {
|
||||
LIQ_OK = 0,
|
||||
LIQ_QUALITY_TOO_LOW = 99,
|
||||
LIQ_VALUE_OUT_OF_RANGE = 100,
|
||||
LIQ_OUT_OF_MEMORY,
|
||||
LIQ_ABORTED,
|
||||
LIQ_BITMAP_NOT_AVAILABLE,
|
||||
LIQ_BUFFER_TOO_SMALL,
|
||||
LIQ_INVALID_POINTER,
|
||||
LIQ_UNSUPPORTED,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone)]
|
||||
pub enum liq_ownership {
|
||||
LIQ_OWN_ROWS = 4,
|
||||
LIQ_OWN_PIXELS = 8,
|
||||
LIQ_COPY_PIXELS = 16,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub struct liq_palette {
|
||||
pub count: c_int,
|
||||
pub entries: [liq_color; 256],
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct liq_histogram_entry {
|
||||
pub color: liq_color,
|
||||
pub count: c_uint,
|
||||
}
|
||||
|
||||
impl error::Error for liq_error {
|
||||
fn description(&self) -> &str {
|
||||
match *self {
|
||||
liq_error::LIQ_OK => "OK",
|
||||
liq_error::LIQ_QUALITY_TOO_LOW => "LIQ_QUALITY_TOO_LOW",
|
||||
liq_error::LIQ_VALUE_OUT_OF_RANGE => "VALUE_OUT_OF_RANGE",
|
||||
liq_error::LIQ_OUT_OF_MEMORY => "OUT_OF_MEMORY",
|
||||
liq_error::LIQ_ABORTED => "LIQ_ABORTED",
|
||||
liq_error::LIQ_BITMAP_NOT_AVAILABLE => "BITMAP_NOT_AVAILABLE",
|
||||
liq_error::LIQ_BUFFER_TOO_SMALL => "BUFFER_TOO_SMALL",
|
||||
liq_error::LIQ_INVALID_POINTER => "INVALID_POINTER",
|
||||
liq_error::LIQ_UNSUPPORTED => "LIQ_UNSUPPORTED",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for liq_error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.description())
|
||||
}
|
||||
}
|
||||
|
||||
impl liq_error {
|
||||
#[inline]
|
||||
pub fn is_ok(&self) -> bool {
|
||||
*self == liq_error::LIQ_OK
|
||||
}
|
||||
|
||||
pub fn is_err(&self) -> bool {
|
||||
!self.is_ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn ok(&self) -> Result<(), liq_error> {
|
||||
match *self {
|
||||
liq_error::LIQ_OK => Ok(()),
|
||||
e => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn ok_or<E>(self, err: E) -> Result<(), E> {
|
||||
if self.is_ok() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unwrap(&self) {
|
||||
assert!(self.is_ok(), "{}", self);
|
||||
}
|
||||
|
||||
pub fn expect(&self, msg: &str) {
|
||||
assert!(self.is_ok(), "{}", msg);
|
||||
}
|
||||
}
|
||||
|
||||
pub type liq_log_callback_function = Option<unsafe extern "C" fn(arg1: &liq_attr, message: *const c_char, user_info: *mut c_void)>;
|
||||
pub type liq_log_flush_callback_function = Option<unsafe extern "C" fn(arg1: &liq_attr, user_info: *mut c_void)>;
|
||||
pub type liq_progress_callback_function = Option<unsafe extern "C" fn(progress_percent: f32, user_info: *mut c_void) -> c_int>;
|
||||
pub type liq_image_get_rgba_row_callback = unsafe extern "C" fn(row_out: *mut liq_color, row: c_int, width: c_int, user_info: *mut c_void);
|
||||
|
||||
#[link(name="imagequant", kind="static")]
|
||||
extern "C" {
|
||||
|
||||
/// Returns object that will hold initial settings (attributes) for the library.
|
||||
///
|
||||
/// The object should be freed using `liq_attr_destroy()` after it's no longer needed.
|
||||
/// Returns `NULL` in the unlikely case that the library cannot run on the current machine (e.g. the library has been compiled for SSE-capable x86 CPU and run on VIA C3 CPU).
|
||||
pub fn liq_attr_create() -> *mut liq_attr;
|
||||
pub fn liq_attr_copy(orig: &liq_attr) -> *mut liq_attr;
|
||||
pub fn liq_attr_destroy(attr: &mut liq_attr);
|
||||
|
||||
/// Specifies maximum number of colors to use.
|
||||
///
|
||||
/// The default is 256. Instead of setting a fixed limit it's better to use `liq_set_quality()`.
|
||||
/// The first argument is attributes object from `liq_attr_create()`.
|
||||
/// Returns `LIQ_VALUE_OUT_OF_RANGE` if number of colors is outside the range 2-256.
|
||||
pub fn liq_set_max_colors(attr: &mut liq_attr, colors: c_int) -> liq_error;
|
||||
pub fn liq_get_max_colors(attr: &liq_attr) -> c_int;
|
||||
pub fn liq_set_speed(attr: &mut liq_attr, speed: c_int) -> liq_error;
|
||||
pub fn liq_get_speed(attr: &liq_attr) -> c_int;
|
||||
pub fn liq_set_min_posterization(attr: &mut liq_attr, bits: c_int) -> liq_error;
|
||||
pub fn liq_get_min_posterization(attr: &liq_attr) -> c_int;
|
||||
/// Quality is in range `0` (worst) to `100` (best) and values are analoguous to JPEG quality (i.e. `80` is usually good enough).
|
||||
///
|
||||
/// Quantization will attempt to use the lowest number of colors needed to achieve `maximum` quality. `maximum` value of `100` is the default and means conversion as good as possible.
|
||||
/// If it's not possible to convert the image with at least `minimum` quality (i.e. 256 colors is not enough to meet the minimum quality), then `liq_image_quantize()` will fail. The default minumum is `0` (proceeds regardless of quality).
|
||||
/// Quality measures how well the generated palette fits image given to `liq_image_quantize()`. If a different image is remapped with `liq_write_remapped_image()` then actual quality may be different.
|
||||
/// Regardless of the quality settings the number of colors won't exceed the maximum (see `liq_set_max_colors()`).
|
||||
/// The first argument is attributes object from `liq_attr_create()`.
|
||||
///
|
||||
/// Returns `LIQ_VALUE_OUT_OF_RANGE` if target is lower than minimum or any of them is outside the 0-100 range.
|
||||
/// Returns `LIQ_INVALID_POINTER` if `attr` appears to be invalid.
|
||||
pub fn liq_set_quality(attr: &mut liq_attr, minimum: c_int, maximum: c_int) -> liq_error;
|
||||
pub fn liq_get_min_quality(attr: &liq_attr) -> c_int;
|
||||
pub fn liq_get_max_quality(attr: &liq_attr) -> c_int;
|
||||
pub fn liq_set_last_index_transparent(attr: &mut liq_attr, is_last: c_int);
|
||||
|
||||
pub fn liq_image_create_rgba_rows(attr: &liq_attr, rows: *const *const u8, width: c_int, height: c_int, gamma: f64) -> *mut liq_image;
|
||||
/// Creates an object that represents the image pixels to be used for quantization and remapping.
|
||||
///
|
||||
/// The pixel array must be contiguous run of RGBA pixels (alpha is the last component, 0 = transparent, 255 = opaque).
|
||||
///
|
||||
/// The first argument is attributes object from `liq_attr_create()`. The same `attr` object should be used for the entire process, from creation of images to quantization.
|
||||
///
|
||||
/// The `pixels` array must not be modified or freed until this object is freed with `liq_image_destroy()`. See also `liq_image_set_memory_ownership()`.
|
||||
///
|
||||
/// `width` and `height` are dimensions in pixels. An image 10x10 pixel large will need a 400-byte array.
|
||||
///
|
||||
/// `gamma` can be `0` for images with the typical 1/2.2 [gamma](https://en.wikipedia.org/wiki/Gamma_correction).
|
||||
/// Otherwise `gamma` must be > 0 and < 1, e.g. `0.45455` (1/2.2) or `0.55555` (1/1.8). Generated palette will use the same gamma unless `liq_set_output_gamma()` is used. If `liq_set_output_gamma` is not used, then it only affects whether brighter or darker areas of the image will get more palette colors allocated.
|
||||
///
|
||||
/// Returns `NULL` on failure, e.g. if `pixels` is `NULL` or `width`/`height` is <= 0.
|
||||
pub fn liq_image_create_rgba(attr: &liq_attr, bitmap: *const u8, width: c_int, height: c_int, gamma: f64) -> *mut liq_image;
|
||||
/// unsafe: It will crash if the owned memory wasn't allocated using `libc::malloc()` (or whatever allocator C side is using)
|
||||
pub fn liq_image_set_memory_ownership(image: &liq_image, own: liq_ownership) -> liq_error;
|
||||
|
||||
pub fn liq_set_log_callback(arg1: &mut liq_attr, arg2: liq_log_callback_function, user_info: *mut c_void);
|
||||
pub fn liq_set_log_flush_callback(arg1: &mut liq_attr, arg2: liq_log_flush_callback_function, user_info: *mut c_void);
|
||||
pub fn liq_attr_set_progress_callback(arg1: &mut liq_attr, arg2: liq_progress_callback_function, user_info: *mut c_void);
|
||||
pub fn liq_result_set_progress_callback(arg1: &mut liq_result, arg2: liq_progress_callback_function, user_info: *mut c_void);
|
||||
pub fn liq_image_create_custom(attr: &liq_attr, row_callback: liq_image_get_rgba_row_callback, user_info: *mut c_void, width: c_int, height: c_int, gamma: f64) -> *mut liq_image;
|
||||
/// Remap assuming the image will be always presented exactly on top of this background.
|
||||
///
|
||||
/// Takes ownership of the background image (i.e. do NOT use it afterwards, do NOT call liq_image_destroy on it).
|
||||
///
|
||||
/// The background must have the same size. The foreground image must have a transparent color.
|
||||
pub fn liq_image_set_background(img: &mut liq_image, background: *mut liq_image) -> liq_error;
|
||||
pub fn liq_image_set_importance_map(img: &mut liq_image, buffer: *mut u8, buffer_size: usize, own: liq_ownership) -> liq_error;
|
||||
pub fn liq_image_add_fixed_color(img: &mut liq_image, color: liq_color) -> liq_error;
|
||||
pub fn liq_image_get_width(img: &liq_image) -> c_int;
|
||||
pub fn liq_image_get_height(img: &liq_image) -> c_int;
|
||||
pub fn liq_image_destroy(img: &mut liq_image);
|
||||
|
||||
pub fn liq_histogram_create(attr: &liq_attr) -> *mut liq_histogram;
|
||||
pub fn liq_histogram_add_image(hist: &mut liq_histogram, attr: &liq_attr, image: &mut liq_image) -> liq_error;
|
||||
pub fn liq_histogram_add_colors(hist: &mut liq_histogram, attr: &liq_attr, entries: *const liq_histogram_entry, num_entries: c_int, gamma: f64) -> liq_error;
|
||||
pub fn liq_histogram_add_fixed_color(hist: &mut liq_histogram, color: liq_color) -> liq_error;
|
||||
pub fn liq_histogram_destroy(hist: &mut liq_histogram);
|
||||
|
||||
/// Performs quantization (palette generation) based on settings in `attr` (from `liq_attr_create()`) and pixels of the image.
|
||||
///
|
||||
/// Returns `LIQ_OK` if quantization succeeds and sets `liq_result` pointer in `out_result`. The last argument is used for receiving the `result` object:
|
||||
///
|
||||
/// liq_result *result;
|
||||
/// if (LIQ_OK == liq_image_quantize(img, attr, &result)) { // Note &result
|
||||
/// // result pointer is valid here
|
||||
/// }
|
||||
///
|
||||
/// Returns `LIQ_QUALITY_TOO_LOW` if quantization fails due to limit set in `liq_set_quality()`.
|
||||
///
|
||||
/// See `liq_write_remapped_image()`.
|
||||
///
|
||||
/// If you want to generate one palette for multiple images at once, see `liq_histogram_create()`.
|
||||
pub fn liq_quantize_image(options: &liq_attr, input_image: &liq_image) -> *mut liq_result;
|
||||
pub fn liq_histogram_quantize(input_hist: &liq_histogram, options: &liq_attr, result_output: &mut *mut liq_result) -> liq_error;
|
||||
pub fn liq_image_quantize(input_image: &liq_image, options: &liq_attr, result_output: &mut *mut liq_result) -> liq_error;
|
||||
/// Enables/disables dithering in `liq_write_remapped_image()`.
|
||||
///
|
||||
/// Dithering level must be between `0` and `1` (inclusive). Dithering level `0` enables fast non-dithered remapping. Otherwise a variation of Floyd-Steinberg error diffusion is used.
|
||||
///
|
||||
/// Precision of the dithering algorithm depends on the speed setting, see `liq_set_speed()`.
|
||||
///
|
||||
/// Returns `LIQ_VALUE_OUT_OF_RANGE` if the dithering level is outside the 0-1 range.
|
||||
pub fn liq_set_dithering_level(res: &mut liq_result, dither_level: f32) -> liq_error;
|
||||
pub fn liq_set_output_gamma(res: &mut liq_result, gamma: f64) -> liq_error;
|
||||
pub fn liq_get_output_gamma(result: &liq_result) -> f64;
|
||||
/// Returns pointer to palette optimized for image that has been quantized or remapped
|
||||
/// (final refinements are applied to the palette during remapping).
|
||||
///
|
||||
/// It's valid to call this method before remapping, if you don't plan to remap any images or want to use same palette for multiple images.
|
||||
///
|
||||
/// `liq_palette->count` contains number of colors (up to 256), `liq_palette->entries[n]` contains RGBA value for nth palette color.
|
||||
pub fn liq_get_palette<'a>(result: &'a mut liq_result) -> &'a liq_palette;
|
||||
/// Remaps the image to palette and writes its pixels to the given buffer, 1 pixel per byte.
|
||||
///
|
||||
/// The buffer must be large enough to fit the entire image, i.e. width×height bytes large. For safety, pass the size of the buffer as `buffer_size`.
|
||||
///
|
||||
/// For best performance call `liq_get_palette()` *after* this function, as palette is improved during remapping (except when `liq_histogram_quantize()` is used).
|
||||
///
|
||||
/// Returns `LIQ_BUFFER_TOO_SMALL` if given size of the buffer is not enough to fit the entire image.
|
||||
///
|
||||
/// int buffer_size = width*height;
|
||||
/// char *buffer = malloc(buffer_size);
|
||||
/// if (LIQ_OK == liq_write_remapped_image(result, input_image, buffer, buffer_size)) {
|
||||
/// liq_palette *pal = liq_get_palette(result);
|
||||
/// // save image
|
||||
/// }
|
||||
///
|
||||
/// See `liq_get_palette()`.
|
||||
///
|
||||
/// The buffer is assumed to be contiguous, with rows ordered from top to bottom, and no gaps between rows. If you need to write rows with padding or upside-down order, then use `liq_write_remapped_image_rows()`.
|
||||
///
|
||||
/// Please note that it only writes raw uncompressed pixels to memory. It does not perform any PNG compression. If you'd like to create a PNG file then you need to pass the raw pixel data to another library, e.g. libpng or lodepng. See `rwpng.c` in `pngquant` project for an example how to do that.
|
||||
pub fn liq_write_remapped_image(result: &mut liq_result, input_image: &mut liq_image, buffer: *mut u8, buffer_size: usize) -> liq_error;
|
||||
pub fn liq_write_remapped_image_rows(result: &mut liq_result, input_image: &mut liq_image, row_pointers: *const *mut u8) -> liq_error;
|
||||
pub fn liq_get_quantization_error(result: &liq_result) -> f64;
|
||||
pub fn liq_get_quantization_quality(result: &liq_result) -> c_int;
|
||||
|
||||
pub fn liq_result_destroy(res: &mut liq_result);
|
||||
pub fn liq_get_remapping_error(result: &liq_result) -> f64;
|
||||
pub fn liq_get_remapping_quality(result: &liq_result) -> c_int;
|
||||
pub fn liq_version() -> c_int;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_and_runs() {
|
||||
use std::ptr;
|
||||
unsafe {
|
||||
assert!(liq_version() >= 20901);
|
||||
let attr = liq_attr_create();
|
||||
assert!(!attr.is_null());
|
||||
let hist = liq_histogram_create(&*attr);
|
||||
assert!(!hist.is_null());
|
||||
let mut res = ptr::null_mut();
|
||||
liq_histogram_quantize(&*hist, &*attr, &mut res);
|
||||
assert!(res.is_null());
|
||||
liq_histogram_destroy(&mut *hist);
|
||||
liq_attr_destroy(&mut *attr);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user