Debian Codegraph @

internal/warpc/genavif/avif.c

raw
1 #include <stdlib.h>
2 #include <string.h>
3 #include <stdbool.h>
4 #include <stdio.h>
5 #include "avif/avif.h"
6 #include "../deps/parson/parson.h"
7
8 void handle_commands(FILE *stream);
9
10 int main()
11 {
12 // This will read commands from stdin and write responses to stdout
13 // and return 0 when stdin is closed.
14 // Any errors gets reported in the RPC response messages.
15 handle_commands(stdin);
16 return 0;
17 }
18
19 typedef struct
20 {
21 int version;
22 int id;
23 char command[256];
24 char err[256];
25 } Header;
26
27 typedef struct
28 {
29 int width;
30 int height;
31 int stride;
32 int depth; // Bit depth per channel (8, 10, 12, 16).
33 int loopCount;
34 int frameCount;
35 int *frameDurations;
36
37 // CICP color properties.
38 int colorPrimaries;
39 int transferCharacteristics;
40 int matrixCoefficients;
41
42 // HDR CLLI box (max content/picture-average light level, in cd/m^2).
43 int maxCLL;
44 int maxPALL;
45
46 } InputParams;
47
48 typedef struct
49 {
50 float quality; // between 1 and 100.
51 char compression[32]; // "lossy" or "lossless"
52 int encoderSpeed; // 1 (slowest, best) to 10 (fastest). 0 means use default.
53 char hint[64]; // drawing, icon, photo, picture, or text. Selects chroma subsampling.
54 } InputOptions;
55
56 typedef struct
57 {
58 InputOptions options;
59 InputParams params;
60
61 } InputData;
62
63 typedef struct
64 {
65 Header header;
66 InputData data;
67
68 } InputMessage;
69
70 typedef struct
71 {
72 Header header;
73 InputData data;
74
75 } OutputMessage;
76
77 #define MAX_LINE_LENGTH 4096
78
79 InputMessage parse_input_message(const char *line)
80 {
81 InputMessage msg = {0};
82
83 JSON_Value *root_value = json_parse_string(line);
84 if (root_value == NULL)
85 {
86 fprintf(stderr, "Error parsing JSON line\n");
87 return msg;
88 }
89
90 if (json_value_get_type(root_value) != JSONObject)
91 {
92 fprintf(stderr, "Error: Line did not parse to a valid JSON object\n");
93 json_value_free(root_value);
94 return msg;
95 }
96
97 JSON_Object *root_object = json_value_get_object(root_value);
98
99 JSON_Object *header_object = json_object_get_object(root_object, "header");
100 if (header_object != NULL)
101 {
102 msg.header.version = (int)json_object_get_number(header_object, "version");
103 msg.header.id = (int)json_object_get_number(header_object, "id");
104 const char *command_str = json_object_get_string(header_object, "command");
105 if (command_str != NULL)
106 {
107 strncpy(msg.header.command, command_str, sizeof(msg.header.command) - 1);
108 msg.header.command[sizeof(msg.header.command) - 1] = '\0';
109 }
110 const char *err_str = json_object_get_string(header_object, "err");
111 if (err_str != NULL)
112 {
113 strncpy(msg.header.err, err_str, sizeof(msg.header.err) - 1);
114 msg.header.err[sizeof(msg.header.err) - 1] = '\0';
115 }
116 }
117
118 JSON_Object *data_object = json_object_get_object(root_object, "data");
119 if (data_object != NULL)
120 {
121 JSON_Object *params_object = json_object_get_object(data_object, "params");
122 if (params_object != NULL)
123 {
124 msg.data.params.width = (int)json_object_get_number(params_object, "width");
125 msg.data.params.height = (int)json_object_get_number(params_object, "height");
126 msg.data.params.stride = (int)json_object_get_number(params_object, "stride");
127 msg.data.params.depth = (int)json_object_get_number(params_object, "depth");
128 msg.data.params.loopCount = (int)json_object_get_number(params_object, "loopCount");
129 msg.data.params.colorPrimaries = (int)json_object_get_number(params_object, "colorPrimaries");
130 msg.data.params.transferCharacteristics = (int)json_object_get_number(params_object, "transferCharacteristics");
131 msg.data.params.matrixCoefficients = (int)json_object_get_number(params_object, "matrixCoefficients");
132 msg.data.params.maxCLL = (int)json_object_get_number(params_object, "maxCLL");
133 msg.data.params.maxPALL = (int)json_object_get_number(params_object, "maxPALL");
134 JSON_Array *durations_array = json_object_get_array(params_object, "frameDurations");
135 if (durations_array != NULL)
136 {
137 size_t count = json_array_get_count(durations_array);
138 msg.data.params.frameCount = count;
139
140 if (count > 0)
141 {
142 msg.data.params.frameDurations = malloc(sizeof(int) * count);
143 if (msg.data.params.frameDurations != NULL)
144 {
145 for (size_t i = 0; i < count; i++)
146 {
147 msg.data.params.frameDurations[i] = (int)json_array_get_number(durations_array, i);
148 }
149 }
150 else
151 {
152 // Malloc failed.
153 msg.data.params.frameCount = 0;
154 }
155 }
156 }
157 }
158 JSON_Object *options_object = json_object_get_object(data_object, "options");
159 if (options_object != NULL)
160 {
161 msg.data.options.quality = (float)json_object_get_number(options_object, "quality");
162 msg.data.options.encoderSpeed = (int)json_object_get_number(options_object, "encoderSpeed");
163 const char *compression_str = json_object_get_string(options_object, "compression");
164 if (compression_str != NULL)
165 {
166 strncpy(msg.data.options.compression, compression_str, sizeof(msg.data.options.compression) - 1);
167 msg.data.options.compression[sizeof(msg.data.options.compression) - 1] = '\0';
168 }
169 const char *hint_str = json_object_get_string(options_object, "hint");
170 if (hint_str != NULL)
171 {
172 strncpy(msg.data.options.hint, hint_str, sizeof(msg.data.options.hint) - 1);
173 msg.data.options.hint[sizeof(msg.data.options.hint) - 1] = '\0';
174 }
175 }
176 }
177
178 json_value_free(root_value);
179 return msg;
180 }
181
182 static void write_blob(uint32_t id, const uint8_t *data, uint32_t size)
183 {
184 uint8_t output_blob_header[16];
185 uint32_t output_blob_id = id;
186 uint32_t output_blob_size = size;
187 // See https://github.com/bep/textandbinarywriter
188 const char magic[] = {'T', 'A', 'K', '3', '5', 'E', 'M', '1'};
189 memcpy(output_blob_header, magic, 8);
190 memcpy(&output_blob_header[8], &output_blob_id, sizeof(output_blob_id));
191 memcpy(&output_blob_header[12], &output_blob_size, sizeof(output_blob_size));
192
193 fwrite(output_blob_header, 1, sizeof(output_blob_header), stdout);
194 fwrite(data, 1, (size_t)size, stdout);
195 fflush(stdout);
196 }
197
198 void write_output_message(const OutputMessage *msg)
199 {
200 JSON_Value *root_value = json_value_init_object();
201 JSON_Object *root_object = json_value_get_object(root_value);
202
203 // Header
204 JSON_Value *header_value = json_value_init_object();
205 JSON_Object *header_object = json_value_get_object(header_value);
206 json_object_set_value(root_object, "header", header_value);
207 json_object_set_number(header_object, "version", msg->header.version);
208 json_object_set_number(header_object, "id", msg->header.id);
209 json_object_set_string(header_object, "err", msg->header.err);
210
211 // Data
212 if (msg->data.params.width > 0)
213 {
214 JSON_Value *data_value = json_value_init_object();
215 JSON_Object *data_object = json_value_get_object(data_value);
216 json_object_set_value(root_object, "data", data_value);
217
218 JSON_Value *params_value = json_value_init_object();
219 JSON_Object *params_object = json_value_get_object(params_value);
220 json_object_set_value(data_object, "params", params_value);
221
222 json_object_set_number(params_object, "width", msg->data.params.width);
223 json_object_set_number(params_object, "height", msg->data.params.height);
224 json_object_set_number(params_object, "stride", msg->data.params.stride);
225 json_object_set_number(params_object, "depth", msg->data.params.depth);
226 json_object_set_number(params_object, "colorPrimaries", msg->data.params.colorPrimaries);
227 json_object_set_number(params_object, "transferCharacteristics", msg->data.params.transferCharacteristics);
228 json_object_set_number(params_object, "matrixCoefficients", msg->data.params.matrixCoefficients);
229 json_object_set_number(params_object, "maxCLL", msg->data.params.maxCLL);
230 json_object_set_number(params_object, "maxPALL", msg->data.params.maxPALL);
231 if (msg->data.params.frameDurations != NULL)
232 {
233 JSON_Value *durations_value = json_value_init_array();
234 JSON_Array *durations_array = json_value_get_array(durations_value);
235 for (int i = 0; i < msg->data.params.frameCount; i++)
236 {
237 json_array_append_number(durations_array, msg->data.params.frameDurations[i]);
238 }
239
240 json_object_set_value(params_object, "frameDurations", durations_value);
241 json_object_set_number(params_object, "loopCount", msg->data.params.loopCount);
242 }
243 }
244
245 char *serialized_string = json_serialize_to_string(root_value);
246 fprintf(stdout, "%s\n", serialized_string);
247 fflush(stdout);
248
249 json_free_serialized_string(serialized_string);
250 json_value_free(root_value);
251 }
252
253 // drain_bytes discards n bytes from stream. Used to keep the protocol aligned
254 // after an error that prevents the blob from being consumed normally.
255 static void drain_bytes(FILE *stream, size_t n)
256 {
257 uint8_t buf[4096];
258 while (n > 0)
259 {
260 size_t want = n < sizeof(buf) ? n : sizeof(buf);
261 size_t got = fread(buf, 1, want, stream);
262 if (got == 0)
263 {
264 break;
265 }
266 n -= got;
267 }
268 }
269
270 // avifFormatForHint maps a content hint to a chroma subsampling format.
271 // Photographic content tolerates 4:2:0, which roughly halves the encoder's
272 // memory footprint and the output size. Sharp-edged content (text, icons, line
273 // art) keeps full 4:4:4 chroma. See issue 14987.
274 static avifPixelFormat avifFormatForHint(const char *hint)
275 {
276 if (strcmp(hint, "drawing") == 0 || strcmp(hint, "icon") == 0 || strcmp(hint, "text") == 0)
277 {
278 return AVIF_PIXEL_FORMAT_YUV444;
279 }
280 return AVIF_PIXEL_FORMAT_YUV420; // photo, picture, and the default.
281 }
282
283 // encoder_errf writes "prefix: result[: diag]", where diag is libavif's
284 // detailed diagnostics (e.g. the underlying aom error, such as an allocation
285 // failure hidden behind the generic "Encoding of color planes failed").
286 static void encoder_errf(char *dst, size_t size, const char *prefix, avifResult result, const avifEncoder *encoder)
287 {
288 snprintf(dst, size, "%s: %s%s%s", prefix, avifResultToString(result),
289 encoder->diag.error[0] ? ": " : "", encoder->diag.error);
290 }
291
292 void handle_commands(FILE *stream)
293 {
294
295 char line[MAX_LINE_LENGTH];
296
297 while (fgets(line, sizeof(line), stream) != NULL)
298 {
299 InputMessage input = {0};
300 uint8_t *blob_data = NULL;
301 uint32_t blob_size = 0;
302
303 // Remove newline character if present
304 line[strcspn(line, "\n")] = 0;
305
306 if (strlen(line) == 0)
307 {
308 continue;
309 }
310
311 input = parse_input_message(line);
312
313 // Next in stream is a blob header defined in https://github.com/bep/textandbinaryreader
314 // T', 'A', 'K', '3', '5', 'E', 'M', '1' id uint32, size uint32
315 uint8_t blob_header[16];
316 size_t read_bytes = fread(blob_header, 1, sizeof(blob_header), stream);
317 if (read_bytes != sizeof(blob_header))
318 {
319 fprintf(stderr, "Error reading blob header\n");
320 goto cleanup;
321 }
322 uint32_t blob_id = *(uint32_t *)&blob_header[8];
323 blob_size = *(uint32_t *)&blob_header[12];
324 blob_data = malloc((size_t)blob_size);
325 if (blob_data == NULL)
326 {
327 // Out of memory. Drain the blob from the input stream so the next
328 // command stays aligned, then report the error to the client instead
329 // of leaving the stream corrupted with no response.
330 drain_bytes(stream, (size_t)blob_size);
331 OutputMessage err_output = {0};
332 err_output.header = input.header;
333 snprintf(err_output.header.err, sizeof(err_output.header.err),
334 "out of memory allocating %u bytes for blob data", blob_size);
335 write_output_message(&err_output);
336 goto cleanup;
337 }
338 read_bytes = fread(blob_data, 1, (size_t)blob_size, stream);
339 if (read_bytes != (size_t)blob_size)
340 {
341 fprintf(stderr, "[%d] Error reading blob data (size: %llu read: %zu) \n", blob_id, (unsigned long long)blob_size, read_bytes);
342 goto cleanup;
343 }
344
345 OutputMessage output = {0};
346 output.header = input.header;
347
348 if (strcmp(input.header.command, "decode") == 0)
349 {
350 avifDecoder *decoder = avifDecoderCreate();
351 if (decoder == NULL)
352 {
353 snprintf(output.header.err, sizeof(output.header.err), "Failed to create AVIF decoder");
354 write_output_message(&output);
355 goto cleanup;
356 }
357
358 decoder->ignoreExif = AVIF_TRUE;
359 decoder->ignoreXMP = AVIF_TRUE;
360 decoder->maxThreads = 1;
361 // dav1d decodes ~2-4x faster than aom under WASM.
362 decoder->codecChoice = AVIF_CODEC_CHOICE_DAV1D;
363 // Request gain map pixels when present (e.g. Lightroom HDR exports).
364 decoder->imageContentToDecode = AVIF_IMAGE_CONTENT_ALL;
365
366 avifResult result = avifDecoderSetIOMemory(decoder, blob_data, blob_size);
367 if (result != AVIF_RESULT_OK)
368 {
369 snprintf(output.header.err, sizeof(output.header.err), "Failed to set IO memory: %s", avifResultToString(result));
370 avifDecoderDestroy(decoder);
371 write_output_message(&output);
372 goto cleanup;
373 }
374
375 result = avifDecoderParse(decoder);
376 if (result != AVIF_RESULT_OK)
377 {
378 snprintf(output.header.err, sizeof(output.header.err), "Failed to parse AVIF: %s", avifResultToString(result));
379 avifDecoderDestroy(decoder);
380 write_output_message(&output);
381 goto cleanup;
382 }
383
384 // If a gain map is present (e.g. Adobe-style SDR+gainmap HDR from Lightroom),
385 // bake it into a single true-HDR image in BT.2020/PQ at 10-bit.
386 // The downstream pipeline then sees a normal HDR AVIF; SDR clients/displays
387 // tone-map automatically.
388 avifBool hasGainMap = (decoder->image->gainMap != NULL && decoder->image->gainMap->image != NULL);
389 if (hasGainMap)
390 {
391 // Need a full frame to apply the gain map.
392 result = avifDecoderNextImage(decoder);
393 if (result != AVIF_RESULT_OK)
394 {
395 snprintf(output.header.err, sizeof(output.header.err), "Failed to decode AVIF for gain map: %s", avifResultToString(result));
396 avifDecoderDestroy(decoder);
397 write_output_message(&output);
398 goto cleanup;
399 }
400
401 avifRGBImage outRGB;
402 memset(&outRGB, 0, sizeof(outRGB));
403 avifRGBImageSetDefaults(&outRGB, decoder->image);
404 outRGB.format = AVIF_RGB_FORMAT_RGBA;
405 outRGB.depth = 16;
406 if (avifRGBImageAllocatePixels(&outRGB) != AVIF_RESULT_OK)
407 {
408 snprintf(output.header.err, sizeof(output.header.err), "Failed to allocate RGB pixels for gain map apply");
409 avifDecoderDestroy(decoder);
410 write_output_message(&output);
411 goto cleanup;
412 }
413
414 // Target the alternate (full-HDR) endpoint: alternateHdrHeadroom = log2(HDR/SDR).
415 float hdrHeadroom = 0.0f;
416 const avifUnsignedFraction *h = &decoder->image->gainMap->alternateHdrHeadroom;
417 if (h->d != 0)
418 {
419 hdrHeadroom = (float)h->n / (float)h->d;
420 }
421
422 avifContentLightLevelInformationBox outCLLI = {0};
423 avifResult applyResult = avifImageApplyGainMap(
424 decoder->image,
425 decoder->image->gainMap,
426 hdrHeadroom,
427 AVIF_COLOR_PRIMARIES_BT2020,
428 AVIF_TRANSFER_CHARACTERISTICS_PQ,
429 &outRGB,
430 &outCLLI,
431 NULL);
432 if (applyResult != AVIF_RESULT_OK)
433 {
434 snprintf(output.header.err, sizeof(output.header.err), "Failed to apply gain map: %s", avifResultToString(applyResult));
435 avifRGBImageFreePixels(&outRGB);
436 avifDecoderDestroy(decoder);
437 write_output_message(&output);
438 goto cleanup;
439 }
440
441 output.data.params.width = outRGB.width;
442 output.data.params.height = outRGB.height;
443 // Tell the Go side we're 10-bit HDR so it wraps in NRGBA64 and re-encodes as HDR.
444 output.data.params.depth = 10;
445 output.data.params.stride = outRGB.rowBytes;
446 output.data.params.frameCount = 1;
447 output.data.params.colorPrimaries = AVIF_COLOR_PRIMARIES_BT2020;
448 output.data.params.transferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_PQ;
449 output.data.params.matrixCoefficients = AVIF_MATRIX_COEFFICIENTS_BT2020_NCL;
450 output.data.params.maxCLL = outCLLI.maxCLL;
451 output.data.params.maxPALL = outCLLI.maxPALL;
452
453 size_t blob_out_size = (size_t)outRGB.rowBytes * outRGB.height;
454 write_output_message(&output);
455 write_blob(output.header.id, outRGB.pixels, blob_out_size);
456
457 avifRGBImageFreePixels(&outRGB);
458 avifDecoderDestroy(decoder);
459 goto cleanup;
460 }
461
462 output.data.params.width = decoder->image->width;
463 output.data.params.height = decoder->image->height;
464 output.data.params.loopCount = decoder->repetitionCount;
465 output.data.params.frameCount = decoder->imageCount;
466 output.data.params.depth = decoder->image->depth;
467 output.data.params.colorPrimaries = decoder->image->colorPrimaries;
468 output.data.params.transferCharacteristics = decoder->image->transferCharacteristics;
469 output.data.params.matrixCoefficients = decoder->image->matrixCoefficients;
470
471 // For 10+ bit images (HDR), use 16-bit RGB to preserve quality.
472 // 8-bit depth: 4 bytes per pixel (RGBA, 1 byte each)
473 // 16-bit depth: 8 bytes per pixel (RGBA, 2 bytes each)
474 int rgb_depth = (decoder->image->depth > 8) ? 16 : 8;
475 uint32_t bytes_per_pixel = (rgb_depth == 16) ? 8 : 4;
476 uint32_t row_bytes = decoder->image->width * bytes_per_pixel;
477
478 output.data.params.stride = row_bytes;
479
480 size_t frame_size = (size_t)row_bytes * decoder->image->height;
481 size_t all_frames_size = frame_size * decoder->imageCount;
482 uint8_t *all_frames_data = malloc(all_frames_size);
483 if (all_frames_data == NULL)
484 {
485 snprintf(output.header.err, sizeof(output.header.err), "Failed to allocate memory for decoded image");
486 avifDecoderDestroy(decoder);
487 write_output_message(&output);
488 goto cleanup;
489 }
490
491 if (decoder->imageCount > 1)
492 {
493 output.data.params.frameDurations = malloc(sizeof(int) * decoder->imageCount);
494 if (output.data.params.frameDurations == NULL)
495 {
496 snprintf(output.header.err, sizeof(output.header.err), "Failed to allocate memory for frame durations");
497 free(all_frames_data);
498 avifDecoderDestroy(decoder);
499 write_output_message(&output);
500 goto cleanup;
501 }
502 }
503
504 // Set up RGB conversion parameters.
505 avifRGBImage rgb;
506 memset(&rgb, 0, sizeof(rgb));
507 avifRGBImageSetDefaults(&rgb, decoder->image);
508 rgb.format = AVIF_RGB_FORMAT_RGBA;
509 rgb.depth = rgb_depth;
510 rgb.rowBytes = row_bytes;
511
512 int frame_index = 0;
513 avifResult next_result;
514 while ((next_result = avifDecoderNextImage(decoder)) == AVIF_RESULT_OK)
515 {
516 rgb.pixels = all_frames_data + (frame_index * frame_size);
517
518 avifResult conv_result = avifImageYUVToRGB(decoder->image, &rgb);
519 if (conv_result != AVIF_RESULT_OK)
520 {
521 snprintf(output.header.err, sizeof(output.header.err), "Failed to convert to RGBA: %s", avifResultToString(conv_result));
522 free(all_frames_data);
523 if (output.data.params.frameDurations != NULL)
524 {
525 free(output.data.params.frameDurations);
526 output.data.params.frameDurations = NULL;
527 }
528 avifDecoderDestroy(decoder);
529 write_output_message(&output);
530 goto cleanup;
531 }
532
533 if (decoder->imageCount > 1)
534 {
535 uint64_t duration_ms = (uint64_t)(decoder->imageTiming.duration * 1000.0);
536 output.data.params.frameDurations[frame_index] = (int)duration_ms;
537 }
538
539 frame_index++;
540 }
541
542 if (next_result != AVIF_RESULT_NO_IMAGES_REMAINING)
543 {
544 snprintf(output.header.err, sizeof(output.header.err), "Failed to decode AVIF frame %d: %s", frame_index, avifResultToString(next_result));
545 free(all_frames_data);
546 if (output.data.params.frameDurations != NULL)
547 {
548 free(output.data.params.frameDurations);
549 output.data.params.frameDurations = NULL;
550 }
551 avifDecoderDestroy(decoder);
552 write_output_message(&output);
553 goto cleanup;
554 }
555
556 if (frame_index != decoder->imageCount)
557 {
558 snprintf(output.header.err, sizeof(output.header.err), "Decoded %d frames, expected %d", frame_index, decoder->imageCount);
559 free(all_frames_data);
560 if (output.data.params.frameDurations != NULL)
561 {
562 free(output.data.params.frameDurations);
563 output.data.params.frameDurations = NULL;
564 }
565 avifDecoderDestroy(decoder);
566 write_output_message(&output);
567 goto cleanup;
568 }
569
570 write_output_message(&output);
571 write_blob(output.header.id, all_frames_data, all_frames_size);
572
573 free(all_frames_data);
574 if (output.data.params.frameDurations != NULL)
575 {
576 free(output.data.params.frameDurations);
577 output.data.params.frameDurations = NULL;
578 }
579 avifDecoderDestroy(decoder);
580
581 goto cleanup;
582 }
583 else if (strcmp(input.header.command, "config") == 0)
584 {
585 avifDecoder *decoder = avifDecoderCreate();
586 if (decoder == NULL)
587 {
588 snprintf(output.header.err, sizeof(output.header.err), "Failed to create AVIF decoder");
589 write_output_message(&output);
590 goto cleanup;
591 }
592
593 decoder->ignoreExif = AVIF_TRUE;
594 decoder->ignoreXMP = AVIF_TRUE;
595 decoder->maxThreads = 1;
596 decoder->codecChoice = AVIF_CODEC_CHOICE_DAV1D;
597
598 avifResult result = avifDecoderSetIOMemory(decoder, blob_data, blob_size);
599 if (result != AVIF_RESULT_OK)
600 {
601 snprintf(output.header.err, sizeof(output.header.err), "Failed to set IO memory: %s", avifResultToString(result));
602 avifDecoderDestroy(decoder);
603 write_output_message(&output);
604 goto cleanup;
605 }
606
607 result = avifDecoderParse(decoder);
608 if (result != AVIF_RESULT_OK)
609 {
610 snprintf(output.header.err, sizeof(output.header.err), "Failed to parse AVIF: %s", avifResultToString(result));
611 avifDecoderDestroy(decoder);
612 write_output_message(&output);
613 goto cleanup;
614 }
615
616 output.data.params.width = decoder->image->width;
617 output.data.params.height = decoder->image->height;
618 output.data.params.depth = decoder->image->depth;
619 output.data.params.loopCount = decoder->repetitionCount;
620 output.data.params.frameCount = decoder->imageCount;
621
622 avifDecoderDestroy(decoder);
623
624 write_output_message(&output);
625 }
626 else if (strcmp(input.header.command, "encodeNRGBA") == 0)
627 {
628 int width = input.data.params.width;
629 int height = input.data.params.height;
630 int depth = input.data.params.depth;
631 int stride = input.data.params.stride;
632
633 // Default depth to 8 if not specified.
634 if (depth == 0) {
635 depth = 8;
636 }
637 // For HDR (10+ bit), input comes as 16-bit RGBA.
638 int rgb_depth = (depth > 8) ? 16 : 8;
639 int bytes_per_pixel = (rgb_depth > 8) ? 8 : 4;
640 if (stride == 0) {
641 stride = width * bytes_per_pixel;
642 }
643 float quality = input.data.options.quality;
644 const char* compression = input.data.options.compression;
645
646 if (width == 0 || height == 0) {
647 snprintf(output.header.err, sizeof(output.header.err), "encodeNRGBA: width and height must be > 0");
648 write_output_message(&output);
649 goto cleanup;
650 }
651
652 // Pick chroma subsampling from the content hint. Lossless keeps 4:4:4,
653 // since subsampling discards chroma and would defeat it.
654 avifPixelFormat yuvFormat = avifFormatForHint(input.data.options.hint);
655 if (strcmp(compression, "lossless") == 0) {
656 yuvFormat = AVIF_PIXEL_FORMAT_YUV444;
657 }
658
659 // Create image with the target bit depth for encoding.
660 avifImage *image = avifImageCreate(width, height, depth, yuvFormat);
661 if (!image) {
662 snprintf(output.header.err, sizeof(output.header.err), "encodeNRGBA: Failed to create avifImage");
663 write_output_message(&output);
664 goto cleanup;
665 }
666
667 // Set color properties from input if provided, otherwise use depth-based defaults.
668 // This preserves the original color space when re-encoding (e.g., BT.709 SDR vs BT.2020 HDR).
669 if (input.data.params.colorPrimaries > 0) {
670 image->colorPrimaries = input.data.params.colorPrimaries;
671 image->transferCharacteristics = input.data.params.transferCharacteristics;
672 image->matrixCoefficients = input.data.params.matrixCoefficients;
673 } else if (depth > 8) {
674 // Default for 10-bit+: BT.2020/PQ (HDR).
675 image->colorPrimaries = AVIF_COLOR_PRIMARIES_BT2020;
676 image->transferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_PQ;
677 image->matrixCoefficients = AVIF_MATRIX_COEFFICIENTS_BT2020_NCL;
678 } else {
679 // Default for 8-bit: BT.709/sRGB (SDR).
680 image->colorPrimaries = AVIF_COLOR_PRIMARIES_BT709;
681 image->transferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_SRGB;
682 image->matrixCoefficients = AVIF_MATRIX_COEFFICIENTS_BT601;
683 }
684 image->yuvRange = AVIF_RANGE_FULL;
685
686 // CLLI carries HDR peak/avg light levels from a baked gain map.
687 if (input.data.params.maxCLL > 0 || input.data.params.maxPALL > 0) {
688 image->clli.maxCLL = (uint16_t)input.data.params.maxCLL;
689 image->clli.maxPALL = (uint16_t)input.data.params.maxPALL;
690 }
691
692 avifRGBImage rgb;
693 avifRGBImageSetDefaults(&rgb, image);
694 rgb.format = AVIF_RGB_FORMAT_RGBA;
695 rgb.depth = rgb_depth;
696 rgb.pixels = (uint8_t *)blob_data;
697 rgb.rowBytes = stride;
698
699 avifResult result = avifImageRGBToYUV(image, &rgb);
700 if (result != AVIF_RESULT_OK) {
701 snprintf(output.header.err, sizeof(output.header.err), "encodeNRGBA: Failed to convert to YUV: %s", avifResultToString(result));
702 avifImageDestroy(image);
703 write_output_message(&output);
704 goto cleanup;
705 }
706
707 avifEncoder *encoder = avifEncoderCreate();
708 if (!encoder) {
709 snprintf(output.header.err, sizeof(output.header.err), "encodeNRGBA: Failed to create encoder");
710 avifImageDestroy(image);
711 write_output_message(&output);
712 goto cleanup;
713 }
714 encoder->codecChoice = AVIF_CODEC_CHOICE_AOM;
715
716 if (strcmp(compression, "lossless") == 0) {
717 encoder->quality = AVIF_QUALITY_LOSSLESS;
718 encoder->qualityAlpha = AVIF_QUALITY_LOSSLESS;
719 } else {
720 // Map Hugo quality 1-100 to libavif quality 0-100 (higher is better).
721 if (quality < 1) quality = 1;
722 if (quality > 100) quality = 100;
723 int avif_quality = (int)((quality - 1.0) / 99.0 * 100.0);
724 // Keep lossy strictly below lossless so quality 100 stays lossy. See issue 14981.
725 if (avif_quality >= AVIF_QUALITY_LOSSLESS) avif_quality = AVIF_QUALITY_LOSSLESS - 1;
726 encoder->quality = avif_quality;
727 encoder->qualityAlpha = avif_quality;
728 }
729 // Range 0 (slowest, best quality) to 10 (fastest).
730 encoder->speed = (input.data.options.encoderSpeed >= 1 && input.data.options.encoderSpeed <= 10)
731 ? input.data.options.encoderSpeed
732 : 10;
733 encoder->autoTiling = AVIF_TRUE;
734
735 result = avifEncoderAddImage(encoder, image, 1, AVIF_ADD_IMAGE_FLAG_SINGLE);
736 if (result != AVIF_RESULT_OK) {
737 encoder_errf(output.header.err, sizeof(output.header.err), "encodeNRGBA: Failed to add image to encoder", result, encoder);
738 avifEncoderDestroy(encoder);
739 avifImageDestroy(image);
740 write_output_message(&output);
741 goto cleanup;
742 }
743
744 avifRWData raw = { NULL, 0 };
745 result = avifEncoderFinish(encoder, &raw);
746 if (result != AVIF_RESULT_OK) {
747 encoder_errf(output.header.err, sizeof(output.header.err), "encodeNRGBA: Failed to finish encoding", result, encoder);
748 avifEncoderDestroy(encoder);
749 avifImageDestroy(image);
750 write_output_message(&output);
751 goto cleanup;
752 }
753
754 write_output_message(&output);
755 write_blob(output.header.id, raw.data, raw.size);
756
757 avifRWDataFree(&raw);
758 avifEncoderDestroy(encoder);
759 avifImageDestroy(image);
760
761 goto cleanup;
762 }
763 else if (strcmp(input.header.command, "encodeGray") == 0)
764 {
765 int width = input.data.params.width;
766 int height = input.data.params.height;
767 int depth = input.data.params.depth;
768 int stride = input.data.params.stride;
769
770 // Default depth to 8 if not specified.
771 if (depth == 0) {
772 depth = 8;
773 }
774 int bytes_per_sample = (depth > 8) ? 2 : 1;
775 if (stride == 0) {
776 stride = width * bytes_per_sample;
777 }
778 float quality = input.data.options.quality;
779 const char* compression = input.data.options.compression;
780
781 if (width == 0 || height == 0) {
782 snprintf(output.header.err, sizeof(output.header.err), "encodeGray: width and height must be > 0");
783 write_output_message(&output);
784 goto cleanup;
785 }
786
787 avifImage *image = avifImageCreate(width, height, depth, AVIF_PIXEL_FORMAT_YUV400);
788 if (!image) {
789 snprintf(output.header.err, sizeof(output.header.err), "encodeGray: Failed to create avifImage");
790 write_output_message(&output);
791 goto cleanup;
792 }
793
794 // Set color properties from input if provided, otherwise use depth-based defaults.
795 if (input.data.params.colorPrimaries > 0) {
796 image->colorPrimaries = input.data.params.colorPrimaries;
797 image->transferCharacteristics = input.data.params.transferCharacteristics;
798 image->matrixCoefficients = input.data.params.matrixCoefficients;
799 } else if (depth > 8) {
800 // Default for 10-bit+: BT.2020/PQ (HDR).
801 image->colorPrimaries = AVIF_COLOR_PRIMARIES_BT2020;
802 image->transferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_PQ;
803 image->matrixCoefficients = AVIF_MATRIX_COEFFICIENTS_BT2020_NCL;
804 } else {
805 // Default for 8-bit: BT.709/sRGB (SDR).
806 image->colorPrimaries = AVIF_COLOR_PRIMARIES_BT709;
807 image->transferCharacteristics = AVIF_TRANSFER_CHARACTERISTICS_SRGB;
808 image->matrixCoefficients = AVIF_MATRIX_COEFFICIENTS_BT601;
809 }
810 image->yuvRange = AVIF_RANGE_FULL;
811
812 if (input.data.params.maxCLL > 0 || input.data.params.maxPALL > 0) {
813 image->clli.maxCLL = (uint16_t)input.data.params.maxCLL;
814 image->clli.maxPALL = (uint16_t)input.data.params.maxPALL;
815 }
816
817 avifResult alloc_result = avifImageAllocatePlanes(image, AVIF_PLANES_YUV);
818 if (alloc_result != AVIF_RESULT_OK) {
819 snprintf(output.header.err, sizeof(output.header.err), "encodeGray: Failed to allocate planes: %s", avifResultToString(alloc_result));
820 avifImageDestroy(image);
821 write_output_message(&output);
822 goto cleanup;
823 }
824 uint8_t *src = blob_data;
825 uint8_t *dst = image->yuvPlanes[AVIF_CHAN_Y];
826 size_t row_bytes = width * bytes_per_sample;
827 for (int i = 0; i < height; ++i) {
828 memcpy(dst, src, row_bytes);
829 src += stride;
830 dst += image->yuvRowBytes[AVIF_CHAN_Y];
831 }
832
833
834 avifEncoder *encoder = avifEncoderCreate();
835 if (!encoder) {
836 snprintf(output.header.err, sizeof(output.header.err), "encodeGray: Failed to create encoder");
837 avifImageDestroy(image);
838 write_output_message(&output);
839 goto cleanup;
840 }
841 encoder->codecChoice = AVIF_CODEC_CHOICE_AOM;
842
843 if (strcmp(compression, "lossless") == 0) {
844 encoder->quality = AVIF_QUALITY_LOSSLESS;
845 } else {
846 // Map Hugo quality 1-100 to libavif quality 0-100 (higher is better).
847 if (quality < 1) quality = 1;
848 if (quality > 100) quality = 100;
849 int avif_quality = (int)((quality - 1.0) / 99.0 * 100.0);
850 // Keep lossy strictly below lossless so quality 100 stays lossy. See issue 14981.
851 if (avif_quality >= AVIF_QUALITY_LOSSLESS) avif_quality = AVIF_QUALITY_LOSSLESS - 1;
852 encoder->quality = avif_quality;
853 }
854 encoder->qualityAlpha = AVIF_QUALITY_LOSSLESS;
855 encoder->speed = (input.data.options.encoderSpeed >= 1 && input.data.options.encoderSpeed <= 10)
856 ? input.data.options.encoderSpeed
857 : 10;
858 encoder->autoTiling = AVIF_TRUE;
859
860 avifResult result = avifEncoderAddImage(encoder, image, 1, AVIF_ADD_IMAGE_FLAG_SINGLE);
861 if (result != AVIF_RESULT_OK) {
862 encoder_errf(output.header.err, sizeof(output.header.err), "encodeGray: Failed to add image to encoder", result, encoder);
863 avifEncoderDestroy(encoder);
864 avifImageDestroy(image);
865 write_output_message(&output);
866 goto cleanup;
867 }
868
869 avifRWData raw = { NULL, 0 };
870 result = avifEncoderFinish(encoder, &raw);
871 if (result != AVIF_RESULT_OK) {
872 encoder_errf(output.header.err, sizeof(output.header.err), "encodeGray: Failed to finish encoding", result, encoder);
873 avifEncoderDestroy(encoder);
874 avifImageDestroy(image);
875 write_output_message(&output);
876 goto cleanup;
877 }
878
879 write_output_message(&output);
880 write_blob(output.header.id, raw.data, raw.size);
881
882 avifRWDataFree(&raw);
883 avifEncoderDestroy(encoder);
884 avifImageDestroy(image);
885
886 goto cleanup;
887 }
888 else
889 {
890 snprintf(output.header.err, sizeof(output.header.err), "Unknown command: %s", input.header.command);
891 write_output_message(&output);
892 }
893
894 cleanup:
895 if (blob_data != NULL)
896 {
897 free(blob_data);
898 }
899 if (input.data.params.frameDurations != NULL)
900 {
901 free(input.data.params.frameDurations);
902 }
903 }
904 }