Debian Codegraph @

tools/jni/org/jpeg/jpegli/wrapper/encoder_jni.cc

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 #include "encoder_jni.h" // NOLINT: build/include
7
8 #include <jni.h>
9
10 #include <algorithm>
11 #include <array>
12 #include <cstddef>
13 #include <cstdint>
14 #include <cstdio>
15 #include <cstring>
16 #include <memory>
17 #include <new>
18
19 #include "lib/jpegli/common.h"
20 #include "lib/jpegli/encode.h"
21 #include "lib/jpegli/types.h"
22
23 namespace org_jpeg_jpegli_wrapper {
24 namespace {
25
26 jint JNI_VERSION = JNI_VERSION_1_6;
27
28 jclass JC_WritableByteChannel;
29 jmethodID JMID_WritableByteChannel_write;
30
31 enum ReturnCode {
32 OK = 0,
33 ERROR_ALLOCATION = -1,
34 ERROR_INVALID_PARAMS = -2,
35 ERROR_INTERNAL = -3
36 };
37
38 // #define RETURN_ERROR(T) return ERROR_##T
39 #define RETURN_ERROR(T) \
40 return fprintf(stderr, "%s:%d: error " #T "\n", __FILE__, __LINE__), ERROR_##T
41
42 void ExitHandler(j_common_ptr cinfo) {
43 (*cinfo->err->output_message)(cinfo);
44 jmp_buf* env = reinterpret_cast<jmp_buf*>(cinfo->client_data);
45 jpegli_destroy(cinfo);
46 longjmp(*env, 1);
47 }
48
49 struct DestinationManager {
50 // IMPORTANT: this should always be the first member!
51 jpeg_destination_mgr pub;
52
53 std::unique_ptr<uint8_t[]> output = nullptr;
54 size_t output_size;
55
56 JNIEnv* jenv;
57 jobject sink;
58 bool has_error = false;
59
60 DestinationManager() {
61 pub.init_destination = init_destination;
62 pub.empty_output_buffer = empty_output_buffer;
63 pub.term_destination = term_destination;
64 }
65
66 void Rewind() {
67 pub.next_output_byte = output.get();
68 pub.free_in_buffer = output_size;
69 }
70
71 void WriteAndRewind() {
72 size_t to_write = pub.next_output_byte - output.get();
73 if (to_write == 0) {
74 return;
75 }
76 jobject byte_buffer = jenv->NewDirectByteBuffer(output.get(), to_write);
77 if (byte_buffer == nullptr || jenv->ExceptionCheck()) {
78 has_error = true;
79 Rewind();
80 return;
81 }
82 jint num_written =
83 jenv->CallIntMethod(sink, JMID_WritableByteChannel_write, byte_buffer);
84 jenv->DeleteLocalRef(byte_buffer);
85 if (num_written != static_cast<jint>(to_write) || jenv->ExceptionCheck()) {
86 has_error = true;
87 }
88 Rewind();
89 }
90
91 static void init_destination(j_compress_ptr cinfo) {
92 auto* self = reinterpret_cast<DestinationManager*>(cinfo->dest);
93 self->Rewind();
94 }
95
96 static boolean empty_output_buffer(j_compress_ptr cinfo) {
97 auto* self = reinterpret_cast<DestinationManager*>(cinfo->dest);
98 if (self->has_error) return FALSE;
99 self->WriteAndRewind();
100 if (self->has_error) return FALSE;
101 return TRUE;
102 }
103
104 static void term_destination(j_compress_ptr cinfo) {
105 auto* self = reinterpret_cast<DestinationManager*>(cinfo->dest);
106 self->WriteAndRewind();
107 }
108 };
109
110 typedef std::array<jint, 33> Config;
111
112 class Encoder {
113 public:
114 Encoder(JNIEnv* jenv, jint width, jint height, const Config& config,
115 jintArray input, jobject output)
116 : jenv_(jenv), width_(width), height_(height), input_(input) {
117 healthy_ = (static_cast<jint>(width_) == width) &&
118 (static_cast<jint>(height_) == height);
119
120 jint config_present = config[32];
121 if (config_present & 1) {
122 quality_ = config[0];
123 healthy_ &= (static_cast<jint>(quality_) == config[0]);
124 healthy_ &= (quality_ >= 1 && quality_ <= 100);
125 } else {
126 healthy_ = false; // quality is mandatory
127 }
128
129 dest_.jenv = jenv;
130 dest_.sink = output;
131
132 size_t justified_width = (width + 31) & ~31;
133 size_t output_buffer_min = batch_lines_ * justified_width * 4;
134 size_t output_buffer_tmp = 1;
135 while (output_buffer_tmp < output_buffer_min) output_buffer_tmp <<= 1;
136 output_buffer_size_ = output_buffer_tmp;
137 }
138
139 ~Encoder() { jpegli_destroy_compress(&cinfo_); }
140
141 int Run() {
142 if (!healthy_) RETURN_ERROR(INVALID_PARAMS);
143
144 std::unique_ptr<JSAMPROW[]> batch_rows{new (std::nothrow)
145 JSAMPROW[batch_lines_]};
146 if (!batch_rows) RETURN_ERROR(ALLOCATION);
147
148 size_t input_stride = width_ * 4;
149 std::unique_ptr<uint8_t[]> batch{new (std::nothrow)
150 uint8_t[input_stride * batch_lines_]};
151 if (!batch) RETURN_ERROR(ALLOCATION);
152
153 size_t stride = width_ * 3;
154 for (size_t i = 0; i < batch_lines_; ++i) {
155 batch_rows[i] = batch.get() + i * stride;
156 }
157
158 dest_.output_size = output_buffer_size_;
159 dest_.output = std::unique_ptr<uint8_t[]>{new (std::nothrow)
160 uint8_t[output_buffer_size_]};
161 if (!dest_.output) RETURN_ERROR(ALLOCATION);
162 dest_.Rewind();
163
164 // Setup error handling.
165 cinfo_.err = jpegli_std_error(&err_);
166 cinfo_.client_data = reinterpret_cast<void*>(&env_);
167 cinfo_.err->error_exit = &ExitHandler;
168 if (setjmp(env_)) {
169 RETURN_ERROR(INTERNAL);
170 }
171
172 jpegli_create_compress(&cinfo_);
173 cinfo_.dest = reinterpret_cast<jpeg_destination_mgr*>(&dest_);
174
175 cinfo_.image_width = width_;
176 cinfo_.image_height = height_;
177 cinfo_.input_components = 3;
178 cinfo_.in_color_space = JCS_RGB;
179 jpegli_set_defaults(&cinfo_);
180 jpegli_set_quality(&cinfo_, quality_, TRUE);
181 cinfo_.comp_info[0].v_samp_factor = v_sampling_[0];
182 jpegli_set_progressive_level(&cinfo_, 0);
183 cinfo_.optimize_coding = FALSE;
184 jpegli_start_compress(&cinfo_, TRUE);
185
186 while (cinfo_.next_scanline < cinfo_.image_height) {
187 size_t lines_left = cinfo_.image_height - cinfo_.next_scanline;
188 size_t num_lines = std::min(batch_lines_, lines_left);
189 // We use batch buffer both for temporary storage of input RGBA and pixel
190 // data passed to encoder.
191 if (!ReadBatch(cinfo_.next_scanline, num_lines,
192 reinterpret_cast<jint*>(batch.get()), batch.get())) {
193 RETURN_ERROR(INTERNAL);
194 }
195 size_t lines_done = 0;
196 while (lines_done < num_lines) {
197 lines_done += jpegli_write_scanlines(
198 &cinfo_, batch_rows.get() + lines_done, num_lines - lines_done);
199 if (dest_.has_error) {
200 RETURN_ERROR(INTERNAL);
201 }
202 }
203 }
204
205 jpegli_finish_compress(&cinfo_);
206 if (dest_.has_error) {
207 RETURN_ERROR(INTERNAL);
208 }
209
210 dest_.WriteAndRewind();
211 if (dest_.has_error) {
212 RETURN_ERROR(INTERNAL);
213 }
214
215 return OK;
216 }
217
218 private:
219 bool ReadBatch(size_t y0, size_t num_lines, jint* tmp_buffer,
220 uint8_t* buffer) {
221 size_t num_pixels = num_lines * width_;
222 jenv_->GetIntArrayRegion(input_, y0 * width_, num_pixels, tmp_buffer);
223 if (jenv_->ExceptionCheck()) return false;
224 // TODO(eustas): speedup
225 for (size_t i = 0; i < num_pixels; ++i) {
226 // TODO(eustas): take care of endianness.
227 memcpy(buffer + 3 * i, tmp_buffer + i, 4);
228 // Convert BGRA input data to RGB.
229 std::swap(buffer[3 * i], buffer[3 * i + 2]);
230 }
231 return true;
232 }
233
234 // Interface
235 bool healthy_;
236 JNIEnv* jenv_;
237 size_t width_;
238 size_t height_;
239 size_t quality_;
240 // TODO(eustas): make configurable
241 size_t v_sampling_[3] = {1, 1, 1};
242 // TODO(eustas): depends on v_sampling_; make configurable
243 size_t batch_lines_ = 32;
244 size_t output_buffer_size_;
245 jintArray input_;
246
247 // Jpegli encoder
248 jpeg_compress_struct cinfo_ = {};
249 jpeg_error_mgr err_;
250 jmp_buf env_;
251 DestinationManager dest_;
252 };
253
254 char* kEncodeName = const_cast<char*>("nativeEncode");
255 char* kEncodeSig =
256 const_cast<char*>("(III[ILjava/nio/channels/WritableByteChannel;)I");
257
258 const JNINativeMethod kEncoderMethods[] = {
259 {kEncodeName, kEncodeSig,
260 reinterpret_cast<void*>(
261 Java_org_jpeg_jpegli_wrapper_Encoder_nativeEncode)}};
262
263 static const size_t kNumEncoderMethods = 1;
264
265 } // namespace
266
267 jint JniRegister(JavaVM* vm) {
268 JNIEnv* env;
269 if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION) != JNI_OK) {
270 return JNI_ERR;
271 }
272
273 jclass localClassRef = env->FindClass("org/jpeg/jpegli/wrapper/EncoderJni");
274 if (localClassRef == nullptr || env->ExceptionCheck()) {
275 return JNI_ERR;
276 }
277 if (env->RegisterNatives(localClassRef, kEncoderMethods, kNumEncoderMethods) <
278 0) {
279 return JNI_ERR;
280 }
281 env->DeleteLocalRef(localClassRef);
282 return JNI_VERSION;
283 }
284
285 } // namespace org_jpeg_jpegli_wrapper
286
287 #ifdef __cplusplus
288 extern "C" {
289 #endif
290
291 JNIEXPORT jint JNICALL
292 Java_org_jpeg_jpegli_wrapper_Encoder_nativeInit(JNIEnv* env, jobject /*jobj*/) {
293 using org_jpeg_jpegli_wrapper::ERROR_INTERNAL;
294 using org_jpeg_jpegli_wrapper::JC_WritableByteChannel;
295 using org_jpeg_jpegli_wrapper::JMID_WritableByteChannel_write;
296 using org_jpeg_jpegli_wrapper::OK;
297
298 jclass localClassRef =
299 env->FindClass("java/nio/channels/WritableByteChannel");
300 if (localClassRef == nullptr || env->ExceptionCheck()) {
301 RETURN_ERROR(INTERNAL);
302 }
303 JC_WritableByteChannel = (jclass)env->NewGlobalRef(localClassRef);
304 if (JC_WritableByteChannel == nullptr || env->ExceptionCheck()) {
305 RETURN_ERROR(INTERNAL);
306 }
307 env->DeleteLocalRef(localClassRef);
308
309 JMID_WritableByteChannel_write = env->GetMethodID(
310 JC_WritableByteChannel, "write", "(Ljava/nio/ByteBuffer;)I");
311 if (JMID_WritableByteChannel_write == nullptr || env->ExceptionCheck()) {
312 RETURN_ERROR(INTERNAL);
313 }
314
315 return OK;
316 }
317
318 JNIEXPORT jint JNICALL Java_org_jpeg_jpegli_wrapper_Encoder_nativeEncode(
319 JNIEnv* env, jobject /*jobj*/, jint width, jint height, jintArray config,
320 jintArray input, jobject output) {
321 using org_jpeg_jpegli_wrapper::Config;
322 using org_jpeg_jpegli_wrapper::Encoder;
323 using org_jpeg_jpegli_wrapper::ERROR_ALLOCATION;
324 using org_jpeg_jpegli_wrapper::ERROR_INVALID_PARAMS;
325
326 Config config_values;
327 env->GetIntArrayRegion(config, 0, 33, config_values.data());
328 if (env->ExceptionCheck()) {
329 RETURN_ERROR(INVALID_PARAMS);
330 }
331
332 std::unique_ptr<Encoder> encoder{new (std::nothrow) Encoder(
333 env, width, height, config_values, input, output)};
334 if (!encoder) RETURN_ERROR(ALLOCATION);
335 return encoder->Run();
336 }
337
338 #ifdef __cplusplus
339 }
340 #endif