Repository navigation
Expand file tree
/
Copy pathNativeModelIntegrationTest.java
More file actions
531 lines (474 loc) · 24.4 KB
/
Copy pathNativeModelIntegrationTest.java
File metadata and controls
531 lines (474 loc) · 24.4 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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package cc.projectargus.workbench.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import cc.projectargus.workbench.audio.AudioService;
import cc.projectargus.workbench.audio.AudioService.SynthesizedAudioResult;
import cc.projectargus.workbench.chat.ChatService;
import cc.projectargus.workbench.chat.InvalidChatRequestException;
import cc.projectargus.workbench.config.ArgusAudioProperties;
import cc.projectargus.workbench.config.ArgusLangChain4jConfig;
import cc.projectargus.workbench.config.ArgusVisionProperties;
import cc.projectargus.workbench.config.ArgusWorkbenchProperties;
import cc.projectargus.workbench.web.dto.AudioTranscriptionResponseDto;
import cc.projectargus.workbench.web.dto.ChatImageAttachmentDto;
import cc.projectargus.workbench.web.dto.ChatRequestDto;
import cc.projectargus.workbench.web.dto.ChatResponseDto;
import cc.projectargus.workbench.web.dto.SpeechSynthesisRequestDto;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.langchain4j.data.audio.Audio;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.TokenCountEstimator;
import dev.langchain4j.model.audio.AudioTranscriptionModel;
import dev.langchain4j.model.audio.AudioTranscriptionRequest;
import dev.langchain4j.model.audio.TextToSpeechModel;
import dev.langchain4j.model.audio.TextToSpeechRequest;
import dev.langchain4j.model.audio.TextToSpeechResponse;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.request.ChatRequestParameters;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.PartialResponse;
import dev.langchain4j.model.chat.response.PartialResponseContext;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.CRC32;
import java.util.zip.Deflater;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
/**
* Opt-in end-to-end native integration test that loads real GGUF/GGML models via the active
* {@code libargus} binding (Project Panama FFM on JDK 22+/25 or portable JNI on JDK 17+ / {@code -Pjni})
* and exercises token counting, synchronous chat, multi-token streaming, live model recovery,
* multimodal vision projection ({@code ARGUS_VISION_MMPROJ_PATH}), local Whisper ASR
* ({@code ARGUS_ASR_MODEL_PATH}), Speech-LLM TTS ({@code ARGUS_TTS_MODEL_PATH} +
* {@code ARGUS_TTS_VOCODER_PATH}), and deterministic reverse-order teardown.
*
* <p>Each test skips cleanly via JUnit {@link Assumptions} when its required model path(s) are not
* provided via environment variables or Maven system properties.
*/
class NativeModelIntegrationTest {
@TempDir
Path tempDir;
private static Path resolveConfiguredModelPath() {
return resolveOptionalModelPath("argus.chat.model-path", "ARGUS_CHAT_MODEL_PATH", "chat GGUF");
}
private static Path resolveOptionalModelPath(String sysProp, String envVar, String label) {
String configuredPath = System.getProperty(sysProp);
if (configuredPath == null || configuredPath.isBlank()) {
configuredPath = System.getenv(envVar);
}
Assumptions.assumeTrue(
configuredPath != null && !configuredPath.isBlank(),
"Skipping native " + label + " integration test: set " + envVar + " or -D" + sysProp + "=/path/to/model to run."
);
Path modelPath = Path.of(configuredPath.trim());
Assumptions.assumeTrue(
Files.isRegularFile(modelPath),
"Skipping native " + label + " integration test: configured model file does not exist: " + modelPath
);
return modelPath;
}
@Test
void loadsRealGgufModelExecutesSyncAndStreamingChatAndClosesCleanly() throws Exception {
Path modelPath = resolveConfiguredModelPath();
ArgusWorkbenchProperties props = new ArgusWorkbenchProperties();
props.setModelPath(modelPath.toString());
props.setContextLength(512);
props.setMaxOutputTokens(8);
props.setGpuLayers(0);
props.setTemperature(0.0f);
props.setFailFastStartup(true);
InferenceConcurrencyGate gate = new InferenceConcurrencyGate(props);
ArgusRuntimeManager runtimeManager = new ArgusRuntimeManager(props, gate);
ChatService chatService = new ChatService(runtimeManager, gate, props, new ObjectMapper());
try {
runtimeManager.afterPropertiesSet();
assertThat(runtimeManager.isReady()).isTrue();
RuntimeStatusSnapshot status = runtimeManager.getStatusSnapshot(0);
assertThat(status.status()).isEqualTo("ready");
assertThat(status.chatEnabled()).isTrue();
assertThat(status.runtimeVersion()).isEqualTo("2.4.0");
assertThat(status.capabilities()).contains("chat", "streaming", "thinking");
assertThat(status.binding()).isEqualTo(ArgusRuntimeManager.detectActiveBinding());
assertThat(status.modelName()).isEqualTo(modelPath.getFileName().toString());
// 1. Verify native BPE token estimation (including raw text vs formatted chat message via @Bean adapter)
ArgusLangChain4jConfig langChainConfig = new ArgusLangChain4jConfig();
TokenCountEstimator estimatorBean = langChainConfig.argusTokenCountEstimator(runtimeManager);
ChatModel chatBean = langChainConfig.argusChatModel(runtimeManager);
int rawHelloTokens = estimatorBean.estimateTokenCountInText("Hello");
int formattedHelloTokens = estimatorBean.estimateTokenCountInMessage(UserMessage.from("Hello"));
int multiTurnTokens = estimatorBean.estimateTokenCountInMessages(
List.of(SystemMessage.from("Sys"), UserMessage.from("Hello"))
);
assertThat(rawHelloTokens).isPositive();
assertThat(formattedHelloTokens).isGreaterThanOrEqualTo(rawHelloTokens);
assertThat(multiTurnTokens).isGreaterThan(rawHelloTokens);
assertThat(
chatBean.doChat(
ChatRequest.builder()
.messages(UserMessage.from("Hi"))
.parameters(ChatRequestParameters.builder().temperature(0.0).maxOutputTokens(2).build())
.build()
).aiMessage().text()
).isNotEmpty();
int tokens = runtimeManager.countTokens(List.of(
SystemMessage.from(props.getSystemPrompt()),
UserMessage.from("Hello")
));
assertThat(tokens).isPositive();
// 2. Verify synchronous chat through ChatService
ChatResponseDto syncResponse = chatService.chat(
new ChatRequestDto(null, "Hello", 0.0f, 4, "native-sync-1")
);
assertThat(syncResponse.requestId()).isEqualTo("native-sync-1");
assertThat(syncResponse.usage().inputTokens()).isPositive();
assertThat(syncResponse.usage().outputTokens()).isEqualTo(4);
assertThat(syncResponse.finishReason()).isNotBlank();
// 3. Verify incremental streaming chat with CancellationToken
List<String> fragments = new ArrayList<>();
CompletableFuture<ChatResponse> streamDone = new CompletableFuture<>();
ChatRequest streamReq = ChatRequest.builder()
.messages(UserMessage.from("Hello"))
.parameters(
ChatRequestParameters.builder()
.temperature(0.0)
.maxOutputTokens(4)
.build()
)
.build();
try (CancellationToken cancelToken = runtimeManager.createCancellationToken()) {
runtimeManager.streamChat(
streamReq,
new StreamingChatResponseHandler() {
@Override
public void onPartialResponse(String partialResponse) {
fragments.add(partialResponse);
}
@Override
public void onCompleteResponse(ChatResponse completeResponse) {
streamDone.complete(completeResponse);
}
@Override
public void onError(Throwable error) {
streamDone.completeExceptionally(error);
}
},
cancelToken
);
}
ChatResponse completed = streamDone.get(30, TimeUnit.SECONDS);
assertThat(completed).isNotNull();
assertThat(completed.tokenUsage().inputTokenCount()).isPositive();
assertThat(fragments).hasSizeGreaterThanOrEqualTo(2);
assertThat(String.join("", fragments)).isEqualTo(completed.aiMessage().text());
// 4. Verify 1.23.0 2-arg StreamingChatResponseHandler + StreamingHandle.cancel() + chatAsync
ChatResponse asyncResponse = chatBean.chatAsync(
ChatRequest.builder()
.messages(UserMessage.from("Hi"))
.parameters(ChatRequestParameters.builder().temperature(0.0).maxOutputTokens(2).build())
.build()
).get(30, TimeUnit.SECONDS);
assertThat(asyncResponse.aiMessage().text()).isNotEmpty();
var streamingBean = langChainConfig.argusStreamingChatModel(runtimeManager);
AtomicInteger piecesBeforeCancel = new AtomicInteger(0);
CompletableFuture<ChatResponse> handleCancelDone = new CompletableFuture<>();
streamingBean.chat(
ChatRequest.builder()
.messages(UserMessage.from("Hello"))
.parameters(ChatRequestParameters.builder().temperature(0.0).maxOutputTokens(6).build())
.build(),
new StreamingChatResponseHandler() {
@Override
public void onPartialResponse(PartialResponse partialResponse, PartialResponseContext context) {
assertThat(context.streamingHandle()).isNotNull();
piecesBeforeCancel.incrementAndGet();
context.streamingHandle().cancel();
}
@Override
public void onCompleteResponse(ChatResponse completeResponse) {
handleCancelDone.complete(completeResponse);
}
@Override
public void onError(Throwable error) {
handleCancelDone.completeExceptionally(error);
}
}
);
ChatResponse abortedResp = handleCancelDone.get(30, TimeUnit.SECONDS);
assertThat(abortedResp).isNotNull();
assertThat(piecesBeforeCancel.get()).isEqualTo(1);
} finally {
chatService.destroy();
runtimeManager.destroy();
assertThat(runtimeManager.isReady()).isFalse();
}
}
@Test
void recoversLiveWhenModelFileArrivesAfterDegradedStartup() throws Exception {
Path sourceModel = resolveConfiguredModelPath();
Path delayedDestination = tempDir.resolve("delayed-arrival.gguf");
ArgusWorkbenchProperties props = new ArgusWorkbenchProperties();
props.setModelPath(delayedDestination.toString());
props.setContextLength(256);
props.setMaxOutputTokens(4);
props.setGpuLayers(0);
props.setTemperature(0.0f);
props.setFailFastStartup(false);
InferenceConcurrencyGate gate = new InferenceConcurrencyGate(props);
ArgusRuntimeManager runtimeManager = new ArgusRuntimeManager(props, gate);
try {
runtimeManager.afterPropertiesSet();
assertThat(runtimeManager.isReady()).isFalse();
assertThat(runtimeManager.getStatusSnapshot(0).status()).isEqualTo("not_ready");
// Simulate user finishing model download to the configured path
Files.copy(sourceModel, delayedDestination, StandardCopyOption.REPLACE_EXISTING);
assertThat(runtimeManager.isReady()).isTrue();
RuntimeStatusSnapshot recovered = runtimeManager.getStatusSnapshot(0);
assertThat(recovered.status()).isEqualTo("ready");
assertThat(recovered.chatEnabled()).isTrue();
assertThat(recovered.modelName()).isEqualTo("delayed-arrival.gguf");
} finally {
runtimeManager.destroy();
}
}
@Test
void streamOnlyChatModeAllocatesSingleStreamingAdapterAndRejectsSyncRequests() throws Exception {
Path modelPath = resolveConfiguredModelPath();
ArgusWorkbenchProperties props = new ArgusWorkbenchProperties();
props.setModelPath(modelPath.toString());
props.setChatMode("stream");
props.setContextLength(256);
props.setMaxOutputTokens(4);
props.setGpuLayers(0);
props.setTemperature(0.0f);
props.setFailFastStartup(true);
InferenceConcurrencyGate gate = new InferenceConcurrencyGate(props);
ArgusRuntimeManager runtimeManager = new ArgusRuntimeManager(props, gate);
ChatService chatService = new ChatService(runtimeManager, gate, props, new ObjectMapper());
try {
runtimeManager.afterPropertiesSet();
assertThat(runtimeManager.isReady()).isTrue();
assertThatThrownBy(() -> chatService.chat(new ChatRequestDto(null, "Hello", 0.0f, 4, "sync-disabled-1")))
.isInstanceOf(InvalidChatRequestException.class)
.extracting(ex -> ((InvalidChatRequestException) ex).getErrorCode())
.isEqualTo("sync_chat_disabled");
CompletableFuture<ChatResponse> streamDone = new CompletableFuture<>();
ChatRequest streamReq = ChatRequest.builder()
.messages(UserMessage.from("Hello"))
.parameters(
ChatRequestParameters.builder()
.temperature(0.0)
.maxOutputTokens(4)
.build()
)
.build();
try (CancellationToken cancelToken = runtimeManager.createCancellationToken()) {
runtimeManager.streamChat(
streamReq,
new StreamingChatResponseHandler() {
@Override
public void onPartialResponse(String partialResponse) {
}
@Override
public void onCompleteResponse(ChatResponse completeResponse) {
streamDone.complete(completeResponse);
}
@Override
public void onError(Throwable error) {
streamDone.completeExceptionally(error);
}
},
cancelToken
);
}
assertThat(streamDone.get(30, TimeUnit.SECONDS)).isNotNull();
} finally {
chatService.destroy();
runtimeManager.destroy();
}
}
@Test
void loadsOptionalWhisperAndTtsModelsAndExecutesEndToEndAudioPipeline() throws Exception {
Path chatModelPath = resolveConfiguredModelPath();
Path asrModelPath = resolveOptionalModelPath("argus.audio.asr-model-path", "ARGUS_ASR_MODEL_PATH", "Whisper ASR");
Path ttsModelPath = resolveOptionalModelPath("argus.audio.tts-model-path", "ARGUS_TTS_MODEL_PATH", "TTS Speech-LLM");
Path ttsVocoderPath = resolveOptionalModelPath("argus.audio.tts-vocoder-path", "ARGUS_TTS_VOCODER_PATH", "TTS Vocoder");
ArgusWorkbenchProperties props = new ArgusWorkbenchProperties();
props.setModelPath(chatModelPath.toString());
props.setContextLength(512);
props.setMaxOutputTokens(8);
props.setGpuLayers(0);
props.setFailFastStartup(true);
ArgusAudioProperties audioProps = new ArgusAudioProperties();
audioProps.setAsrModelPath(asrModelPath.toString());
audioProps.setTtsModelPath(ttsModelPath.toString());
audioProps.setTtsVocoderPath(ttsVocoderPath.toString());
audioProps.setTtsMaxDurationSeconds(2);
audioProps.setTtsVoice("42");
InferenceConcurrencyGate gate = new InferenceConcurrencyGate(props);
ArgusRuntimeManager runtimeManager = new ArgusRuntimeManager(props, audioProps, gate);
AudioService audioService = new AudioService(runtimeManager, gate, props, audioProps);
try {
runtimeManager.afterPropertiesSet();
assertThat(runtimeManager.isReady()).isTrue();
assertThat(runtimeManager.isAsrReady()).isTrue();
assertThat(runtimeManager.isTtsReady()).isTrue();
RuntimeStatusSnapshot status = runtimeManager.getStatusSnapshot(0);
assertThat(status.asrEnabled()).isTrue();
assertThat(status.ttsEnabled()).isTrue();
assertThat(status.capabilities()).contains("chat", "streaming", "thinking", "asr", "tts");
SynthesizedAudioResult synth = audioService.synthesizeSpeech(
new SpeechSynthesisRequestDto("Hello Argus", null, "native-tts-1")
);
assertThat(synth.wavBytes().length).isGreaterThan(44);
assertThat(new String(synth.wavBytes(), 0, 4, StandardCharsets.US_ASCII)).isEqualTo("RIFF");
assertThat(new String(synth.wavBytes(), 8, 4, StandardCharsets.US_ASCII)).isEqualTo("WAVE");
AudioTranscriptionResponseDto transcribed = audioService.transcribe(
synth.wavBytes(), "audio/wav", "native-asr-1"
);
assertThat(transcribed.requestId()).isEqualTo("native-asr-1");
assertThat(transcribed.text()).isNotNull();
// Verify @Bean TextToSpeechModel & AudioTranscriptionModel adapters directly
ArgusLangChain4jConfig lc4jConfig = new ArgusLangChain4jConfig();
TextToSpeechModel ttsBean = lc4jConfig.argusTextToSpeechModel(runtimeManager);
AudioTranscriptionModel asrBean = lc4jConfig.argusAudioTranscriptionModel(runtimeManager);
TextToSpeechResponse beanSynth = ttsBean.synthesize(
TextToSpeechRequest.builder().text("Hi").voice("42").build()
);
assertThat(beanSynth.audio().binaryData().length).isGreaterThan(44);
assertThat(
asrBean.transcribe(
AudioTranscriptionRequest.builder(
Audio.builder().binaryData(beanSynth.audio().binaryData()).mimeType("audio/wav").build()
).build()
).text()
).isNotNull();
assertThat(gate.getAvailablePermits()).isEqualTo(1);
} finally {
audioService.destroy();
runtimeManager.destroy();
assertThat(runtimeManager.isReady()).isFalse();
assertThat(runtimeManager.isAsrReady()).isFalse();
assertThat(runtimeManager.isTtsReady()).isFalse();
}
}
@Test
void loadsVisionProjectorAndExecutesMultimodalImageChat() throws Exception {
Path chatModelPath = resolveConfiguredModelPath();
Path mmprojPath = resolveOptionalModelPath("argus.vision.mmproj-path", "ARGUS_VISION_MMPROJ_PATH", "vision mmproj GGUF");
ArgusWorkbenchProperties props = new ArgusWorkbenchProperties();
props.setModelPath(chatModelPath.toString());
props.setChatMode("sync");
props.setContextLength(2048);
props.setMaxOutputTokens(4);
props.setGpuLayers(0);
props.setFailFastStartup(true);
ArgusVisionProperties visionProps = new ArgusVisionProperties();
visionProps.setMmprojPath(mmprojPath.toString());
visionProps.setUseGpu(false);
visionProps.setTokensPerImage(512);
InferenceConcurrencyGate gate = new InferenceConcurrencyGate(props);
ArgusRuntimeManager runtimeManager = new ArgusRuntimeManager(
props,
new ArgusAudioProperties(),
visionProps,
gate,
null
);
ChatService chatService = new ChatService(runtimeManager, gate, props, visionProps, new ObjectMapper());
String redPngBase64 = Base64.getEncoder().encodeToString(syntheticRgbPngBytes(16, 16));
try {
runtimeManager.afterPropertiesSet();
assertThat(runtimeManager.isReady()).isTrue();
assertThat(runtimeManager.isVisionReady()).isTrue();
RuntimeStatusSnapshot status = runtimeManager.getStatusSnapshot(0);
assertThat(status.visionEnabled()).isTrue();
assertThat(status.visionProjectorName()).isEqualTo(mmprojPath.getFileName().toString());
assertThat(status.capabilities()).contains("chat", "vision");
ChatResponseDto response = chatService.chat(
new ChatRequestDto(
null,
"Reply with one short word describing this image color.",
0.0f,
2,
"native-vision-1",
List.of(new ChatImageAttachmentDto("image/png", redPngBase64))
)
);
assertThat(response.requestId()).isEqualTo("native-vision-1");
assertThat(response.reply()).isNotNull();
assertThat(response.usage().inputTokens()).isGreaterThan(0);
assertThat(gate.getAvailablePermits()).isEqualTo(1);
} finally {
chatService.destroy();
runtimeManager.destroy();
assertThat(runtimeManager.isReady()).isFalse();
assertThat(runtimeManager.isVisionReady()).isFalse();
}
}
private static byte[] syntheticRgbPngBytes(int width, int height) throws IOException {
byte[] rawRows = new byte[height * (1 + width * 3)];
for (int y = 0; y < height; y++) {
int rowStart = y * (1 + width * 3);
rawRows[rowStart] = 0; // filter type None
for (int x = 0; x < width; x++) {
int px = rowStart + 1 + x * 3;
rawRows[px] = (byte) 220;
rawRows[px + 1] = (byte) 30;
rawRows[px + 2] = (byte) 30;
}
}
Deflater deflater = new Deflater();
deflater.setInput(rawRows);
deflater.finish();
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
byte[] buf = new byte[256];
while (!deflater.finished()) {
int n = deflater.deflate(buf);
compressed.write(buf, 0, n);
}
deflater.end();
ByteArrayOutputStream png = new ByteArrayOutputStream();
png.write(new byte[] {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A});
ByteArrayOutputStream ihdr = new ByteArrayOutputStream(13);
try (DataOutputStream dos = new DataOutputStream(ihdr)) {
dos.writeInt(width);
dos.writeInt(height);
dos.writeByte(8); // bit depth
dos.writeByte(2); // RGB color type
dos.writeByte(0); // compression
dos.writeByte(0); // filter
dos.writeByte(0); // interlace
}
writePngChunk(png, "IHDR", ihdr.toByteArray());
writePngChunk(png, "IDAT", compressed.toByteArray());
writePngChunk(png, "IEND", new byte[0]);
return png.toByteArray();
}
private static void writePngChunk(ByteArrayOutputStream out, String type, byte[] data) throws IOException {
byte[] typeBytes = type.getBytes(StandardCharsets.US_ASCII);
try (DataOutputStream dos = new DataOutputStream(out)) {
dos.writeInt(data.length);
dos.write(typeBytes);
dos.write(data);
CRC32 crc = new CRC32();
crc.update(typeBytes);
crc.update(data);
dos.writeInt((int) crc.getValue());
}
}
}