-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathCompressorFactory.java
More file actions
377 lines (329 loc) · 14.3 KB
/
CompressorFactory.java
File metadata and controls
377 lines (329 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
*
* MIT License
*
* Copyright (c) 2020. Brockmann Consult GmbH (info@brockmann-consult.de)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package com.bc.zarr;
import com.sun.jna.ptr.NativeLongByReference;
import org.blosc.BufferSizes;
import org.blosc.IBloscDll;
import org.blosc.JBlosc;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
public class CompressorFactory {
public final static Compressor nullCompressor = new NullCompressor();
/**
* @return the properties of the default compressor as a key/value map.
*/
public static Map<String, Object> getDefaultCompressorProperties() {
final Map<String, Object> map = new HashMap<>();
/* zlib defaults */
// map.put("id", "zlib");
// map.put("level", 1);
/* blosc defaults */
map.put("id", "blosc");
map.putAll(BloscCompressor.defaultProperties);
return map;
}
/**
* @return a new Compressor instance using the method {@link #create(Map properties)} with {@link #getDefaultCompressorProperties()}.
*/
public static Compressor createDefaultCompressor() {
return create(getDefaultCompressorProperties());
}
/**
* Creates a new {@link Compressor} instance according to the given properties.
*
* @param properties a Map containing the properties to create a compressor
* @return a new Compressor instance according to the properties
* @throws IllegalArgumentException If it is not able to create a Compressor.
*/
public static Compressor create(Map<String, Object> properties) {
final String id = (String) properties.get("id");
return create(id, properties);
}
/**
* Creates a new {@link Compressor} instance according to the id and the given properties.
*
* @param id the type of the compression algorithm
* @param keyValuePair an even count of key value pairs defining the compressor specific properties
* @return a new Compressor instance according to the id and the properties
* @throws IllegalArgumentException If it is not able to create a Compressor.
*/
public static Compressor create(String id, Object... keyValuePair) {
if (keyValuePair.length % 2 != 0) {
throw new IllegalArgumentException("The count of keyValuePair arguments must be an even count.");
}
return create(id, toMap(keyValuePair));
}
/**
* Creates a new {@link Compressor} instance according to the id and the given properties.
*
* @param id the type of the compression algorithm
* @param properties a Map containing the compressor specific properties
* @return a new Compressor instance according to the id and the properties
* @throws IllegalArgumentException If it is not able to create a Compressor.
*/
public static Compressor create(String id, Map<String, Object> properties) {
if ("null".equals(id)) {
return nullCompressor;
}
if ("zlib".equals(id)) {
return new ZlibCompressor(properties);
}
if ("blosc".equals(id)) {
return new BloscCompressor(properties);
}
throw new IllegalArgumentException("Compressor id:'" + id + "' not supported.");
}
private static Map<String, Object> toMap(Object... args) {
final HashMap<String, Object> map = new HashMap<>();
for (int i = 0; i < args.length; i += 2) {
String key = (String) args[i];
Object val = args[i + 1];
map.put(key, val);
}
return map;
}
private static class NullCompressor extends Compressor {
@Override
public String getId() {
return null;
}
@Override
public String toString() {
return getId();
}
@Override
public void compress(InputStream is, OutputStream os) throws IOException {
passThrough(is, os);
}
@Override
public void uncompress(InputStream is, OutputStream os) throws IOException {
passThrough(is, os);
}
}
private static class ZlibCompressor extends Compressor {
private final int level;
private ZlibCompressor(Map<String, Object> map) {
final Object levelObj = map.get("level");
if (levelObj == null) {
this.level = 1; //default value
} else if (levelObj instanceof String) {
this.level = Integer.parseInt((String) levelObj);
} else {
this.level = ((Number) levelObj).intValue();
}
validateLevel();
}
@Override
public String toString() {
return "compressor=" + getId() + "/level=" + level;
}
private void validateLevel() {
// see new Deflater().setLevel(level);
if (level < 0 || level > 9) {
throw new IllegalArgumentException("Invalid compression level: " + level);
}
}
@Override
public String getId() {
return "zlib";
}
// this getter is needed for JSON serialisation
public int getLevel() {
return level;
}
@Override
public void compress(InputStream is, OutputStream os) throws IOException {
try (final DeflaterOutputStream dos = new DeflaterOutputStream(os, new Deflater(level))) {
passThrough(is, dos);
}
}
@Override
public void uncompress(InputStream is, OutputStream os) throws IOException {
try (final InflaterInputStream iis = new InflaterInputStream(is, new Inflater())) {
passThrough(iis, os);
}
}
}
static class BloscCompressor extends Compressor {
final static int AUTOSHUFFLE = -1;
final static int NOSHUFFLE = 0;
final static int BYTESHUFFLE = 1;
final static int BITSHUFFLE = 2;
public final static String keyCname = "cname";
public final static String defaultCname = "lz4";
public final static String keyClevel = "clevel";
public final static int defaultCLevel = 5;
public final static String keyShuffle = "shuffle";
public final static int defaultShuffle = BYTESHUFFLE;
public final static String keyBlocksize = "blocksize";
public final static int defaultBlocksize = 0;
public final static String keyNumThreads = "nthreads";
public final static int defaultNumThreads = 1;
public final static int[] supportedShuffle = new int[]{/*AUTOSHUFFLE, */NOSHUFFLE, BYTESHUFFLE, BITSHUFFLE};
public final static String[] supportedCnames = new String[]{"zstd", "blosclz", defaultCname, "lz4hc", "zlib"/*, "snappy"*/};
public final static Map<String, Object> defaultProperties = Collections
.unmodifiableMap(new HashMap<String, Object>() {{
put(keyCname, defaultCname);
put(keyClevel, defaultCLevel);
put(keyShuffle, defaultShuffle);
put(keyBlocksize, defaultBlocksize);
put(keyNumThreads, defaultNumThreads);
}});
private final int clevel;
private final int blocksize;
private final int shuffle;
private final String cname;
private final int nthreads;
private BloscCompressor(Map<String, Object> map) {
final Object cnameObj = map.get(keyCname);
if (cnameObj == null) {
cname = defaultCname;
} else {
cname = (String) cnameObj;
}
if (Arrays.stream(supportedCnames).noneMatch(cname::equals)) {
throw new IllegalArgumentException(
"blosc: compressor not supported: '" + cname + "'; expected one of " + Arrays.toString(supportedCnames));
}
final Object clevelObj = map.get(keyClevel);
if (clevelObj == null) {
clevel = defaultCLevel;
} else if (clevelObj instanceof String) {
clevel = Integer.parseInt((String) clevelObj);
} else {
clevel = ((Number) clevelObj).intValue();
}
if (clevel < 0 || clevel > 9) {
throw new IllegalArgumentException("blosc: clevel parameter must be between 0 and 9 but was: " + clevel);
}
final Object shuffleObj = map.get(keyShuffle);
if (shuffleObj == null) {
this.shuffle = defaultShuffle;
} else if (shuffleObj instanceof String) {
this.shuffle = Integer.parseInt((String) shuffleObj);
} else {
this.shuffle = ((Number) shuffleObj).intValue();
}
final String[] supportedShuffleNames = new String[]{/*"-1 (AUTOSHUFFLE)", */"0 (NOSHUFFLE)", "1 (BYTESHUFFLE)", "2 (BITSHUFFLE)"};
if (Arrays.stream(supportedShuffle).noneMatch(value -> value == shuffle)) {
throw new IllegalArgumentException(
"blosc: shuffle type not supported: '" + shuffle + "'; expected one of " + Arrays.toString(supportedShuffleNames));
}
final Object blocksizeObj = map.get(keyBlocksize);
if (blocksizeObj == null) {
this.blocksize = defaultBlocksize;
} else if (blocksizeObj instanceof String) {
this.blocksize = Integer.parseInt((String) blocksizeObj);
} else {
this.blocksize = ((Number) blocksizeObj).intValue();
}
final Object nthreadsObj = map.get(keyNumThreads);
if (nthreadsObj == null) {
this.nthreads = defaultNumThreads;
} else if (nthreadsObj instanceof String) {
this.nthreads = Integer.parseInt((String) nthreadsObj);
} else {
this.nthreads = ((Number) nthreadsObj).intValue();
}
}
@Override
public String getId() {
return "blosc";
}
public int getClevel() {
return clevel;
}
public int getBlocksize() {
return blocksize;
}
public int getShuffle() {
return shuffle;
}
public String getCname() {
return cname;
}
public int getNumThreads() {
return nthreads;
}
@Override
public String toString() {
return "compressor=" + getId()
+ "/cname=" + cname + "/clevel=" + clevel
+ "/blocksize=" + blocksize + "/shuffle=" + shuffle;
}
@Override
public void compress(InputStream is, OutputStream os) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
passThrough(is, baos);
final byte[] inputBytes = baos.toByteArray();
final int inputSize = inputBytes.length;
final int outputSize = inputSize + JBlosc.OVERHEAD;
final ByteBuffer inputBuffer = ByteBuffer.wrap(inputBytes);
final ByteBuffer outBuffer = ByteBuffer.allocate(outputSize);
final int i = JBlosc.compressCtx(clevel, shuffle, 1, inputBuffer, inputSize, outBuffer, outputSize, cname, blocksize, nthreads);
final BufferSizes bs = cbufferSizes(outBuffer);
byte[] compressedChunk = Arrays.copyOfRange(outBuffer.array(), 0, (int) bs.getCbytes());
os.write(compressedChunk);
}
@Override
public void uncompress(InputStream is, OutputStream os) throws IOException {
final DataInput di = new DataInputStream(is);
byte[] header = new byte[JBlosc.OVERHEAD];
di.readFully(header);
BufferSizes bs = cbufferSizes(ByteBuffer.wrap(header));
int compressedSize = (int) bs.getCbytes();
int uncompressedSize = (int) bs.getNbytes();
byte[] inBytes = Arrays.copyOf(header, compressedSize);
di.readFully(inBytes, header.length, compressedSize - header.length);
ByteBuffer outBuffer = ByteBuffer.allocate(uncompressedSize);
JBlosc.decompressCtx(ByteBuffer.wrap(inBytes), outBuffer, outBuffer.limit(), nthreads);
os.write(outBuffer.array());
}
private BufferSizes cbufferSizes(ByteBuffer cbuffer) {
NativeLongByReference nbytes = new NativeLongByReference();
NativeLongByReference cbytes = new NativeLongByReference();
NativeLongByReference blocksize = new NativeLongByReference();
IBloscDll.blosc_cbuffer_sizes(cbuffer, nbytes, cbytes, blocksize);
BufferSizes bs = new BufferSizes(nbytes.getValue().longValue(),
cbytes.getValue().longValue(),
blocksize.getValue().longValue());
return bs;
}
}
}