File: jxl.c

package info (click to toggle)
graphicsmagick 1.4%2Breally1.3.40-4%2Bdeb12u1
  • links: PTS
  • area: main
  • in suites: bookworm
  • size: 40,072 kB
  • sloc: ansic: 245,408; cpp: 18,712; sh: 11,427; perl: 3,521; makefile: 2,521; tcl: 2,211; python: 1,250
file content (1643 lines) | stat: -rw-r--r-- 57,207 bytes parent folder | download
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
/*
% Copyright (C) 2022 GraphicsMagick Group
%
% This program is covered by multiple licenses, which are described in
% Copyright.txt. You should have received a copy of Copyright.txt with this
% package; otherwise see http://www.graphicsmagick.org/www/Copyright.html.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                   J  X X  L                                 %
%                                   J   X   L                                 %
%                                 JJJ  X X  LLL                               %
%                                                                             %
%                        Read/Write JPEG-XL Image Format.                     %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Status: Only support basic images (no animations) with grayscale/SRGB colorspace
* Note that JXL is a C++ library so does require linking with a c++ compiler.
*
* Currently tested vs libjxl-0.7.0 on ubuntu only, likely will have build problems
* on other platforms. Also note the amount of third-party-libs required!
*
* Libjxl requires the full uncompressed image in memory in order to compress,
* so it requires a lot of memory when writing.
*
* Features which work:
*
*   * Gray and RGB images
*   * 8, and 16 bit integer samples
*   * 16 and 32-bit float samples
*   * Store/Read ICC, EXIF, and XMP profiles
*   * Resource-limited memory allocator
*
* Features still to be completed:
*
*   * Multiple frames / animations
*   * Premultiplied alpha
*   * Alpha bits != RGB sample bits
*   * CMYK layers
*   * Progressive images
*   * Progress monitor
*   * Linear images (needs improvement)
*/

#include "magick/studio.h"
#include "magick/analyze.h"
#include "magick/blob.h"
#include "magick/colormap.h"
#include "magick/log.h"
#include "magick/constitute.h"
#include "magick/magick.h"
#include "magick/monitor.h"
#include "magick/pixel_cache.h"
#include "magick/profile.h"
#include "magick/utility.h"
#include "magick/resource.h"

#if defined(HasJXL)
#include <jxl/decode.h>
#include <jxl/encode.h>
#include <jxl/thread_parallel_runner.h>

#define MaxBufferExtent 65536

struct MyJXLMemoryManager {
  JxlMemoryManager super;
  ExceptionInfo *exception;
  const char *filename;
};

static void *MyJXLMalloc(void *opaque, size_t size)
{
  unsigned char
    *data=MagickAllocateResourceLimitedMemory(unsigned char *,size);
  if (data == (unsigned char *) NULL)
    {
      struct MyJXLMemoryManager
        *mm = (struct MyJXLMemoryManager*)opaque;
      ThrowException(mm->exception, ResourceLimitError,MemoryAllocationFailed,
                     mm->filename);
    }
  return data;
}

static void MyJXLFree(void *dummy, void *address)
{
  (void)(dummy);
  MagickFreeResourceLimitedMemory(address);
}

static void MyJxlMemoryManagerInit(struct MyJXLMemoryManager *mm,
                                   Image *image,ExceptionInfo *exception)
{
  mm->exception=exception;
  mm->filename=image->filename;
  mm->super.opaque=mm;
  mm->super.alloc=MyJXLMalloc;
  mm->super.free=MyJXLFree;
}
static const char *JxlDataTypeAsString(const JxlDataType data_type)
{
  const char *str = "Unknown";

  switch (data_type)
    {
    case JXL_TYPE_FLOAT:
      str = "Float";
      break;
    case JXL_TYPE_UINT8:
      str = "UINT8";
      break;
    case JXL_TYPE_UINT16:
      str = "UINT16";
      break;
    case JXL_TYPE_FLOAT16:
      str = "FLOAT16";
      break;
    }

  return str;
}

static QuantumSampleType JxlDataTypeToQuantumSampleType(const JxlDataType data_type)
{
  QuantumSampleType
    sample_type = UndefinedQuantumSampleType;

  switch (data_type)
    {
    case JXL_TYPE_FLOAT:
      sample_type = FloatQuantumSampleType;
      break;
    case JXL_TYPE_UINT8:
      sample_type = UnsignedQuantumSampleType;
      break;
    case JXL_TYPE_UINT16:
      sample_type = UnsignedQuantumSampleType;
      break;
    case JXL_TYPE_FLOAT16:
      sample_type = FloatQuantumSampleType;
      break;
    }
  return sample_type;
}

static unsigned int JxlDataTypeToQuantumSize(const JxlDataType data_type)
{
  unsigned int
    quantum_size = 0;

  switch (data_type)
    {
    case JXL_TYPE_FLOAT:
      quantum_size = 32;
      break;
    case JXL_TYPE_UINT8:
      quantum_size = 8;
      break;
    case JXL_TYPE_UINT16:
      quantum_size = 16;
      break;
    case JXL_TYPE_FLOAT16:
      quantum_size = 16;
      break;
    }
  return quantum_size;
}

static const char *JxlExtraChannelTypeAsString(const JxlExtraChannelType extra_channel_type)
{
  const char *str = "Unknown";

  /* Defined in jxl/codestream_header.h */
  switch (extra_channel_type)
    {
    case JXL_CHANNEL_ALPHA:
      str = "Alpha";
      break;
    case JXL_CHANNEL_DEPTH:
      str = "Depth";
      break;
    case JXL_CHANNEL_SPOT_COLOR:
      str = "SpotColor";
      break;
    case JXL_CHANNEL_SELECTION_MASK:
      str = "SelectionMask";
      break;
    case JXL_CHANNEL_BLACK:
      str = "Black";
      break;
    case JXL_CHANNEL_CFA:
      str = "CFA";
      break;
    case JXL_CHANNEL_THERMAL:
      str = "Thermal";
      break;
    case JXL_CHANNEL_RESERVED0:
      str = "RESERVED0";
      break;
    case JXL_CHANNEL_RESERVED1:
      str = "RESERVED1";
      break;
    case JXL_CHANNEL_RESERVED2:
      str = "RESERVED2";
      break;
    case JXL_CHANNEL_RESERVED3:
      str = "RESERVED3";
      break;
    case JXL_CHANNEL_RESERVED4:
      str = "RESERVED4";
      break;
    case JXL_CHANNEL_RESERVED5:
      str = "RESERVED5";
      break;
    case JXL_CHANNEL_RESERVED6:
      str = "RESERVED6";
      break;
    case JXL_CHANNEL_RESERVED7:
      str = "RESERVED7";
      break;
    case JXL_CHANNEL_UNKNOWN:
      str = "Unknown";
      break;
    case JXL_CHANNEL_OPTIONAL:
      str = "Optional";
      break;
    }

  return str;
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e a d J X L I m a g e                                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ReadJXLImage() reads an image in the JXL image format.
%
%  The format of the ReadJXLImage method is:
%
%      Image *ReadJXLImage(const ImageInfo *image_info,
%        ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image_info: the image info.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static inline OrientationType convert_orientation(JxlOrientation orientation)
{
  switch (orientation)
    {
    default:
    case JXL_ORIENT_IDENTITY:
      return TopLeftOrientation;
    case JXL_ORIENT_FLIP_HORIZONTAL:
      return TopRightOrientation;
    case JXL_ORIENT_ROTATE_180:
      return BottomRightOrientation;
    case JXL_ORIENT_FLIP_VERTICAL:
      return BottomLeftOrientation;
    case JXL_ORIENT_TRANSPOSE:
      return LeftTopOrientation;
    case JXL_ORIENT_ROTATE_90_CW:
      return RightTopOrientation;
    case JXL_ORIENT_ANTI_TRANSPOSE:
      return RightBottomOrientation;
    case JXL_ORIENT_ROTATE_90_CCW:
      return LeftBottomOrientation;
    }
}

/** Convert any linear RGB to SRGB
 *  Formula from wikipedia:
 *      https://en.wikipedia.org/wiki/SRGB
 */
static void linear2nonlinear_quantum(Quantum *q)
{
  double p = *q * (1.0/256.0);
  if (p < 0.0031308) {
    p=p * 12.92;
  } else {
    p=1.055 * pow(p, 1.0/2.4) - 0.055;
  }
  *q = RoundDoubleToQuantum(p * MaxRGBDouble);
}

static const char *JxlTransferFunctionAsString(const JxlTransferFunction fn)
{
  const char *str = "Unknown";

  switch (fn)
    {
    case JXL_TRANSFER_FUNCTION_709:
      str = "Rec709 (SMPTE RP 431-2)";
      break;
    case JXL_TRANSFER_FUNCTION_UNKNOWN:
      str = "Unknown";
      break;
    case JXL_TRANSFER_FUNCTION_LINEAR:
      str = "Linear (Gamma 1.0)";
      break;
    case JXL_TRANSFER_FUNCTION_SRGB:
      str = "sRGB (IEC 61966-2-1)";
      break;
    case JXL_TRANSFER_FUNCTION_PQ:
      str = "PQ (SMPTE ST 428-1)";
      break;
    case JXL_TRANSFER_FUNCTION_DCI:
      str = "DCI (SMPTE ST 428-1)";
      break;
    case JXL_TRANSFER_FUNCTION_HLG:
      str = "HLG (Rec. ITU-R BT.2100-1)";
      break;
    case JXL_TRANSFER_FUNCTION_GAMMA:
      str = "Gamma (use gamma from JxlColorEncoding)";
      break;
    }

  return str;
}

static const char *JxlColorSpaceAsString(const JxlColorSpace color_space)
{
  const char *str = "Unknown";

  switch (color_space)
    {
    case JXL_COLOR_SPACE_RGB:
      str = "Tristimulus RGB";
      break;
    case JXL_COLOR_SPACE_GRAY:
      str = "Luminance based (Gray)";
      break;
    case JXL_COLOR_SPACE_XYB:
      str = "XYB (opsin)";
      break;
    case JXL_COLOR_SPACE_UNKNOWN:
      str = "Unknown";
      break;
    }

  return str;
}


#define JXLReadCleanup()                                \
  MagickFreeResourceLimitedMemory(out_buf);             \
  MagickFreeResourceLimitedMemory(in_buf);              \
  MagickFreeResourceLimitedMemory(exif_profile);        \
  MagickFreeResourceLimitedMemory(xmp_profile);         \
  if (jxl_thread_runner)                                \
    JxlThreadParallelRunnerDestroy(jxl_thread_runner);  \
  if (jxl_decoder)                                      \
    JxlDecoderDestroy(jxl_decoder);


#define ThrowJXLReaderException(code_,reason_,image_)   \
  {                                                     \
    JXLReadCleanup();                                   \
    ThrowReaderException(code_,reason_,image_);         \
  }

static Image *ReadJXLImage(const ImageInfo *image_info,
                           ExceptionInfo *exception)
{
  Image
    *image;

  JxlDecoder
    *jxl_decoder = NULL;

  void
    *jxl_thread_runner = NULL;

  JxlDecoderStatus
    status;

  JxlPixelFormat
    pixel_format;

  JxlExtraChannelInfo
    extra_channel_info[5];

  struct MyJXLMemoryManager
    mm;

  const size_t
    in_len = MaxBufferExtent;

  unsigned char
    *in_buf = NULL,
    *out_buf = NULL;

  MagickBool
    grayscale = MagickFalse;

  MagickBool
    isLinear = MagickFalse;

  magick_off_t
    blob_len = 0;

  unsigned char
    *exif_profile = NULL,
    *xmp_profile = NULL;

  size_t
    exif_size = 0,
    exif_pad = 2,
    xmp_size = 0;

  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);

  memset(&pixel_format,0,sizeof(pixel_format));

  /*
    Open image file.
  */
  image=AllocateImage(image_info);
  if (image == (Image *) NULL)
    ThrowReaderException(ResourceLimitError,MemoryAllocationFailed,image);

  if (OpenBlob(image_info,image,ReadBinaryBlobMode,exception) == MagickFail)
    ThrowReaderException(FileOpenError,UnableToOpenFile,image);

  /* Init JXL-Decoder handles */
  MyJxlMemoryManagerInit(&mm,image,exception);
  jxl_decoder=JxlDecoderCreate(&mm.super);
  if (jxl_decoder == (JxlDecoder *) NULL)
    ThrowReaderException(ResourceLimitError,MemoryAllocationFailed,image);

  /* Deliver image as-is. We provide autoOrient function if user requires it */
  if (JxlDecoderSetKeepOrientation(jxl_decoder, JXL_TRUE) != JXL_DEC_SUCCESS)
    ThrowJXLReaderException(ResourceLimitError,MemoryAllocationFailed,image);

  /* Apply any pre-multiplied alpha for us so we don't need to do it. */
  (void) JxlDecoderSetUnpremultiplyAlpha(jxl_decoder, JXL_TRUE);

  if(!image_info->ping)
    {
      jxl_thread_runner=JxlThreadParallelRunnerCreate(NULL,(size_t) GetMagickResourceLimit(ThreadsResource));
      if (jxl_thread_runner == (void *) NULL)
        ThrowJXLReaderException(ResourceLimitError,MemoryAllocationFailed,image);
      if (JxlDecoderSetParallelRunner(jxl_decoder, JxlThreadParallelRunner, jxl_thread_runner)
          != JXL_DEC_SUCCESS)
        ThrowJXLReaderException(ResourceLimitError,MemoryAllocationFailed,image);
    }

  if (JxlDecoderSubscribeEvents(jxl_decoder,
                                (JxlDecoderStatus)(image_info->ping == MagickTrue
                                                   ? (JXL_DEC_BASIC_INFO |
                                                      JXL_DEC_BOX)
                                                   : (JXL_DEC_BASIC_INFO |
                                                      JXL_DEC_FULL_IMAGE |
                                                      JXL_DEC_COLOR_ENCODING |
                                                      JXL_DEC_BOX))
                                ) != JXL_DEC_SUCCESS)
    ThrowJXLReaderException(ResourceLimitError,MemoryAllocationFailed,image);

  in_buf=MagickAllocateResourceLimitedArray(unsigned char *,in_len,sizeof(*in_buf));
  if (in_buf == (unsigned char *) NULL)
    ThrowJXLReaderException(ResourceLimitError,MemoryAllocationFailed,image);

  blob_len = GetBlobSize(image);

  status=JXL_DEC_NEED_MORE_INPUT;
  while (status != JXL_DEC_ERROR && status != JXL_DEC_SUCCESS)
    {
      switch (status)
        {
        case JXL_DEC_NEED_MORE_INPUT:
          { /* read something from blob */
            size_t
              remaining = JxlDecoderReleaseInput(jxl_decoder),
              count;

            if (remaining > 0)
              memmove(in_buf,in_buf+in_len-remaining,remaining);
            count=ReadBlob(image,in_len-remaining,in_buf+remaining);
            if (count == 0)
              ThrowJXLReaderException(CorruptImageError, UnexpectedEndOfFile, image);
            status = JxlDecoderSetInput(jxl_decoder,(const uint8_t *) in_buf, (size_t) count);
            if (blob_len > 0)
              {
                /* If file size is known pass the info about the last block,
                   to the decoder. Note that the call is currently optional */
                blob_len -= count;
                if (blob_len == 0)
                  JxlDecoderCloseInput(jxl_decoder);
              }
            break;
          }
        case JXL_DEC_BASIC_INFO:
          { /* got image information */
            JxlBasicInfo
              basic_info;

            JxlEncoderInitBasicInfo(&basic_info);

            status=JxlDecoderGetBasicInfo(jxl_decoder,&basic_info);
            if (status != JXL_DEC_SUCCESS)
              break;

            if (image->logging)
              {
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                      "Basic Info:\n"
                                      "    xsize=%u\n"
                                      "    ysize=%u \n"
                                      "    bits_per_sample=%u\n"
                                      "    exponent_bits_per_sample=%u\n"
                                      "    alpha_bits=%u\n"
                                      "    num_color_channels=%u\n"
                                      "    have_animation=%s",
                                      basic_info.xsize, basic_info.ysize,
                                      basic_info.bits_per_sample, basic_info.exponent_bits_per_sample,
                                      basic_info.alpha_bits, basic_info.num_color_channels,
                                      basic_info.have_animation == JXL_FALSE ? "False" : "True");
              }

            if (basic_info.num_extra_channels)
              {
                size_t index;
                (void) memset(extra_channel_info,0,sizeof(extra_channel_info));
                for (index = 0 ;index < Min(basic_info.num_extra_channels,
                                            ArraySize(extra_channel_info));
                     index++)
                  {
                    JxlExtraChannelInfo* ecip=&extra_channel_info[index];
                    status=JxlDecoderGetExtraChannelInfo(jxl_decoder,
                                                         index,
                                                         ecip);
                    if (JXL_DEC_SUCCESS == status)
                      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                            "Extra Channel Info[%lu]:\n"
                                            "    type=%s\n"
                                            "    bits_per_sample=%u\n"
                                            "    exponent_bits_per_sample=%u\n"
                                            "    dim_shift=%u\n"
                                            "    name_length=%u\n"
                                            "    alpha_premultiplied=%s\n"
                                            "    spot_color=%f,%f,%f,%f\n"
                                            "    cfa_channel=%u"
                                          ,
                                            (unsigned long) index,
                                            JxlExtraChannelTypeAsString(ecip->type),
                                            ecip->bits_per_sample,
                                            ecip->exponent_bits_per_sample,
                                            ecip->dim_shift,
                                            ecip->name_length,
                                            ecip->alpha_premultiplied == JXL_FALSE ? "False" : "True",
                                            ecip->spot_color[0],ecip->spot_color[1],
                                            ecip->spot_color[2],ecip->spot_color[3],
                                            ecip->cfa_channel);
                  }
              }

            if (basic_info.have_animation == 1)
              ThrowJXLReaderException(CoderError, ImageTypeNotSupported, image);

            image->columns=basic_info.xsize;
            image->rows=basic_info.ysize;
            image->depth=basic_info.bits_per_sample;
            if (basic_info.alpha_bits != 0)
              image->matte=MagickTrue;

            image->orientation=convert_orientation(basic_info.orientation);

            if (CheckImagePixelLimits(image, exception) != MagickPass)
              ThrowJXLReaderException(ResourceLimitError,ImagePixelLimitExceeded,image);

            pixel_format.endianness=JXL_NATIVE_ENDIAN;
            pixel_format.align=0;
            if (basic_info.num_color_channels == 1)
              {
                if ((basic_info.bits_per_sample <= 8) && (!image->matte))
                  {
                    unsigned long
                      max_value_given_bits;

                    max_value_given_bits=MaxValueGivenBits(basic_info.bits_per_sample);
                    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                          "max_value_given_bits=%lu",max_value_given_bits);

                    if (!AllocateImageColormap(image,max_value_given_bits+1))
                      ThrowJXLReaderException(ResourceLimitError,MemoryAllocationFailed,image);
                  }
                grayscale=MagickTrue;
                pixel_format.num_channels=image->matte ? 2 : 1;
                pixel_format.data_type=(basic_info.bits_per_sample <= 8 ? JXL_TYPE_UINT8 :
                                  (basic_info.bits_per_sample <= 16 ? JXL_TYPE_UINT16 :
                                   JXL_TYPE_FLOAT));
              }
            else if (basic_info.num_color_channels == 3)
              {
                pixel_format.num_channels=image->matte ? 4 : 3;
                pixel_format.data_type=(basic_info.bits_per_sample <= 8 ? JXL_TYPE_UINT8 :
                                  (basic_info.bits_per_sample <= 16 ? JXL_TYPE_UINT16 :
                                   JXL_TYPE_FLOAT));
              }
            else
              {
                ThrowJXLReaderException(CoderError, ImageTypeNotSupported, image);
              }
            break;
          }

        case JXL_DEC_COLOR_ENCODING:
          {
            /* check the colorspace that will be used for output buffer
             *
             * The JXL API does return the pixels in their original colorspace
             * which has a large number of possibilities with profiles etc.
             *
             * We need to try to convert this to the internel SRGB Colorspace
             * as best as possibly. Better to read a image somewhat bogus then
             * to error out.
             *
             * Handling is inspired by the JXL lib example for the GIMP-Plugin.
             */
            JxlColorEncoding
              color_encoding;

            status=JxlDecoderGetColorAsEncodedProfile(jxl_decoder,&pixel_format,
                                                      JXL_COLOR_PROFILE_TARGET_DATA,&color_encoding);
            if (status == JXL_DEC_ERROR)
              {
                status=JXL_DEC_SUCCESS;
                if (image->logging)
                  {
                    (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                          "[%s] failed to get ColorEncoding assuming SRGB",
                                          image->filename);
                  }
              }
            else if (status == JXL_DEC_SUCCESS)
              {
                /*
                  Transfer function if have_gamma is 0
                 */
                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                      "Color Transfer Function: %s",
                                      JxlTransferFunctionAsString(color_encoding.transfer_function));
                switch (color_encoding.transfer_function) {
                case JXL_TRANSFER_FUNCTION_LINEAR:
                  isLinear=MagickTrue;
                  break;
                case JXL_TRANSFER_FUNCTION_709:
                  isLinear=MagickFalse;
                  break;
                case JXL_TRANSFER_FUNCTION_PQ:
                  isLinear=MagickFalse;
                  break;
                case JXL_TRANSFER_FUNCTION_HLG:
                  isLinear=MagickFalse;
                  break;
                case JXL_TRANSFER_FUNCTION_GAMMA:
                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                        "Gamma: %g", color_encoding.gamma);
                  isLinear=MagickFalse;
                  break;
                case JXL_TRANSFER_FUNCTION_DCI:
                  isLinear=MagickFalse;
                  break;
                case JXL_TRANSFER_FUNCTION_SRGB:
                  isLinear=MagickFalse;
                  break;

                case JXL_TRANSFER_FUNCTION_UNKNOWN:
                default:
                  ThrowJXLReaderException(CoderError, ImageTypeNotSupported, image);
                }

                (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                      "Color Space: %s",
                                      JxlColorSpaceAsString(color_encoding.color_space));

                /*
                  Color space of the image data.
                 */
                switch (color_encoding.color_space) {
                case JXL_COLOR_SPACE_RGB:
                  if (color_encoding.white_point == JXL_WHITE_POINT_D65 &&
                      color_encoding.primaries == JXL_PRIMARIES_SRGB)
                    {
                      /* ok */
                    }
                  else if(!isLinear &&
                          color_encoding.white_point == JXL_WHITE_POINT_D65 &&
                          (color_encoding.primaries_green_xy[0] == 0.2100 ||
                           color_encoding.primaries_green_xy[1] == 0.7100))
                    {
                      /* Probably Adobe RGB */
                      ThrowJXLReaderException(CoderError, ImageTypeNotSupported, image);
                    }
                  else if (image->logging)
                    {
                      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                            "[%s] Unknown colorspace assume SRGB",
                                            image->filename);
                    }
                  break;
                case JXL_COLOR_SPACE_GRAY:
                  if (!grayscale)
                    ThrowJXLReaderException(CoderError, ImageTypeNotSupported, image);
                  break;
                case JXL_COLOR_SPACE_XYB:
                case JXL_COLOR_SPACE_UNKNOWN:
                default:
                  if (image->logging)
                    {
                      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                            "[%s] Unsupported/Unknown colorspace treat as SRGB",
                                            image->filename);
                    }
                  break;
                }
              }
            /*
              Get original ICC-profile and store as metadata
            */
            {
              size_t
                profile_size;

              if (JxlDecoderGetICCProfileSize(jxl_decoder,&pixel_format,
                                              JXL_COLOR_PROFILE_TARGET_ORIGINAL,&profile_size)
                  == JXL_DEC_SUCCESS)
                {
                  unsigned char
                    *profile;

                  if ((profile=MagickAllocateResourceLimitedMemory(unsigned char *,profile_size))
                      != NULL)
                    {
                      if (JxlDecoderGetColorAsICCProfile(jxl_decoder,&pixel_format,
                                                         JXL_COLOR_PROFILE_TARGET_ORIGINAL,
                                                         profile,
                                                         profile_size) == JXL_DEC_SUCCESS)
                        {
                          (void) SetImageProfile(image,"ICM",profile,profile_size);
                        }
                      MagickFreeResourceLimitedMemory(profile);
                    }
                }
            }
            break;
          }
        case JXL_DEC_NEED_IMAGE_OUT_BUFFER:
          { /* allocate output buffer */
            size_t
              out_len;

            if (image->logging)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                    "JxlPixelFormat:\n"
                                    "    num_channels: %u\n"
                                    "    data_type: %s\n"
                                    "    endianness: %s\n"
                                    "    align: %" MAGICK_SIZE_T_F "u",
                                    pixel_format.num_channels,
                                    pixel_format.data_type == JXL_TYPE_FLOAT ? "float" :
                                    (pixel_format.data_type == JXL_TYPE_UINT8 ? "uint8" :
                                     (pixel_format.data_type == JXL_TYPE_UINT16 ? "uint16" :
                                      (pixel_format.data_type == JXL_TYPE_FLOAT16 ? "float16" :
                                       "unknown"))) ,
                                    pixel_format.endianness == JXL_NATIVE_ENDIAN ? "native" :
                                    (pixel_format.endianness == JXL_LITTLE_ENDIAN ? "little" :
                                     (pixel_format.endianness == JXL_BIG_ENDIAN ? "big" : "unknown")),
                                    pixel_format.align);

            status=JxlDecoderImageOutBufferSize(jxl_decoder,&pixel_format,&out_len);
            if (status != JXL_DEC_SUCCESS)
              break;

            if (image->logging)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                    "JxlDecoderImageOutBufferSize() returns %" MAGICK_SIZE_T_F "u",
                                    (MAGICK_SIZE_T) out_len);
            out_buf=MagickAllocateResourceLimitedArray(unsigned char *,out_len,sizeof(*out_buf));
            if (out_buf == (unsigned char *) NULL)
              ThrowJXLReaderException(ResourceLimitError,MemoryAllocationFailed,image);

            status=JxlDecoderSetImageOutBuffer(jxl_decoder,&pixel_format,out_buf,out_len);
            break;
          }
        case JXL_DEC_FULL_IMAGE:
          { /* got image */
            long
              x,
              y;

            PixelPacket
              *q;

            unsigned char
              *p;

            ImportPixelAreaOptions
              import_options;

            ImportPixelAreaInfo
              import_area_info;

            unsigned int
              quantum_size;

            QuantumType
              quantum_type;

            QuantumSampleType
              sample_type;

            MagickPassFail
              res=MagickPass;

            assert(out_buf != (unsigned char *)NULL);

            quantum_size = JxlDataTypeToQuantumSize(pixel_format.data_type);
            sample_type = JxlDataTypeToQuantumSampleType(pixel_format.data_type);

            if (grayscale)
              {
                if (image->matte)
                  quantum_type = GrayAlphaQuantum;
                else
                  quantum_type = GrayQuantum;
              }
            #if 0
            else if (cmyk)
              {
                if (image->matte)
                  quantum_type = CMYKAQuantum;
                else
                  quantum_type = CMYKQuantum;
              }
            #endif
            else
              {
                if (image->matte)
                  quantum_type = RGBAQuantum;
                else
                  quantum_type = RGBQuantum;
              }

            ImportPixelAreaOptionsInit(&import_options);
            import_options.sample_type = sample_type;
            import_options.endian = NativeEndian;

            p = out_buf;
            for (y=0; y < (long) image->rows; y++)
              {
                q=SetImagePixelsEx(image,0,y,image->columns,1,exception);
                if (q == (PixelPacket *) NULL)
                  {
                    res = MagickFail;
                    break;
                  }

                if ((res = ImportImagePixelArea(image,quantum_type,quantum_size,
                                                p,
                                                &import_options,&import_area_info))
                    != MagickPass)
                  break;
                // Promote linear image to sRGB (2.4 gamma).
                // We could also set image->gamma and return the original image.
#if 1
                if (isLinear)
                  {
                    for (x = 0 ; x < (long) image->columns ; x++)
                      {
                        linear2nonlinear_quantum(&q[x].red);
                        if (grayscale)
                          {
                            q[x].green = q[x].blue = q[x].red;
                          }
                        else
                          {
                            linear2nonlinear_quantum(&q[x].green);
                            linear2nonlinear_quantum(&q[x].blue);
                          }
                      }
                  }
#endif
                p += import_area_info.bytes_imported;

                if (!SyncImagePixels(image))
                  {
                    res = MagickFail;
                    break;
                  }
              }

            if (!res)
              status=JXL_DEC_ERROR;
            break;
          }
          case JXL_DEC_BOX:
            {
              do
                {
                  JxlBoxType
                    type; /* A 4 character string which is not null terminated! */

                  magick_uint64_t
                    profile_size = 0;

                  unsigned char
                    *profile;

                  /* Release buffer to get box data */
                  (void) JxlDecoderReleaseBoxBuffer(jxl_decoder);

                  /* Get the 4-character box typename */
                  if (JxlDecoderGetBoxType(jxl_decoder,type,JXL_FALSE) != JXL_DEC_SUCCESS)
                    break;

                  /* Get the size of the box as it appears in the container file, not decompressed. */
                  if (JxlDecoderGetBoxSizeRaw(jxl_decoder, &profile_size) != JXL_DEC_SUCCESS)
                    break;

                  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                        "JXL Box of type \"%c%c%c%c\" and %lu bytes",
                                        type[0],type[1],type[2],type[3], (unsigned long) profile_size);

                  /* Ignore tiny profiles */
                  if (profile_size < 4)
                    break;

                  if (LocaleNCompare(type,"Exif",sizeof(type)) == 0)
                    {
                      /*
                        Allocate EXIF profile box buffer (plus a bit more)
                      */
                      if ((profile=MagickAllocateResourceLimitedClearedMemory(unsigned char *,
                                                                              profile_size+exif_pad))
                          != NULL)
                        {
                          if (JxlDecoderSetBoxBuffer(jxl_decoder,profile+exif_pad,profile_size)
                              == JXL_DEC_SUCCESS)
                            {
                              exif_profile=profile;
                              exif_size=profile_size;
                            }
                        }
                    }
                  if (LocaleNCompare(type,"xml ",sizeof(type)) == 0)
                    {
                      /*
                        Allocate XMP profile box buffer
                      */
                      if ((profile=MagickAllocateResourceLimitedMemory(unsigned char *,profile_size))
                          != NULL)
                        {
                          if (JxlDecoderSetBoxBuffer(jxl_decoder,profile,profile_size) == JXL_DEC_SUCCESS)
                            {
                              xmp_profile=profile;
                              xmp_size=profile_size;
                            }
                        }
                    }
                } while(0);
              break;
            }
        default:
          /* unexpected status is error.
           * - JXL_DEC_SUCCESS should never happen here so it's also an error
           */
          status=JXL_DEC_ERROR;
          break;
        }
      if (status == JXL_DEC_ERROR)
        break;
      status = JxlDecoderProcessInput(jxl_decoder);
    }
  /* Release buffer to get box data in the buffers which were passed */
  (void) JxlDecoderReleaseBoxBuffer(jxl_decoder);
  if (exif_profile != NULL)
    {
      /*
        Read Exif profile

        The EXIF box starts with a 4-byte offset to
        the TIFF header (and may be 0).

        The EXIF profile blob needs to be prefixed
        with "Exif\0\0" prior to the TIFF header.

        The buffer provided to libjxl is offset to allow adding our
        header.
      */
      unsigned char *p = exif_profile;
      magick_uint32_t exif_profile_offset;

      (void) memcpy(&exif_profile_offset,p+exif_pad,sizeof(exif_profile_offset));
#if 0
      fprintf(stderr,
              "BOX-1: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n",
              p[0], p[1],p[2], p[3], p[4], p[5], p[6], p[7],  p[8],  p[9],  p[10],  p[11]);
#endif

      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                            "EXIF Box: Size %lu, Offset %u",
                            (unsigned long) exif_size, exif_profile_offset);

      /*
        FIXME: If the TIFF header offset is not zero, then need to
        move the TIFF data forward to the correct offset.
      */

      p[0]='E';
      p[1]='x';
      p[2]='i';
      p[3]='f';
      p[4]='\0';
      p[5]='\0';

#if 0
      fprintf(stderr,
              "BOX-2: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n",
              p[0], p[1],p[2], p[3], p[4], p[5], p[6], p[7],  p[8],  p[9],  p[10],  p[11]);
#endif
      (void) SetImageProfile(image,"EXIF",exif_profile,exif_size+exif_pad);

      MagickFreeResourceLimitedMemory(exif_profile);
    }
  if (xmp_profile != NULL)
    {
      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                            "XMP Box: Size %lu", (unsigned long) exif_size);
      (void) SetImageProfile(image,"XMP",xmp_profile,xmp_size);
      MagickFreeResourceLimitedMemory(xmp_profile);
    }
  /* every break outside of success is some kind of error */
  if (status != JXL_DEC_SUCCESS) {
    /* no details available */
    ThrowJXLReaderException(CorruptImageError, AnErrorHasOccurredReadingFromFile, image);
  }

  JXLReadCleanup();
  CloseBlob(image);
  return image;
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   W r i t e J X L I m a g e                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  WriteJXLImage() writes an image in the JXL image format.
%
%  The format of the WriteJXLImage method is:
%
%      MagickPassFail WriteJXLImage(const ImageInfo *image_info, Image *image)
%
%  A description of each parameter follows.
%
%    o image_info: the image info.
%
%    o image:  The image.
%
*/

#define JXLWriteCleanup() \
  if (jxl_thread_runner) JxlThreadParallelRunnerDestroy(jxl_thread_runner); \
  if (jxl_encoder) JxlEncoderDestroy(jxl_encoder); \
  MagickFreeResourceLimitedMemory(in_buf); \
  MagickFreeResourceLimitedMemory(out_buf); \

#define ThrowJXLWriterException(code_,reason_,image_) \
do { \
  JXLWriteCleanup();                          \
  ThrowWriterException(code_,reason_,image_); \
 } while(1)

static unsigned int WriteJXLImage(const ImageInfo *image_info,Image *image)
{
  MagickPassFail
    status;

  JxlEncoder
    *jxl_encoder = NULL;

  void
    *jxl_thread_runner = NULL;

  JxlEncoderFrameSettings
    *frame_settings = NULL; /* Deallocated when encoder is destroyed with JxlEncoderDestroy() */

  JxlEncoderStatus
    jxl_status;

  JxlBasicInfo
    basic_info;

  struct MyJXLMemoryManager
    memory_manager;

  ImageCharacteristics
    characteristics;

  size_t
    size_row;

  unsigned char
    *in_buf = NULL,
    *out_buf = NULL;

  JxlPixelFormat
    pixel_format;

  JxlColorEncoding
    color_encoding = {};

  memset(&pixel_format,0,sizeof(pixel_format));

  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickSignature);
  assert(image != (Image *) NULL);
  assert(image->signature == MagickSignature);

  /*
    Ensure that image is in desired output space
  */
  if ((image_info->type != UndefinedType) &&
      (image_info->type != OptimizeType))
    (void) SetImageType(image,image_info->type);
  else if (!IsCMYKColorspace(image->colorspace) &&
           (!IsRGBColorspace(image->colorspace)))
    (void) TransformColorspace(image,RGBColorspace);

  /*
    Analyze image to be written.
  */
  if (!GetImageCharacteristics(image,&characteristics,
                               (OptimizeType == image_info->type),
                               &image->exception))
    {
      return MagickFail;
    }

  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                        "Image characteristics: cmyk=%c, gray=%c, mono=%c,"
                        " opaque=%c, palette=%c",
                        (characteristics.cmyk ? 'y' : 'n'),
                        (characteristics.grayscale ? 'y' : 'n'),
                        (characteristics.monochrome ? 'y' : 'n'),
                        (characteristics.opaque ? 'y' : 'n'),
                        (characteristics.palette ? 'y' : 'n'));

  /*
    Open output image file.
  */
  status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
  if (status == MagickFail)
    ThrowWriterException(FileOpenError,UnableToOpenFile,image);

  /* Init JXL-Decoder handles */
  MyJxlMemoryManagerInit(&memory_manager,image,&image->exception);
  jxl_encoder=JxlEncoderCreate(&memory_manager.super);
  if (jxl_encoder == (JxlEncoder *) NULL)
    ThrowWriterException(ResourceLimitError,MemoryAllocationFailed,image);

  /* Use the same number of threads as used for OpenMP */
  jxl_thread_runner=
    JxlThreadParallelRunnerCreate(NULL,
                                  (size_t) GetMagickResourceLimit(ThreadsResource));
  if (jxl_thread_runner == (void *) NULL)
    ThrowJXLWriterException(ResourceLimitError,MemoryAllocationFailed,image);
  if (JxlEncoderSetParallelRunner(jxl_encoder, JxlThreadParallelRunner, jxl_thread_runner)
      != JXL_ENC_SUCCESS)
    ThrowJXLWriterException(ResourceLimitError,MemoryAllocationFailed,image);

  /* Use one color channel for grayscale image */
  if (characteristics.grayscale)
    pixel_format.num_channels = 1;
  else
    {
      image->storage_class=DirectClass;
      pixel_format.num_channels = characteristics.opaque ? 3 : 4;
    }

  /* Support writing integer depths 8, 16, and 32 */
  /* FIXME: Provide an option to write JXL_TYPE_FLOAT16 or really any
     desired type here */
  if (image->depth <= 8)
    pixel_format.data_type = JXL_TYPE_UINT8;
  else if (image->depth <= 16)
    pixel_format.data_type = JXL_TYPE_UINT16; /* or JXL_TYPE_FLOAT16 JXL_TYPE_UINT16  */
  else if (image->depth <= 32)
    pixel_format.data_type = JXL_TYPE_FLOAT; /* or JXL_TYPE_UINT16 */
  else
    ThrowJXLWriterException(CoderError,ColorspaceModelIsNotSupported,image);

  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                        "Using JXL '%s' data type",
                        JxlDataTypeAsString(pixel_format.data_type));

  /* Initialize JxlBasicInfo struct to default values. */
  JxlEncoderInitBasicInfo(&basic_info);
  /* Width of the image in pixels, before applying orientation. */
  basic_info.xsize = image->columns;
  /* Height of the image in pixels, before applying orientation. */
  basic_info.ysize = image->rows;

  /* JXL_TYPE_FLOAT requires a nominal range of 0 to 1 */

  switch (pixel_format.data_type)
    {
    case JXL_TYPE_FLOAT:
      basic_info.bits_per_sample = 32;
      break;
    case JXL_TYPE_UINT8:
      basic_info.bits_per_sample = 8;
      break;
    case JXL_TYPE_UINT16:
      basic_info.bits_per_sample = 16;
      break;
    case JXL_TYPE_FLOAT16:
      basic_info.bits_per_sample = 16;
      break;
    default:
      ThrowJXLWriterException(CoderError,DataStorageTypeIsNotSupported,image);
    }

  pixel_format.endianness = JXL_NATIVE_ENDIAN;
  pixel_format.align = 0;

  if (pixel_format.data_type == JXL_TYPE_FLOAT)
    basic_info.exponent_bits_per_sample = 8;
  else if (pixel_format.data_type == JXL_TYPE_FLOAT16)
    basic_info.exponent_bits_per_sample = 5;

  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                        "Using %u bits per sample", basic_info.bits_per_sample);

  basic_info.num_color_channels = characteristics.grayscale ? 1 : 3;
  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                        "Using %u color channel%s", basic_info.num_color_channels,
                        basic_info.num_color_channels > 1 ? "s" : "");

  if (!characteristics.opaque)
    basic_info.alpha_bits=basic_info.bits_per_sample;

  /*
    Set the feature level of the JPEG XL codestream. Valid values are 5 and
    10, or -1 (to choose automatically). Using the minimum required level, or
    level 5 in most cases, is recommended for compatibility with all decoders.

    See <jxl/encode.h> for more details.
  */
  if ((jxl_status = JxlEncoderSetCodestreamLevel(jxl_encoder,-1)) != JXL_ENC_SUCCESS)
    {
    };
  if (image->logging)
    {
      (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                            "Basic Info:\n"
                            "    xsize=%u\n"
                            "    ysize=%u \n"
                            "    bits_per_sample=%u\n"
                            "    exponent_bits_per_sample=%u\n"
                            "    alpha_bits=%u\n"
                            "    num_color_channels=%u\n"
                            "    have_animation=%s",
                            basic_info.xsize, basic_info.ysize,
                            basic_info.bits_per_sample, basic_info.exponent_bits_per_sample,
                            basic_info.alpha_bits, basic_info.num_color_channels,
                            basic_info.have_animation == JXL_FALSE ? "False" : "True");
    }
  /* Set the global metadata of the image encoded by this encoder. */
  if ((jxl_status = JxlEncoderSetBasicInfo(jxl_encoder,&basic_info)) != JXL_ENC_SUCCESS)
    {
      /* TODO better error codes */
      if (jxl_status == JXL_ENC_ERROR)
        ThrowJXLWriterException(CoderError,NoDataReturned,image);
      else if (jxl_status == JXL_ENC_NOT_SUPPORTED)
        ThrowJXLWriterException(CoderError,UnsupportedBitsPerSample,image);
      else
        ThrowJXLWriterException(CoderFatalError,Default,image);
    }

  /* Set expected input colorspace */
  /* FIXME: For RGB we want to set JXL_COLOR_SPACE_RGB and for gray we want JXL_COLOR_SPACE_GRAY */
  basic_info.uses_original_profile = JXL_TRUE;
  JxlColorEncodingSetToSRGB(&color_encoding, pixel_format.num_channels < 3);
  if (JxlEncoderSetColorEncoding(jxl_encoder, &color_encoding) != JXL_ENC_SUCCESS)
    ThrowJXLWriterException(CoderFatalError,Default,image);

  frame_settings = JxlEncoderFrameSettingsCreate(jxl_encoder, NULL);
  if (image_info->quality == 100)
    {
      if (JxlEncoderSetFrameLossless(frame_settings,JXL_TRUE) != JXL_ENC_SUCCESS)
        ThrowJXLWriterException(CoderFatalError,Default,image);
    }
  else
    {
      /* same as cjxl.c: roughly similar to jpeg-quality for range 1-99 */
      if (image_info->quality >= 30)
        {
          if (JxlEncoderSetFrameDistance(frame_settings,
                                         0.1 + (100 - image_info->quality) * 0.09) != JXL_ENC_SUCCESS)
            ThrowJXLWriterException(CoderFatalError,Default,image);
        }
      else
        {
          if (JxlEncoderSetFrameDistance(frame_settings,
                                         6.4 + pow(2.5, (30 - image_info->quality) / 5.0f) / 6.25f) != JXL_ENC_SUCCESS)
            ThrowJXLWriterException(CoderFatalError,Default,image);
        }
    }
  /*
    Handle key/value for settings handled by JxlEncoderFrameSettingsSetOption()
  */
  {
    static const struct
    {
      const char key[14];
      JxlEncoderFrameSettingId fs_id;
    } int_frame_settings[]
        =
        {
         { "effort", JXL_ENC_FRAME_SETTING_EFFORT },
         { "decodingspeed", JXL_ENC_FRAME_SETTING_DECODING_SPEED },
        };

    unsigned int
      index;

    for (index = 0; index < ArraySize(int_frame_settings); index++)
      {
        const char *key = int_frame_settings[index].key;
        const char *value;
        if ((value=AccessDefinition(image_info,"jxl",key)))
          {
            int int_value =  MagickAtoI(value);
            if (JxlEncoderFrameSettingsSetOption(frame_settings, int_frame_settings[index].fs_id, int_value) != JXL_ENC_SUCCESS)
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                    "JXL does not support \"%s\" frame setting!", key);
            else
              (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                                    "Set \"%s\" to %d", key, int_value);
          }
      }
  }

  /* FIXME: Add metadata boxes */
  do
  {
    const unsigned char
      *exif,
      *xmp;

    size_t
      exif_length,
      xmp_length;

    exif=GetImageProfile(image,"EXIF",&exif_length);
    xmp=GetImageProfile(image,"XMP",&xmp_length);

    if (!((exif != (const unsigned char *) NULL) ||
          (xmp != (const unsigned char *) NULL)))
      break;

    (void) JxlEncoderUseBoxes(jxl_encoder);

    #define ExifNamespace  "Exif\0\0"
    if ((exif != (const unsigned char *) NULL) && (exif_length > 6) &&
        (exif[0] == 'E' && exif[1] == 'x' && exif[2] == 'i' &&
         exif[3] == 'f' && exif[4] == '\0' && exif[5] == '\0'))
      {
        /*
          The contents of this box must be prepended by a 4-byte tiff
          header offset, which may be 4 zero bytes in case the tiff
          header follows immediately.  We will make the header follow
          immediately.

          The EXIF profile blob is prefixed with "Exif\0\0" but the
          EXIF box needs to start with "\0\0\0\0" to indicate that the
          TIFF header follows immediately.
        */
        unsigned char *exif_b = MagickAllocateResourceLimitedMemory(unsigned char *,
                                                                    exif_length-2U);
        if (exif_b != (unsigned char *) NULL)
          {
            (void) memset(exif_b,0,4U);
            (void) memcpy(exif_b+4U,exif+6U,exif_length-6U);

            (void) JxlEncoderAddBox(jxl_encoder,"Exif",exif_b,exif_length-2U,0);
            MagickFreeResourceLimitedMemory(exif_b);
          }
      }

    if (xmp != (const unsigned char *) NULL)
      (void) JxlEncoderAddBox(jxl_encoder,"xml ",xmp,xmp_length,0);

    (void) JxlEncoderCloseBoxes(jxl_encoder);

  } while(0);

  /* get & fill pixel buffer */
  size_row=MagickArraySize(MagickArraySize(image->columns,pixel_format.num_channels),
                           (basic_info.bits_per_sample/8));
  (void) LogMagickEvent(CoderEvent,GetMagickModule(),
                        "size_row = %" MAGICK_SIZE_T_F "u", (MAGICK_SIZE_T) size_row);
  in_buf=MagickAllocateResourceLimitedArray(unsigned char *,image->rows,size_row);
  if (in_buf == (unsigned char *) NULL)
    ThrowJXLWriterException(ResourceLimitError,MemoryAllocationFailed,image);

  /*
    Export image pixels to allocated buffer.
  */
  {
    long
      y;

    const PixelPacket
      *q;

    unsigned char
      *p;

    unsigned int
      quantum_size;

    QuantumType
      quantum_type;

    QuantumSampleType
      sample_type;

    ExportPixelAreaOptions
      export_options;

    ExportPixelAreaInfo
      export_info;

    quantum_size = JxlDataTypeToQuantumSize(pixel_format.data_type);
    sample_type = JxlDataTypeToQuantumSampleType(pixel_format.data_type);

    if (pixel_format.num_channels == 1)
      {
        if (image->matte)
          quantum_type = GrayAlphaQuantum;
        else
          quantum_type = GrayQuantum;
      }
#if 0
    else if (cmyk)
      {
        if (image->matte)
          quantum_type = CMYKAQuantum;
        else
          quantum_type = CMYKQuantum;
      }
#endif
    else
      {
        if (image->matte)
          quantum_type = RGBAQuantum;
        else
          quantum_type = RGBQuantum;
      }

    ExportPixelAreaOptionsInit(&export_options);
    export_options.sample_type = sample_type;
    export_options.endian = NativeEndian;

    p = in_buf;
    for (y=0; y < (long) image->rows; y++)
      {
        q=AcquireImagePixels(image,0,y,image->columns,1,&image->exception);
        if (q == (const PixelPacket *) NULL)
          {
            status = MagickFail;
            break;
          }

        if ((status = ExportImagePixelArea(image,quantum_type,quantum_size,
                                           p,&export_options,&export_info))
            != MagickPass)
          break;

        p += export_info.bytes_exported;
      }
    if (status == MagickFail)
      ThrowJXLWriterException(ResourceLimitError,MemoryAllocationFailed,image);
  }

  /* real encode */
  if (JxlEncoderAddImageFrame(frame_settings,&pixel_format,in_buf,
                              image->rows * size_row) != JXL_ENC_SUCCESS)
    /* TODO Better Error-code? */
    ThrowJXLWriterException(CoderError,NoDataReturned,image);

  /* Close any input to the encoder. No further input of any kind may
     be given to the encoder, but further JxlEncoderProcessOutput
     calls should be done to create the final output. */
  JxlEncoderCloseInput(jxl_encoder);

  out_buf=MagickAllocateResourceLimitedArray(unsigned char *,MaxBufferExtent,sizeof(*out_buf));
  if (out_buf == (unsigned char *) NULL)
    ThrowJXLWriterException(ResourceLimitError,MemoryAllocationFailed,image);

  jxl_status=JXL_ENC_NEED_MORE_OUTPUT;
  while (jxl_status == JXL_ENC_NEED_MORE_OUTPUT)
    {
      size_t
        avail_out,
        write_out;

      unsigned char
        *next_out;

      avail_out=MaxBufferExtent;
      next_out=out_buf;
      /* fprintf(stderr,"Before: next_out=%p, avail_out=%zu\n", next_out, avail_out); */
      jxl_status=JxlEncoderProcessOutput(jxl_encoder,&next_out,&avail_out);
      write_out=next_out-out_buf;
      /* fprintf(stderr,"After: next_out=%p, avail_out=%zu, write_out=%zu\n", next_out, avail_out, write_out); */

      if (WriteBlob(image,write_out,out_buf) != write_out)
        ThrowJXLWriterException(BlobError,UnableToWriteBlob,image);
    }
  if (jxl_status != JXL_ENC_SUCCESS)
    /* TODO Better Error-code? */
    ThrowJXLWriterException(CoderError,NoDataReturned,image);

  CloseBlob(image);

  JXLWriteCleanup();
  return MagickPass;
}

#endif /* HasJXL */


/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   R e g i s t e r J X L I m a g e                                           %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Method RegisterJXLImage adds attributes for the JXL image format to
%  the list of supported formats.  The attributes include the image format
%  tag, a method to read and/or write the format and a brief
%  description of the format.
%
%  The format of the RegisterJXLImage method is:
%
%      RegisterJXLImage(void)
%
*/
ModuleExport void RegisterJXLImage(void)
{
#if defined(HasJXL)
  static const char
    description[] = "JXL Image Format";

  static char
    version[20];

  MagickInfo
    *entry;

  unsigned int
    jxl_major,
    jxl_minor,
    jxl_revision;

  int encoder_version=(JxlDecoderVersion());
  jxl_major=(encoder_version >> 16) & 0xff;
  jxl_minor=(encoder_version >> 8) & 0xff;
  jxl_revision=encoder_version & 0xff;
  *version='\0';
  (void) snprintf(version,sizeof(version),
                  "jxl v%u.%u.%u", jxl_major,
                  jxl_minor, jxl_revision);

  entry=SetMagickInfo("JXL");
  entry->decoder=(DecoderHandler) ReadJXLImage;
  entry->encoder=(EncoderHandler) WriteJXLImage;
  entry->description=description;
  entry->adjoin=False;
  entry->seekable_stream=MagickTrue;
  if (*version != '\0')
    entry->version=version;
  entry->module="JXL";
  entry->coder_class=PrimaryCoderClass;
  (void) RegisterMagickInfo(entry);
#endif /* HasJXL */
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   U n r e g i s t e r J X L I m a g e                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  Method UnregisterJXLImage removes format registrations made by the
%  JXL module from the list of supported formats.
%
%  The format of the UnregisterJXLImage method is:
%
%      UnregisterJXLImage(void)
%
*/
ModuleExport void UnregisterJXLImage(void)
{
#if defined(HasJXL)
  (void) UnregisterMagickInfo("JXL");
#endif /* HasJXL */
}