Debian Codegraph @

tools/jni/org/jpeg/jpegli/wrapper/Encoder.java

raw
1 // Copyright (c) the JPEG XL Project Authors. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 package org.jpeg.jpegli.wrapper;
7
8 import java.io.IOException;
9 import java.io.OutputStream;
10 import java.nio.channels.Channels;
11 import java.nio.channels.WritableByteChannel;
12
13 /** Jpegli JNI encoder wrapper. */
14 public class Encoder {
15 static {
16 JniHelper.ensureInitialized();
17 }
18
19 /** Utility library, disable object construction. */
20 private Encoder() {}
21
22 // NB(eustas): moving serialized to native might improve performance
23 public static class Config {
24 private enum Options {
25 QUALITY,
26 }
27
28 private int[] serialized = new int[33];
29
30 public Config setQuality(int quality) {
31 setOption(Options.QUALITY, quality);
32 return this;
33 }
34
35 private void setOption(Options option, int value) {
36 int index = option.ordinal();
37 serialized[32] |= 1 << index;
38 serialized[index] = value;
39 }
40 }
41
42 private static native int nativeInit();
43
44 private static native int nativeEncode(
45 int width, int height, int[] config, int[] data, WritableByteChannel output);
46
47 private static class InitHelper {
48 private static final int STATUS = nativeInit();
49 }
50
51 public static boolean ensureInitialized() {
52 return (InitHelper.STATUS == 0);
53 }
54
55 /** One-shot encoding. */
56 public static void encode(int[] color, int width, int height, Config config,
57 WritableByteChannel output) throws IOException {
58 if (!ensureInitialized()) {
59 throw new IllegalStateException("Native library not initialized");
60 }
61 if (output == null) {
62 throw new IllegalArgumentException("output is null");
63 }
64 if (color == null) {
65 throw new IllegalArgumentException("color is null");
66 }
67 if ((width <= 0) || (height <= 0) || (color.length != width * height)) {
68 throw new IllegalArgumentException("invalid image dimensions");
69 }
70
71 // TODO(eustas): what is colorspace?
72
73 int status = nativeEncode(width, height, config.serialized, color, output);
74 if (status != 0) {
75 throw new IOException("Jpegli wrapper nativeProcess return code: " + status);
76 }
77 }
78
79 /** One-shot encoding. */
80 public static void encode(int[] color, int width, int height, int quality, OutputStream output)
81 throws IOException {
82 if (output == null) {
83 throw new IllegalArgumentException("output is null");
84 }
85 try (WritableByteChannel channel = Channels.newChannel(output)) {
86 encode(color, width, height, new Config().setQuality(quality), channel);
87 }
88 }
89 }