Debian Codegraph @

coders/uhdr.c

raw symbols SCIP
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 % %
4 % %
5 % %
6 % Read/Write UHDR Image Format %
7 % %
8 % Software Design %
9 % A S %
10 % Jan 2024 %
11 % %
12 % %
13 % Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization %
14 % dedicated to making software imaging solutions freely available. %
15 % %
16 % You may not use this file except in compliance with the License. You may %
17 % obtain a copy of the License at %
18 % %
19 % https://imagemagick.org/license/ %
20 % %
21 % Unless required by applicable law or agreed to in writing, software %
22 % distributed under the License is distributed on an "AS IS" BASIS, %
23 % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
24 % See the License for the specific language governing permissions and %
25 % limitations under the License. %
26 % %
27 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
28 %
29 %
30 */
31
32 /*
33 Include declarations.
34 */
35 #include "MagickCore/studio.h"
36 #include "MagickCore/blob.h"
37 #include "MagickCore/blob-private.h"
38 #include "MagickCore/exception.h"
39 #include "MagickCore/exception-private.h"
40 #include "MagickCore/image.h"
41 #include "MagickCore/image-private.h"
42 #include "MagickCore/list.h"
43 #include "MagickCore/module.h"
44 #include "MagickCore/option.h"
45 #include "MagickCore/profile.h"
46 #include "MagickCore/profile-private.h"
47 #include "MagickCore/resize.h"
48 #include "MagickCore/shear.h"
49 #include "MagickCore/string_.h"
50 #include "MagickCore/string-private.h"
51 #include "MagickCore/transform.h"
52 #if defined(MAGICKCORE_UHDR_DELEGATE)
53 #include "ultrahdr_api.h"
54 #include "uhdr.h"
55 #endif
56
57 /*
58 Forward declarations.
59 */
60 #if defined(MAGICKCORE_UHDR_DELEGATE)
61 static MagickBooleanType
62 WriteUHDRImage(const ImageInfo *,Image *,ExceptionInfo *);
63 #endif
64
65 /*
66 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
67 % %
68 % %
69 % %
70 % I s U H D R %
71 % %
72 % %
73 % %
74 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
75 %
76 % IsUHDR() returns MagickTrue if the input stream is a valid ultra hdr file,
77 % MagickFalse otherwise
78 %
79 % The format of the IsUHDR method is:
80 %
81 % MagickBooleanType IsUHDR(const unsigned char *magick,const size_t length)
82 %
83 % A description of each parameter follows:
84 %
85 % o image_info: the image info.
86 %
87 % o exception: return any errors or warnings in this structure.
88 %
89 */
90 static MagickBooleanType IsUHDR(const unsigned char *magick,
91 const size_t length)
92 {
93 #if defined(MAGICKCORE_UHDR_DELEGATE)
94 if (is_uhdr_image((void *) magick,(int) length))
95 return(MagickTrue);
96 #else
97 magick_unreferenced(magick);
98 magick_unreferenced(length);
99 #endif
100 return(MagickFalse);
101 }
102
103 #if defined(MAGICKCORE_UHDR_DELEGATE)
104 /*
105 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
106 % %
107 % %
108 % %
109 % R e a d U H D R I m a g e %
110 % %
111 % %
112 % %
113 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
114 %
115 % ReadUHDRImage retrieves an image via a file descriptor, decodes the image,
116 % and returns it. It allocates the memory necessary for the new Image
117 % structure and returns a pointer to the new image.
118 %
119 % The format of the ReadUHDRImage method is:
120 %
121 % Image *ReadUHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
122 %
123 % A description of each parameter follows:
124 %
125 % o image_info: the image info.
126 %
127 % o exception: return any errors or warnings in this structure.
128 %
129 */
130 static uhdr_color_transfer_t map_ct_to_uhdr_ct(const char *input_ct)
131 {
132 if (!strcmp(input_ct, "hlg"))
133 return UHDR_CT_HLG;
134 if (!strcmp(input_ct, "pq"))
135 return UHDR_CT_PQ;
136 if (!strcmp(input_ct, "linear"))
137 return UHDR_CT_LINEAR;
138 if (!strcmp(input_ct, "srgb"))
139 return UHDR_CT_SRGB;
140 else
141 return UHDR_CT_UNSPECIFIED;
142 }
143
144 static Image *ReadUHDRImage(const ImageInfo *image_info,
145 ExceptionInfo *exception)
146 {
147 #define SetHDRGMProperty(name,value) \
148 (void) FormatLocaleString(buffer,sizeof(buffer),"%f",(value)); \
149 (void) SetImageProperty(image,"hdrgm:" name,buffer,exception)
150 #define SetHDRGMPropertyInt(name,value) \
151 (void) FormatLocaleString(buffer,sizeof(buffer),"%d",(value)); \
152 (void) SetImageProperty(image,"hdrgm:" name,buffer,exception)
153 #define SetHDRGMPropertySize(name,value) \
154 (void) FormatLocaleString(buffer,sizeof(buffer),"%.20g",(double) (value)); \
155 (void) SetImageProperty(image,"hdrgm:" name,buffer,exception)
156 #define SetHDRGMProperty3(name,value,value1,value2) \
157 (void) FormatLocaleString(buffer,sizeof(buffer),"%f,%f,%f", \
158 (value),(value1),(value2)); \
159 (void) SetImageProperty(image,"hdrgm:" name,buffer,exception)
160
161 Image
162 *image;
163
164 MagickBooleanType
165 status;
166
167 image = AcquireImage(image_info, exception);
168 status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
169 if (status == MagickFalse)
170 return DestroyImageList(image);
171
172 uhdr_compressed_image_t
173 img;
174
175 img.data = GetBlobStreamData(image);
176 img.data_sz = GetBlobSize(image);
177 img.capacity = GetBlobSize(image);
178 img.cg = UHDR_CG_UNSPECIFIED;
179 img.ct = UHDR_CT_UNSPECIFIED;
180 img.range = UHDR_CR_UNSPECIFIED;
181
182 uhdr_codec_private_t
183 *handle = uhdr_create_decoder();
184
185 const char *option = GetImageOption(image_info, "uhdr:output-color-transfer");
186 uhdr_color_transfer_t decoded_img_ct =
187 (option != (const char *)NULL) ? map_ct_to_uhdr_ct(option) : UHDR_CT_SRGB;
188
189 const char *profile_skip = GetImageOption(image_info, "profile:skip");
190
191 MagickBooleanType
192 skip_app_profiles = IsOptionMember("APP",profile_skip),
193 skip_exif_profile = IsOptionMember("EXIF",profile_skip),
194 skip_gainmap_profile = IsOptionMember("HDRGM",profile_skip),
195 skip_icc_profile = IsOptionMember("ICC",profile_skip);
196
197 if (skip_app_profiles != MagickFalse)
198 {
199 skip_exif_profile=MagickTrue;
200 skip_gainmap_profile=MagickTrue;
201 }
202
203 uhdr_img_fmt_t
204 decoded_img_fmt = UHDR_CT_SRGB;
205
206 if (decoded_img_ct == UHDR_CT_LINEAR)
207 decoded_img_fmt = UHDR_IMG_FMT_64bppRGBAHalfFloat;
208 else if (decoded_img_ct == UHDR_CT_HLG || decoded_img_ct == UHDR_CT_PQ)
209 decoded_img_fmt = UHDR_IMG_FMT_32bppRGBA1010102;
210 else if (decoded_img_ct == UHDR_CT_SRGB)
211 decoded_img_fmt = UHDR_IMG_FMT_32bppRGBA8888;
212 else
213 decoded_img_fmt = UHDR_IMG_FMT_UNSPECIFIED;
214
215 #define CHECK_IF_ERR(x) \
216 { \
217 uhdr_error_info_t retval = (x); \
218 if (retval.error_code != UHDR_CODEC_OK) \
219 { \
220 (void)ThrowMagickException(exception, GetMagickModule(), CoderError, \
221 retval.has_detail ? retval.detail : "unknown error", "`%s'", \
222 image->filename); \
223 uhdr_release_decoder(handle); \
224 CloseBlob(image); \
225 return DestroyImageList(image); \
226 } \
227 }
228
229 CHECK_IF_ERR(uhdr_dec_set_image(handle, &img))
230 CHECK_IF_ERR(uhdr_dec_set_out_color_transfer(handle, decoded_img_ct))
231 CHECK_IF_ERR(uhdr_dec_set_out_img_format(handle, decoded_img_fmt))
232 CHECK_IF_ERR(uhdr_dec_probe(handle))
233
234 image->columns = uhdr_dec_get_image_width(handle);
235 image->rows = uhdr_dec_get_image_height(handle);
236
237 if (image_info->ping != MagickFalse)
238 {
239 uhdr_release_decoder(handle);
240 (void) CloseBlob(image);
241 return(GetFirstImageInList(image));
242 }
243
244 CHECK_IF_ERR(uhdr_decode(handle))
245
246 uhdr_raw_image_t
247 *dst = uhdr_get_decoded_image(handle);
248
249 /*
250 Preserve compressed gain‑map + metadata for transcoding.
251 */
252 {
253 uhdr_mem_block_t
254 *gainmap_image = uhdr_dec_get_gainmap_image(handle);
255
256 uhdr_gainmap_metadata_t
257 *gainmap_info = uhdr_dec_get_gainmap_metadata(handle);
258
259 if ((skip_gainmap_profile == MagickFalse) &&
260 (gainmap_image != (uhdr_mem_block_t *) NULL) &&
261 (gainmap_info != (uhdr_gainmap_metadata_t *) NULL))
262 {
263 char
264 buffer[MagickPathExtent];
265
266 /*
267 Set gainmap as a binary profile.
268 */
269 StringInfo *gainmap_profile = BlobToProfileStringInfo("hdrgm",
270 gainmap_image->data,gainmap_image->data_sz,exception);
271 (void) SetImageProfilePrivate(image,gainmap_profile,exception);
272
273 /*
274 Set metadata as properties.
275 */
276 SetHDRGMProperty3("GainMapMax",
277 gainmap_info->max_content_boost[0],gainmap_info->max_content_boost[1],
278 gainmap_info->max_content_boost[2]);
279 SetHDRGMProperty3("GainMapMin",
280 gainmap_info->min_content_boost[0],gainmap_info->min_content_boost[1],
281 gainmap_info->min_content_boost[2]);
282 SetHDRGMProperty3("Gamma",gainmap_info->gamma[0],
283 gainmap_info->gamma[1],gainmap_info->gamma[2]);
284 SetHDRGMProperty3("OffsetSDR",gainmap_info->offset_sdr[0],
285 gainmap_info->offset_sdr[1],gainmap_info->offset_sdr[2]);
286 SetHDRGMProperty3("OffsetHDR",gainmap_info->offset_hdr[0],
287 gainmap_info->offset_hdr[1],gainmap_info->offset_hdr[2]);
288 SetHDRGMProperty("HDRCapacityMin",gainmap_info->hdr_capacity_min);
289 SetHDRGMProperty("HDRCapacityMax",gainmap_info->hdr_capacity_max);
290 SetHDRGMPropertyInt("UseBaseColorGrade",gainmap_info->use_base_cg);
291 SetHDRGMPropertySize("BaseWidth",image->columns);
292 SetHDRGMPropertySize("BaseHeight",image->rows);
293 }
294 }
295
296 status=SetImageExtent(image,image->columns,image->rows,exception);
297 if (status == MagickFalse)
298 {
299 uhdr_release_decoder(handle);
300 CloseBlob(image);
301 return(DestroyImageList(image));
302 }
303
304 #undef CHECK_IF_ERR
305
306 uhdr_mem_block_t *exif = uhdr_dec_get_exif(handle);
307 if ((skip_exif_profile == MagickFalse) && (exif != NULL))
308 {
309 StringInfo *exif_data = BlobToProfileStringInfo("exif",exif->data,
310 exif->data_sz,exception);
311 (void) SetImageProfilePrivate(image,exif_data,exception);
312 }
313
314 uhdr_mem_block_t *icc = uhdr_dec_get_icc(handle);
315 if ((skip_icc_profile == MagickFalse) && (icc != NULL) &&
316 (icc->data != NULL) && (icc->data_sz != 0))
317 {
318 const unsigned char
319 *icc_data_start = (const unsigned char *) icc->data;
320
321 size_t
322 icc_data_size = icc->data_sz;
323
324 /*
325 libultrahdr returns JPEG APP2 ICC chunk data. ImageMagick stores the
326 raw ICC payload and adds the APP2 wrapper itself when writing JPEG.
327 */
328 if ((icc_data_size > 14) &&
329 (memcmp(icc_data_start,"ICC_PROFILE\0",12) == 0))
330 {
331 icc_data_start+=14;
332 icc_data_size-=14;
333 }
334 StringInfo *icc_data = BlobToProfileStringInfo("icc",icc_data_start,
335 icc_data_size,exception);
336 (void) SetImageProfilePrivate(image,icc_data,exception);
337 }
338
339 if (decoded_img_ct == UHDR_CT_LINEAR)
340 {
341 SetImageColorspace(image,RGBColorspace,exception);
342 image->gamma=1.0;
343 }
344 else if ((decoded_img_ct == UHDR_CT_SRGB) && (dst->cg == UHDR_CG_DISPLAY_P3))
345 SetImageColorspace(image,DisplayP3Colorspace,exception);
346 else if (decoded_img_ct == UHDR_CT_SRGB)
347 SetImageColorspace(image,sRGBColorspace,exception);
348 else
349 SetImageColorspace(image,RGBColorspace,exception);
350
351 image->compression = JPEGCompression;
352 if (decoded_img_fmt == UHDR_IMG_FMT_32bppRGBA8888)
353 image->depth = 8;
354 else if (decoded_img_fmt == UHDR_IMG_FMT_32bppRGBA1010102)
355 image->depth = 10;
356 else if (decoded_img_fmt == UHDR_IMG_FMT_64bppRGBAHalfFloat)
357 image->depth = 16;
358 switch (dst->cg)
359 {
360 case UHDR_CG_BT_709:
361 image->chromaticity.red_primary.x = 0.64;
362 image->chromaticity.red_primary.y = 0.33;
363 image->chromaticity.green_primary.x = 0.30;
364 image->chromaticity.green_primary.y = 0.60;
365 image->chromaticity.blue_primary.x = 0.15;
366 image->chromaticity.blue_primary.y = 0.06;
367 image->chromaticity.white_point.x = 0.3127;
368 image->chromaticity.white_point.y = 0.3290;
369 break;
370
371 case UHDR_CG_DISPLAY_P3:
372 image->chromaticity.red_primary.x = 0.680;
373 image->chromaticity.red_primary.y = 0.320;
374 image->chromaticity.green_primary.x = 0.265;
375 image->chromaticity.green_primary.y = 0.690;
376 image->chromaticity.blue_primary.x = 0.150;
377 image->chromaticity.blue_primary.y = 0.060;
378 image->chromaticity.white_point.x = 0.3127;
379 image->chromaticity.white_point.y = 0.3290;
380 break;
381
382 case UHDR_CG_BT_2100:
383 image->chromaticity.red_primary.x = 0.708;
384 image->chromaticity.red_primary.y = 0.292;
385 image->chromaticity.green_primary.x = 0.170;
386 image->chromaticity.green_primary.y = 0.797;
387 image->chromaticity.blue_primary.x = 0.131;
388 image->chromaticity.blue_primary.y = 0.046;
389 image->chromaticity.white_point.x = 0.3127;
390 image->chromaticity.white_point.y = 0.3290;
391 break;
392
393 case UHDR_CG_UNSPECIFIED:
394 break;
395 }
396
397 for (ssize_t y = 0; y < (ssize_t) image->rows; y++)
398 {
399 Quantum
400 *q;
401
402 q = QueueAuthenticPixels(image, 0, y, image->columns, 1, exception);
403 if (q == (Quantum *) NULL)
404 {
405 status = MagickFalse;
406 break;
407 }
408 if (decoded_img_fmt == UHDR_IMG_FMT_64bppRGBAHalfFloat)
409 {
410 uint16_t *row =
411 (uint16_t *)dst->planes[UHDR_PLANE_PACKED] + (y * dst->stride[UHDR_PLANE_PACKED] * 4);
412 for (ssize_t x = 0; x < (ssize_t)image->columns; x++)
413 {
414 SetPixelRed(image, ClampToQuantum(QuantumRange * (HalfToSinglePrecision(*row++))), q);
415 SetPixelGreen(image, ClampToQuantum(QuantumRange * (HalfToSinglePrecision(*row++))), q);
416 SetPixelBlue(image, ClampToQuantum(QuantumRange * (HalfToSinglePrecision(*row++))), q);
417 row++;
418 q += GetPixelChannels(image);
419 }
420 }
421 else if (decoded_img_fmt == UHDR_IMG_FMT_32bppRGBA1010102)
422 {
423 uint32_t *row =
424 (uint32_t *)dst->planes[UHDR_PLANE_PACKED] + (y * dst->stride[UHDR_PLANE_PACKED]);
425 for (ssize_t x = 0; x < (ssize_t)image->columns; x++)
426 {
427 SetPixelRed(image, ScaleShortToQuantum((unsigned short)((*(row + x) & 0x000003FF) << 6)),
428 q);
429 SetPixelGreen(image, ScaleShortToQuantum((unsigned short)((*(row + x) & 0x000FFC00) >> 4)),
430 q);
431 SetPixelBlue(image, ScaleShortToQuantum((unsigned short)((*(row + x) & 0x3FF00000) >> 14)),
432 q);
433 q += GetPixelChannels(image);
434 }
435 }
436 else if (decoded_img_fmt == UHDR_IMG_FMT_32bppRGBA8888) {
437 uint8_t *row =
438 (uint8_t *)dst->planes[UHDR_PLANE_PACKED] + (y * dst->stride[UHDR_PLANE_PACKED] * 4);
439 for (ssize_t x = 0; x < (ssize_t)image->columns; x++)
440 {
441 SetPixelRed(image, ScaleCharToQuantum((unsigned char)(*row++)), q);
442 SetPixelGreen(image, ScaleCharToQuantum((unsigned char)(*row++)), q);
443 SetPixelBlue(image, ScaleCharToQuantum((unsigned char)(*row++)), q);
444 row++;
445 q += GetPixelChannels(image);
446 }
447 }
448
449 if (SyncAuthenticPixels(image, exception) == MagickFalse)
450 {
451 status = MagickFalse;
452 break;
453 }
454 }
455 uhdr_release_decoder(handle);
456 CloseBlob(image);
457 if (status == MagickFalse)
458 return (DestroyImageList(image));
459 return (GetFirstImageInList(image));
460 }
461 #endif
462
463 /*
464 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
465 % %
466 % %
467 % %
468 % R e g i s t e r U H D R I m a g e %
469 % %
470 % %
471 % %
472 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
473 %
474 % RegisterUHDRImage() adds attributes for the Uhdr image format to the list
475 % of supported formats. The attributes include the image format tag, a
476 % method to read and/or write the format, whether the format supports the
477 % saving of more than one frame to the same file or blob, whether the format
478 % supports native in-memory I/O, and a brief description of the format.
479 %
480 % The format of the RegisterUHDRImage method is:
481 %
482 % size_t RegisterUHDRImage(void)
483 %
484 */
485 ModuleExport size_t RegisterUHDRImage(void)
486 {
487 char
488 version[MagickPathExtent];
489
490 MagickInfo
491 *entry;
492
493 *version='\0';
494 entry=AcquireMagickInfo("UHDr","UHDR","Ultra HDR Image Format");
495 #if defined(MAGICKCORE_UHDR_DELEGATE)
496 entry->decoder=(DecodeImageHandler *) ReadUHDRImage;
497 entry->encoder=(EncodeImageHandler *) WriteUHDRImage;
498 #endif
499 entry->flags|=CoderDecoderSeekableStreamFlag;
500 entry->magick=(IsImageFormatHandler *) IsUHDR;
501 if (*version != '\0')
502 entry->version=ConstantString(version);
503 (void) RegisterMagickInfo(entry);
504 return(MagickImageCoderSignature);
505 }
506
507 /*
508 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
509 % %
510 % %
511 % %
512 % U n r e g i s t e r U H D R I m a g e %
513 % %
514 % %
515 % %
516 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
517 %
518 % UnregisterUHDRImage() removes format registrations made by the UHDR module
519 % from the list of supported formats.
520 %
521 % The format of the UnregisterUHDRImage method is:
522 %
523 % UnregisterUHDRImage(void)
524 %
525 */
526 ModuleExport void UnregisterUHDRImage(void)
527 {
528 (void) UnregisterMagickInfo("UHDr");
529 }
530
531 #if defined(MAGICKCORE_UHDR_DELEGATE)
532 /*
533 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
534 % %
535 % %
536 % %
537 % W r i t e U H D R I m a g e %
538 % %
539 % %
540 % %
541 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
542 %
543 % WriteUHDRImage() writes an input HDR intent and SDR intent of an image in
544 % UltraHDR format.
545 %
546 % The format of the WriteUHDRImage method is:
547 %
548 % MagickBooleanType WriteUHDRImage(const ImageInfo *image_info,
549 % Image *image,ExceptionInfo *exception)
550 %
551 % A description of each parameter follows.
552 %
553 % o image_info: the image info.
554 %
555 % o image: The image.
556 %
557 % o exception: return any errors or warnings in this structure.
558 %
559 */
560
561 static MagickBooleanType IsFloatEqual(float fa, float fb)
562 {
563 float diff = fa - fb;
564
565 return (diff < 0.0001 && diff > -0.0001) ? MagickTrue : MagickFalse;
566 }
567
568 static uhdr_color_gamut_t getImageColorGamut(ChromaticityInfo *info)
569 {
570 if (!(IsFloatEqual(info->white_point.x, 0.3127f) &&
571 IsFloatEqual(info->white_point.y, 0.3290f)))
572 return UHDR_CG_UNSPECIFIED;
573
574 if (IsFloatEqual(info->blue_primary.x, 0.150f) &&
575 IsFloatEqual(info->blue_primary.y, 0.060f))
576 {
577 if (IsFloatEqual(info->red_primary.x, 0.64f) &&
578 IsFloatEqual(info->red_primary.y, 0.33f) &&
579 IsFloatEqual(info->green_primary.x, 0.30f) &&
580 IsFloatEqual(info->green_primary.y, 0.60f))
581 {
582 return UHDR_CG_BT_709;
583 }
584 if (IsFloatEqual(info->red_primary.x, 0.680f) &&
585 IsFloatEqual(info->red_primary.y, 0.320f) &&
586 IsFloatEqual(info->green_primary.x, 0.265f) &&
587 IsFloatEqual(info->green_primary.y, 0.690f))
588 {
589 return UHDR_CG_DISPLAY_P3;
590 }
591 }
592 else if (IsFloatEqual(info->blue_primary.x, 0.131f) &&
593 IsFloatEqual(info->blue_primary.y, 0.046f) &&
594 IsFloatEqual(info->red_primary.x, 0.708f) &&
595 IsFloatEqual(info->red_primary.y, 0.292f) &&
596 IsFloatEqual(info->green_primary.x, 0.170f) &&
597 IsFloatEqual(info->green_primary.y, 0.797f))
598 {
599 return UHDR_CG_BT_2100;
600 }
601
602 return UHDR_CG_UNSPECIFIED;
603 }
604
605 static uhdr_color_gamut_t map_cg_to_uhdr_cg(const char *input_cg)
606 {
607 if (!strcmp(input_cg, "display_p3"))
608 return UHDR_CG_DISPLAY_P3;
609 if (!strcmp(input_cg, "bt709"))
610 return UHDR_CG_BT_709;
611 if (!strcmp(input_cg, "bt2100"))
612 return UHDR_CG_BT_2100;
613 else
614 return UHDR_CG_UNSPECIFIED;
615 }
616
617 static uhdr_mem_block_t GetExifProfile(Image *image, ExceptionInfo *exception)
618 {
619 const char
620 *name;
621
622 const StringInfo
623 *profile;
624
625 uhdr_mem_block_t
626 uhdr_profile = { 0 };
627
628 ResetImageProfileIterator(image);
629 for (name = GetNextImageProfile(image); name != (const char *)NULL;)
630 {
631 profile = GetImageProfile(image, name);
632 if (LocaleCompare(name, "EXIF") == 0)
633 {
634 uhdr_profile.data_sz = (unsigned int)GetStringInfoLength(profile);
635 uhdr_profile.capacity = uhdr_profile.data_sz;
636 if (uhdr_profile.data_sz > 65533L)
637 (void)ThrowMagickException(exception, GetMagickModule(), CoderWarning,
638 "ExifProfileSizeExceedsLimit", "`%s'", image->filename);
639
640 uhdr_profile.data = GetStringInfoDatum(profile);
641 return uhdr_profile;
642 }
643 if (image->debug != MagickFalse)
644 (void)LogMagickEvent(CoderEvent, GetMagickModule(), "%s profile: %.20g bytes", name,
645 (double)GetStringInfoLength(profile));
646 name = GetNextImageProfile(image);
647 }
648 return uhdr_profile;
649 }
650
651 static void fillRawImageDescriptor(uhdr_raw_image_t *imgDescriptor, const ImageInfo *image_info,
652 Image *image, uhdr_img_fmt_t fmt, uhdr_color_transfer_t ct)
653 {
654 const char
655 *option;
656
657 imgDescriptor->fmt = fmt;
658
659 if (image->depth >= 10)
660 {
661 option = GetImageOption(image_info, "uhdr:hdr-color-gamut");
662 imgDescriptor->cg = (option != (const char *)NULL) ? map_cg_to_uhdr_cg(option)
663 : getImageColorGamut(&image->chromaticity);
664 }
665 else if (image->depth == 8)
666 {
667 option = GetImageOption(image_info, "uhdr:sdr-color-gamut");
668 imgDescriptor->cg = (option != (const char *)NULL) ? map_cg_to_uhdr_cg(option)
669 : getImageColorGamut(&image->chromaticity);
670 }
671
672 imgDescriptor->range = imgDescriptor->fmt == UHDR_IMG_FMT_24bppYCbCrP010 ? UHDR_CR_LIMITED_RANGE
673 : UHDR_CR_FULL_RANGE;
674 imgDescriptor->ct = ct;
675 imgDescriptor->w = image->columns;
676 imgDescriptor->h = image->rows;
677 }
678
679 static size_t GetHDRGMPropertySize(const Image *image,const char *name,
680 ExceptionInfo *exception)
681 {
682 char
683 property[MagickPathExtent];
684
685 const char
686 *value;
687
688 (void) FormatLocaleString(property,MagickPathExtent,"hdrgm:%s",name);
689 value=GetImageProperty(image,property,exception);
690 if (value == (const char *) NULL)
691 return(0);
692 return((size_t) StringToUnsignedLong(value));
693 }
694
695 static size_t ScaleGainMapExtent(const size_t extent,
696 const size_t scaled_extent,const size_t base_extent)
697 {
698 double
699 scale;
700
701 if ((extent == 0) || (scaled_extent == 0) || (base_extent == 0))
702 return(0);
703 scale=((double) extent*(double) scaled_extent)/(double) base_extent;
704 if (scale < 1.0)
705 return(1);
706 if (scale > (double) MAGICK_SSIZE_MAX)
707 return(0);
708 return(CastDoubleToSizeT(scale+0.5));
709 }
710
711 static ssize_t ScaleGainMapCoordinate(const double coordinate,
712 const size_t extent,const size_t base_extent)
713 {
714 double
715 scale;
716
717 if ((extent == 0) || (base_extent == 0))
718 return(0);
719 scale=((double) extent*coordinate)/(double) base_extent;
720 if (scale < 0.0)
721 return(0);
722 if (scale > (double) MAGICK_SSIZE_MAX)
723 return(MAGICK_SSIZE_MAX);
724 return(CastDoubleToSsizeT(floor(scale+0.5)));
725 }
726
727 static MagickBooleanType IsGainMapBaseGeometry(const size_t base_columns,
728 const size_t base_rows,const double columns,const double rows)
729 {
730 if ((columns <= 0.0) || (rows <= 0.0))
731 return(MagickFalse);
732 if ((base_columns != CastDoubleToSizeT(columns)) ||
733 (base_rows != CastDoubleToSizeT(rows)))
734 return(MagickFalse);
735 return(MagickTrue);
736 }
737
738 static MagickBooleanType ReplaceGainMapImage(Image **gainmap_image,
739 Image *transform_image)
740 {
741 if (transform_image == (Image *) NULL)
742 return(MagickFalse);
743 *gainmap_image=DestroyImageList(*gainmap_image);
744 *gainmap_image=transform_image;
745 return(MagickTrue);
746 }
747
748 static MagickBooleanType CropGainMapImage(Image **gainmap_image,
749 const size_t base_columns,const size_t base_rows,const double columns,
750 const double rows,const double x,const double y,ExceptionInfo *exception)
751 {
752 Image
753 *crop_image;
754
755 RectangleInfo
756 geometry;
757
758 ssize_t
759 x0,
760 x1,
761 y0,
762 y1;
763
764 if ((base_columns == 0) || (base_rows == 0) || (columns <= 0.0) ||
765 (rows <= 0.0))
766 return(MagickFalse);
767 if ((x < 0.0) || (y < 0.0) || ((x+columns) > (double) base_columns) ||
768 ((y+rows) > (double) base_rows))
769 return(MagickFalse);
770 x0=ScaleGainMapCoordinate(x,(*gainmap_image)->columns,base_columns);
771 y0=ScaleGainMapCoordinate(y,(*gainmap_image)->rows,base_rows);
772 x1=ScaleGainMapCoordinate(x+columns,(*gainmap_image)->columns,base_columns);
773 y1=ScaleGainMapCoordinate(y+rows,(*gainmap_image)->rows,base_rows);
774 if (x0 >= (ssize_t) (*gainmap_image)->columns)
775 x0=(ssize_t) (*gainmap_image)->columns-1;
776 if (y0 >= (ssize_t) (*gainmap_image)->rows)
777 y0=(ssize_t) (*gainmap_image)->rows-1;
778 if (x1 > (ssize_t) (*gainmap_image)->columns)
779 x1=(ssize_t) (*gainmap_image)->columns;
780 if (y1 > (ssize_t) (*gainmap_image)->rows)
781 y1=(ssize_t) (*gainmap_image)->rows;
782 if (x1 <= x0)
783 x1=x0+1;
784 if (y1 <= y0)
785 y1=y0+1;
786 geometry.x=x0;
787 geometry.y=y0;
788 geometry.width=(size_t) (x1-x0);
789 geometry.height=(size_t) (y1-y0);
790 crop_image=CropImage(*gainmap_image,&geometry,exception);
791 return(ReplaceGainMapImage(gainmap_image,crop_image));
792 }
793
794 static MagickBooleanType ResizeGainMapImage(Image **gainmap_image,
795 size_t *base_columns,size_t *base_rows,const size_t columns,
796 const size_t rows,const Image *image,ExceptionInfo *exception)
797 {
798 Image
799 *resize_image;
800
801 size_t
802 target_columns,
803 target_rows;
804
805 target_columns=ScaleGainMapExtent((*gainmap_image)->columns,columns,
806 *base_columns);
807 target_rows=ScaleGainMapExtent((*gainmap_image)->rows,rows,*base_rows);
808 if ((target_columns == 0) || (target_rows == 0))
809 return(MagickFalse);
810 if ((target_columns != (*gainmap_image)->columns) ||
811 (target_rows != (*gainmap_image)->rows))
812 {
813 resize_image=ResizeImage(*gainmap_image,target_columns,target_rows,
814 image->filter,exception);
815 if (ReplaceGainMapImage(gainmap_image,resize_image) == MagickFalse)
816 return(MagickFalse);
817 }
818 *base_columns=columns;
819 *base_rows=rows;
820 return(MagickTrue);
821 }
822
823 static MagickBooleanType ApplyGainMapTransform(Image **gainmap_image,
824 size_t *base_columns,size_t *base_rows,const Image *image,
825 const char *transform,ExceptionInfo *exception)
826 {
827 double
828 columns,
829 rows,
830 source_columns,
831 source_rows,
832 x,
833 y;
834
835 Image
836 *transform_image;
837
838 size_t
839 rotations;
840
841 if (LocaleNCompare(transform,"crop ",5) == 0)
842 {
843 if (sscanf(transform+5,"%lfx%lf %lfx%lf%lf%lf",&source_columns,
844 &source_rows,&columns,&rows,&x,&y) != 6)
845 return(MagickFalse);
846 if (IsGainMapBaseGeometry(*base_columns,*base_rows,source_columns,
847 source_rows) == MagickFalse)
848 return(MagickFalse);
849 if (CropGainMapImage(gainmap_image,*base_columns,*base_rows,columns,
850 rows,x,y,exception) == MagickFalse)
851 return(MagickFalse);
852 *base_columns=CastDoubleToSizeT(columns);
853 *base_rows=CastDoubleToSizeT(rows);
854 return(MagickTrue);
855 }
856 if (LocaleNCompare(transform,"resize ",7) == 0)
857 {
858 if (sscanf(transform+7,"%lfx%lf %lfx%lf",&source_columns,
859 &source_rows,&columns,&rows) != 4)
860 return(MagickFalse);
861 if (IsGainMapBaseGeometry(*base_columns,*base_rows,source_columns,
862 source_rows) == MagickFalse)
863 return(MagickFalse);
864 return(ResizeGainMapImage(gainmap_image,base_columns,base_rows,
865 CastDoubleToSizeT(columns),CastDoubleToSizeT(rows),image,exception));
866 }
867 if (LocaleNCompare(transform,"flip ",5) == 0)
868 {
869 if (sscanf(transform+5,"%lfx%lf",&source_columns,&source_rows) != 2)
870 return(MagickFalse);
871 if (IsGainMapBaseGeometry(*base_columns,*base_rows,source_columns,
872 source_rows) == MagickFalse)
873 return(MagickFalse);
874 transform_image=FlipImage(*gainmap_image,exception);
875 return(ReplaceGainMapImage(gainmap_image,transform_image));
876 }
877 if (LocaleNCompare(transform,"flop ",5) == 0)
878 {
879 if (sscanf(transform+5,"%lfx%lf",&source_columns,&source_rows) != 2)
880 return(MagickFalse);
881 if (IsGainMapBaseGeometry(*base_columns,*base_rows,source_columns,
882 source_rows) == MagickFalse)
883 return(MagickFalse);
884 transform_image=FlopImage(*gainmap_image,exception);
885 return(ReplaceGainMapImage(gainmap_image,transform_image));
886 }
887 if (LocaleNCompare(transform,"rotate ",7) == 0)
888 {
889 size_t
890 next_columns,
891 next_rows;
892
893 if (sscanf(transform+7,"%lfx%lf %lf",&source_columns,&source_rows,
894 &x) != 3)
895 return(MagickFalse);
896 if (IsGainMapBaseGeometry(*base_columns,*base_rows,source_columns,
897 source_rows) == MagickFalse)
898 return(MagickFalse);
899 rotations=CastDoubleToSizeT(x) % 4;
900 if (rotations == 0)
901 return(MagickTrue);
902 transform_image=IntegralRotateImage(*gainmap_image,rotations,exception);
903 if (ReplaceGainMapImage(gainmap_image,transform_image) == MagickFalse)
904 return(MagickFalse);
905 if ((rotations == 1) || (rotations == 3))
906 {
907 next_columns=(*base_rows);
908 next_rows=(*base_columns);
909 *base_columns=next_columns;
910 *base_rows=next_rows;
911 }
912 return(MagickTrue);
913 }
914 if (LocaleNCompare(transform,"transpose ",10) == 0)
915 {
916 size_t
917 next_columns;
918
919 if (sscanf(transform+10,"%lfx%lf",&source_columns,&source_rows) != 2)
920 return(MagickFalse);
921 if (IsGainMapBaseGeometry(*base_columns,*base_rows,source_columns,
922 source_rows) == MagickFalse)
923 return(MagickFalse);
924 transform_image=TransposeImage(*gainmap_image,exception);
925 if (ReplaceGainMapImage(gainmap_image,transform_image) == MagickFalse)
926 return(MagickFalse);
927 next_columns=(*base_rows);
928 *base_rows=(*base_columns);
929 *base_columns=next_columns;
930 return(MagickTrue);
931 }
932 if (LocaleNCompare(transform,"transverse ",11) == 0)
933 {
934 size_t
935 next_columns;
936
937 if (sscanf(transform+11,"%lfx%lf",&source_columns,&source_rows) != 2)
938 return(MagickFalse);
939 if (IsGainMapBaseGeometry(*base_columns,*base_rows,source_columns,
940 source_rows) == MagickFalse)
941 return(MagickFalse);
942 transform_image=TransverseImage(*gainmap_image,exception);
943 if (ReplaceGainMapImage(gainmap_image,transform_image) == MagickFalse)
944 return(MagickFalse);
945 next_columns=(*base_rows);
946 *base_rows=(*base_columns);
947 *base_columns=next_columns;
948 return(MagickTrue);
949 }
950 return(MagickFalse);
951 }
952
953 static StringInfo *EncodeBaseImageProfile(const ImageInfo *image_info,
954 Image *image,ExceptionInfo *exception)
955 {
956 Image
957 *base_image;
958
959 ImageInfo
960 *base_info;
961
962 size_t
963 length;
964
965 StringInfo
966 *profile,
967 *removed_profile;
968
969 void
970 *blob;
971
972 base_image=CloneImage(image,0,0,MagickTrue,exception);
973 if (base_image == (Image *) NULL)
974 return((StringInfo *) NULL);
975 removed_profile=RemoveImageProfile(base_image,"hdrgm");
976 if (removed_profile != (StringInfo *) NULL)
977 removed_profile=DestroyStringInfo(removed_profile);
978 base_info=CloneImageInfo(image_info);
979 (void) CopyMagickString(base_info->filename,"JPEG:uhdr-base.jpg",
980 MagickPathExtent);
981 (void) CopyMagickString(base_info->magick,"JPEG",MagickPathExtent);
982 if (image->quality > 0)
983 base_info->quality=image->quality;
984 (void) CopyMagickString(base_image->magick,"JPEG",MagickPathExtent);
985 blob=ImageToBlob(base_info,base_image,&length,exception);
986 base_image=DestroyImage(base_image);
987 base_info=DestroyImageInfo(base_info);
988 if (blob == (void *) NULL)
989 {
990 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
991 "UnableToEncodeBaseImage","`%s'",image->filename);
992 return((StringInfo *) NULL);
993 }
994 profile=BlobToProfileStringInfo("uhdr-base",blob,length,exception);
995 blob=RelinquishMagickMemory(blob);
996 return(profile);
997 }
998
999 static StringInfo *TransformGainMapProfile(const ImageInfo *image_info,
1000 const Image *image,const StringInfo *gainmap_profile,
1001 MagickBooleanType *transform_status,ExceptionInfo *exception)
1002 {
1003 const char
1004 *option,
1005 *transforms;
1006
1007 Image
1008 *gainmap_images;
1009
1010 ImageInfo
1011 *gainmap_info;
1012
1013 MagickBooleanType
1014 status,
1015 transformed,
1016 transform_required;
1017
1018 size_t
1019 base_columns,
1020 base_rows,
1021 length;
1022
1023 StringInfo
1024 *profile;
1025
1026 void
1027 *blob;
1028
1029 assert(transform_status != (MagickBooleanType *) NULL);
1030 *transform_status=MagickTrue;
1031 base_columns=GetHDRGMPropertySize(image,"BaseWidth",exception);
1032 base_rows=GetHDRGMPropertySize(image,"BaseHeight",exception);
1033 transforms=GetImageProperty(image,"hdrgm:Transform",exception);
1034 transform_required=((transforms != (const char *) NULL) &&
1035 (*transforms != '\0')) ? MagickTrue : MagickFalse;
1036 if ((base_columns == 0) || (base_rows == 0))
1037 {
1038 if (transform_required != MagickFalse)
1039 {
1040 *transform_status=MagickFalse;
1041 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
1042 "UnableToTransformGainMap","`%s'",image->filename);
1043 }
1044 return((StringInfo *) NULL);
1045 }
1046 if ((base_columns != image->columns) || (base_rows != image->rows))
1047 {
1048 if (transform_required == MagickFalse)
1049 {
1050 *transform_status=MagickFalse;
1051 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
1052 "UnableToTransformGainMap","`%s'",image->filename);
1053 return((StringInfo *) NULL);
1054 }
1055 }
1056 if (transform_required == MagickFalse)
1057 return((StringInfo *) NULL);
1058 gainmap_info=CloneImageInfo(image_info);
1059 (void) CopyMagickString(gainmap_info->filename,"JPEG:hdrgm.jpg",
1060 MagickPathExtent);
1061 (void) CopyMagickString(gainmap_info->magick,"JPEG",MagickPathExtent);
1062 (void) SetImageOption(gainmap_info,"jpeg:detect-uhdr","false");
1063 gainmap_images=BlobToImage(gainmap_info,GetStringInfoDatum(gainmap_profile),
1064 GetStringInfoLength(gainmap_profile),exception);
1065 if (gainmap_images == (Image *) NULL)
1066 {
1067 gainmap_info=DestroyImageInfo(gainmap_info);
1068 *transform_status=MagickFalse;
1069 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
1070 "UnableToDecodeGainMap","`%s'",image->filename);
1071 return((StringInfo *) NULL);
1072 }
1073 status=MagickTrue;
1074 transformed=MagickFalse;
1075 if ((transforms != (const char *) NULL) && (*transforms != '\0'))
1076 {
1077 char
1078 *next,
1079 *transform,
1080 *transform_list;
1081
1082 transform_list=AcquireString(transforms);
1083 for (transform=transform_list; transform != (char *) NULL; )
1084 {
1085 next=strchr(transform,';');
1086 if (next != (char *) NULL)
1087 *next++='\0';
1088 if (*transform != '\0')
1089 {
1090 status=ApplyGainMapTransform(&gainmap_images,&base_columns,
1091 &base_rows,image,transform,exception);
1092 if (status == MagickFalse)
1093 break;
1094 transformed=MagickTrue;
1095 }
1096 transform=next;
1097 }
1098 transform_list=DestroyString(transform_list);
1099 }
1100 if ((status != MagickFalse) &&
1101 ((base_columns != image->columns) || (base_rows != image->rows)))
1102 status=MagickFalse;
1103 if (status == MagickFalse)
1104 {
1105 gainmap_info=DestroyImageInfo(gainmap_info);
1106 gainmap_images=DestroyImageList(gainmap_images);
1107 *transform_status=MagickFalse;
1108 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
1109 "UnableToTransformGainMap","`%s'",image->filename);
1110 return((StringInfo *) NULL);
1111 }
1112 if (transformed == MagickFalse)
1113 {
1114 gainmap_images=DestroyImageList(gainmap_images);
1115 gainmap_info=DestroyImageInfo(gainmap_info);
1116 return((StringInfo *) NULL);
1117 }
1118 option=GetImageOption(image_info,"uhdr:gainmap-quality");
1119 if (option != (const char *) NULL)
1120 gainmap_info->quality=StringToUnsignedLong(option);
1121 else if (image->quality > 0)
1122 gainmap_info->quality=image->quality;
1123 (void) CopyMagickString(gainmap_images->magick,"JPEG",MagickPathExtent);
1124 blob=ImageToBlob(gainmap_info,gainmap_images,&length,exception);
1125 gainmap_images=DestroyImageList(gainmap_images);
1126 gainmap_info=DestroyImageInfo(gainmap_info);
1127 if (blob == (void *) NULL)
1128 {
1129 *transform_status=MagickFalse;
1130 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
1131 "UnableToEncodeGainMap","`%s'",image->filename);
1132 return((StringInfo *) NULL);
1133 }
1134 profile=BlobToProfileStringInfo("hdrgm",blob,length,exception);
1135 blob=RelinquishMagickMemory(blob);
1136 if (profile == (StringInfo *) NULL)
1137 {
1138 *transform_status=MagickFalse;
1139 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
1140 "UnableToEncodeGainMap","`%s'",image->filename);
1141 }
1142 return(profile);
1143 }
1144
1145 static MagickBooleanType WriteUHDRImage(const ImageInfo *image_info,
1146 Image *images,ExceptionInfo *exception)
1147 {
1148 #define GetHDRGMProperty(name,field) \
1149 do { \
1150 const char *v = GetImageProperty(image,"hdrgm:" name,exception); \
1151 if (v != (const char *) NULL) \
1152 gainmap_info.field=(float) atof(v); \
1153 } while (0)
1154 #define GetHDRGMPropertyInt(name,field) \
1155 do { \
1156 const char *v = GetImageProperty(image,"hdrgm:" name,exception); \
1157 if (v != (const char *) NULL) \
1158 gainmap_info.field=atoi(v); \
1159 } while (0)
1160 #define GetHDRGMProperty3(name,field0,field1,field2) \
1161 do { \
1162 const char *v = GetImageProperty(image,"hdrgm:" name,exception); \
1163 if (v != (const char *) NULL) \
1164 (void) sscanf(v,"%f,%f,%f",&gainmap_info.field0,&gainmap_info.field1, \
1165 &gainmap_info.field2); \
1166 } while (0)
1167
1168 Image
1169 *image = images;
1170
1171 MagickBooleanType
1172 status = MagickTrue;
1173
1174 uhdr_raw_image_t
1175 hdrImgDescriptor = { 0 },
1176 sdrImgDescriptor = { 0 };
1177
1178 uhdr_mem_block_t
1179 sdr_profile = { 0 },
1180 hdr_profile = { 0 };
1181
1182 StringInfo
1183 *base_image_profile = (StringInfo *) NULL,
1184 *resized_gainmap_profile = (StringInfo *) NULL;
1185
1186 uhdr_compressed_image_t
1187 base_image = { 0 },
1188 gainmap_image = { 0 };
1189
1190 uhdr_gainmap_metadata_t
1191 gainmap_info = { 0 };
1192
1193 MagickBooleanType
1194 gainmap_transform_status = MagickTrue,
1195 preserve_gainmap = MagickFalse;
1196
1197 assert(image_info != (const ImageInfo *) NULL);
1198 assert(image_info->signature == MagickCoreSignature);
1199 assert(image != (Image *) NULL);
1200 assert(image->signature == MagickCoreSignature);
1201 if (IsEventLogging() != MagickFalse)
1202 (void) LogMagickEvent(TraceEvent, GetMagickModule(), "%s", image->filename);
1203 status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1204 if (status == MagickFalse)
1205 return (status);
1206
1207 const StringInfo *gainmap_profile = GetImageProfile(image,"hdrgm");
1208
1209 const size_t
1210 image_count = GetImageListLength(image);
1211
1212 if (gainmap_profile != (const StringInfo *) NULL)
1213 {
1214 /*
1215 Preserve gainmap+metadata (for transcoding). If these exist, we do not
1216 regenerate the gainmap. Instead, we pass them directly to the encoder.
1217 */
1218 /*
1219 Compressed image descriptor.
1220 */
1221 resized_gainmap_profile=TransformGainMapProfile(image_info,image,
1222 gainmap_profile,&gainmap_transform_status,exception);
1223 if (gainmap_transform_status == MagickFalse)
1224 {
1225 (void) CloseBlob(image);
1226 return(MagickFalse);
1227 }
1228 if (resized_gainmap_profile != (StringInfo *) NULL)
1229 gainmap_profile=(const StringInfo *) resized_gainmap_profile;
1230 base_image_profile=EncodeBaseImageProfile(image_info,image,exception);
1231 if (base_image_profile == (StringInfo *) NULL)
1232 {
1233 if (resized_gainmap_profile != (StringInfo *) NULL)
1234 resized_gainmap_profile=DestroyStringInfo(resized_gainmap_profile);
1235 (void) CloseBlob(image);
1236 return(MagickFalse);
1237 }
1238 base_image.data=(void *) GetStringInfoDatum(base_image_profile);
1239 base_image.data_sz=GetStringInfoLength(base_image_profile);
1240 base_image.capacity=base_image.data_sz;
1241 base_image.cg=getImageColorGamut(&image->chromaticity);
1242 base_image.ct=UHDR_CT_SRGB;
1243 base_image.range=UHDR_CR_FULL_RANGE;
1244 gainmap_image.data=(void *) GetStringInfoDatum(gainmap_profile);
1245 gainmap_image.data_sz=GetStringInfoLength(gainmap_profile);
1246 gainmap_image.capacity=gainmap_image.data_sz;
1247 gainmap_image.cg=UHDR_CG_UNSPECIFIED;
1248 gainmap_image.ct=UHDR_CT_UNSPECIFIED;
1249 gainmap_image.range=UHDR_CR_UNSPECIFIED;
1250 /*
1251 Gainmap metadata descriptor.
1252 */
1253 GetHDRGMProperty3("GainMapMax",max_content_boost[0],max_content_boost[1],
1254 max_content_boost[2]);
1255 GetHDRGMProperty3("GainMapMin",min_content_boost[0],min_content_boost[1],
1256 min_content_boost[2]);
1257 GetHDRGMProperty3("Gamma",gamma[0],gamma[1],gamma[2]);
1258 GetHDRGMProperty3("OffsetSDR",offset_sdr[0],offset_sdr[1],offset_sdr[2]);
1259 GetHDRGMProperty3("OffsetHDR",offset_hdr[0],offset_hdr[1],offset_hdr[2]);
1260 GetHDRGMProperty("HDRCapacityMin",hdr_capacity_min);
1261 GetHDRGMProperty("HDRCapacityMax",hdr_capacity_max);
1262 GetHDRGMPropertyInt("UseBaseColorGrade",use_base_cg);
1263 preserve_gainmap=MagickTrue;
1264 }
1265
1266 const char
1267 *option = GetImageOption(image_info,"uhdr:hdr-color-transfer");
1268
1269 uhdr_color_transfer_t
1270 hdr_ct = (option != (const char *) NULL) ? map_ct_to_uhdr_ct(option) : UHDR_CT_SRGB;
1271
1272 if (hdr_ct == UHDR_CT_UNSPECIFIED)
1273 {
1274 (void) ThrowMagickException(exception,GetMagickModule(),ConfigureWarning,
1275 "invalid hdr color transfer received, ","%s","exiting ... ");
1276 return(MagickFalse);
1277 }
1278
1279 /*
1280 HDR intent:
1281 color transfer linear, MUST be rgba half float - bitdepth is ATLEAST 16
1282 color transfer hlg or pq, MUST be rgba1010102/p010-bitdepth is ATLEAST 10
1283
1284 SDR intent
1285 color transfer sRGB MUST be rgba8888/yuv420 - bitdepth MUST be 8
1286 */
1287 int
1288 hdrIntentMinDepth = hdr_ct == UHDR_CT_LINEAR ? 16 : 10;
1289
1290 for (int i = 0; i < (ssize_t) image_count; i++)
1291 {
1292 /* Classify image as hdr/sdr intent basing on depth */
1293 int
1294 bpp;
1295
1296 ssize_t
1297 aligned_height,
1298 aligned_width;
1299
1300 size_t
1301 picSize;
1302
1303 void
1304 *crBuffer = NULL, *cbBuffer = NULL, *yBuffer = NULL;
1305
1306 if (((double) image->columns > sqrt(MAGICK_SSIZE_MAX/3.0)) ||
1307 ((double) image->rows > sqrt(MAGICK_SSIZE_MAX/3.0)))
1308 {
1309 (void) ThrowMagickException(exception,GetMagickModule(),ImageError,
1310 "WidthOrHeightExceedsLimit","%s",image->filename);
1311 goto next_image;
1312 }
1313 bpp = (int) image->depth >= hdrIntentMinDepth ? 2 : 1;
1314 if (IssRGBCompatibleColorspace(image->colorspace) && !IsGrayColorspace(image->colorspace))
1315 {
1316 if ((int) image->depth >= hdrIntentMinDepth && hdr_ct == UHDR_CT_LINEAR)
1317 bpp = 8; /* rgbahalf float */
1318 else
1319 bpp = 4; /* rgba1010102 or rgba8888 */
1320 }
1321 else if (IsYCbCrCompatibleColorspace(image->colorspace))
1322 {
1323 if ((int) image->depth >= hdrIntentMinDepth && hdr_ct == UHDR_CT_LINEAR)
1324 {
1325 (void) ThrowMagickException(exception, GetMagickModule(), ConfigureWarning,
1326 "linear color transfer inputs MUST be compatible with RGB Colorspace, ", "%s",
1327 "ignoring ...");
1328 goto next_image;
1329 }
1330 }
1331 else
1332 {
1333 (void) ThrowMagickException(exception, GetMagickModule(), ConfigureWarning,
1334 "Received image with color space incompatible with RGB/YCbCr, ","%s","ignoring ...");
1335 goto next_image;
1336 }
1337
1338 aligned_width = image->columns + (image->columns & 1);
1339 aligned_height = image->rows + (image->rows & 1);
1340 if (HeapOverflowSanityCheckGetSize(aligned_width,aligned_height,&picSize) != MagickFalse)
1341 {
1342 (void) ThrowMagickException(exception,GetMagickModule(),
1343 CorruptImageError,"ImproperImageHeader","%s",image->filename);
1344 goto next_image;
1345 }
1346 if (HeapOverflowSanityCheckGetSize(picSize,bpp,&picSize) != MagickFalse)
1347 {
1348 (void) ThrowMagickException(exception,GetMagickModule(),
1349 CorruptImageError,"ImproperImageHeader","%s",image->filename);
1350 goto next_image;
1351 }
1352 if (bpp < 4)
1353 {
1354 if (HeapOverflowSanityCheckGetSize(picSize,3,&picSize) != MagickFalse)
1355 {
1356 (void) ThrowMagickException(exception,GetMagickModule(),
1357 CorruptImageError,"ImproperImageHeader","%s",image->filename);
1358 goto next_image;
1359 }
1360 picSize/=2;
1361 }
1362
1363 if (((int) image->depth < hdrIntentMinDepth) && (image->depth != 8))
1364 {
1365 (void) ThrowMagickException(exception, GetMagickModule(), ConfigureWarning,
1366 "Received image with unexpected bit depth","%s","ignoring ...");
1367 goto next_image;
1368 }
1369
1370 if (((int) image->depth >= hdrIntentMinDepth) &&
1371 (hdrImgDescriptor.planes[UHDR_PLANE_Y] != NULL))
1372 {
1373 (void) ThrowMagickException(exception, GetMagickModule(), ConfigureWarning,
1374 "Received multiple hdr intent resources, ","%s","overwriting ...");
1375 RelinquishMagickMemory(hdrImgDescriptor.planes[UHDR_PLANE_Y]);
1376 hdrImgDescriptor.planes[UHDR_PLANE_Y] = NULL;
1377 }
1378 else if ((image->depth == 8) &&
1379 (sdrImgDescriptor.planes[UHDR_PLANE_Y] != NULL))
1380 {
1381 (void) ThrowMagickException(exception,GetMagickModule(),ConfigureWarning,
1382 "Received multiple sdr intent resources, ","%s","overwriting ...");
1383 RelinquishMagickMemory(sdrImgDescriptor.planes[UHDR_PLANE_Y]);
1384 sdrImgDescriptor.planes[UHDR_PLANE_Y] = NULL;
1385 }
1386
1387 yBuffer = AcquireMagickMemory(picSize);
1388 if (yBuffer == NULL)
1389 {
1390 status = MagickFalse;
1391 break;
1392 }
1393
1394 if ((int) image->depth >= hdrIntentMinDepth)
1395 {
1396 if (IsYCbCrCompatibleColorspace(image->colorspace))
1397 {
1398 cbBuffer = ((uint16_t *) yBuffer) + aligned_width * aligned_height;
1399 crBuffer = ((uint16_t *) cbBuffer) + 1;
1400
1401 fillRawImageDescriptor(&hdrImgDescriptor, image_info, image, UHDR_IMG_FMT_24bppYCbCrP010,
1402 hdr_ct);
1403
1404 hdrImgDescriptor.planes[UHDR_PLANE_Y] = yBuffer;
1405 hdrImgDescriptor.planes[UHDR_PLANE_UV] = cbBuffer;
1406 hdrImgDescriptor.planes[UHDR_PLANE_V] = NULL;
1407
1408 hdrImgDescriptor.stride[UHDR_PLANE_Y] = aligned_width;
1409 hdrImgDescriptor.stride[UHDR_PLANE_UV] = aligned_width;
1410 hdrImgDescriptor.stride[UHDR_PLANE_V] = 0;
1411 }
1412 else
1413 {
1414 fillRawImageDescriptor(&hdrImgDescriptor, image_info, image,
1415 hdr_ct == UHDR_CT_LINEAR ? UHDR_IMG_FMT_64bppRGBAHalfFloat
1416 : UHDR_IMG_FMT_32bppRGBA1010102,
1417 hdr_ct);
1418
1419 hdrImgDescriptor.planes[UHDR_PLANE_PACKED] = yBuffer;
1420 hdrImgDescriptor.planes[UHDR_PLANE_U] = NULL;
1421 hdrImgDescriptor.planes[UHDR_PLANE_V] = NULL;
1422
1423 hdrImgDescriptor.stride[UHDR_PLANE_PACKED] = aligned_width;
1424 hdrImgDescriptor.stride[UHDR_PLANE_U] = 0;
1425 hdrImgDescriptor.stride[UHDR_PLANE_V] = 0;
1426 }
1427
1428 hdr_profile = GetExifProfile(image, exception);
1429 }
1430 else if (image->depth == 8)
1431 {
1432 if (IsYCbCrCompatibleColorspace(image->colorspace))
1433 {
1434 cbBuffer = ((uint8_t *) yBuffer) + aligned_width * aligned_height;
1435 crBuffer = ((uint8_t *) cbBuffer) + ((aligned_width / 2) * (aligned_height / 2));
1436
1437 fillRawImageDescriptor(&sdrImgDescriptor, image_info, image, UHDR_IMG_FMT_12bppYCbCr420,
1438 UHDR_CT_SRGB);
1439
1440 sdrImgDescriptor.planes[UHDR_PLANE_Y] = yBuffer;
1441 sdrImgDescriptor.planes[UHDR_PLANE_U] = cbBuffer;
1442 sdrImgDescriptor.planes[UHDR_PLANE_V] = crBuffer;
1443
1444 sdrImgDescriptor.stride[UHDR_PLANE_Y] = aligned_width;
1445 sdrImgDescriptor.stride[UHDR_PLANE_U] = aligned_width / 2;
1446 sdrImgDescriptor.stride[UHDR_PLANE_V] = aligned_width / 2;
1447 }
1448 else
1449 {
1450 fillRawImageDescriptor(&sdrImgDescriptor, image_info, image, UHDR_IMG_FMT_32bppRGBA8888,
1451 UHDR_CT_SRGB);
1452
1453 sdrImgDescriptor.planes[UHDR_PLANE_PACKED] = yBuffer;
1454 sdrImgDescriptor.planes[UHDR_PLANE_U] = NULL;
1455 sdrImgDescriptor.planes[UHDR_PLANE_V] = NULL;
1456
1457 sdrImgDescriptor.stride[UHDR_PLANE_PACKED] = aligned_width;
1458 sdrImgDescriptor.stride[UHDR_PLANE_U] = 0;
1459 sdrImgDescriptor.stride[UHDR_PLANE_V] = 0;
1460 }
1461
1462 sdr_profile = GetExifProfile(image, exception);
1463 }
1464
1465 for (int y = 0; y < (ssize_t) image->rows; y++)
1466 {
1467 const Quantum
1468 *p;
1469
1470 ssize_t
1471 x;
1472
1473 p = GetVirtualPixels(image, 0, y, image->columns, 1, exception);
1474 if (p == (const Quantum *) NULL)
1475 {
1476 status = MagickFalse;
1477 break;
1478 }
1479
1480 for (x = 0; x < (ssize_t) image->columns; x++)
1481 {
1482 if ((int) image->depth >= hdrIntentMinDepth)
1483 {
1484 if (hdrImgDescriptor.fmt == UHDR_IMG_FMT_24bppYCbCrP010)
1485 {
1486 uint16_t
1487 *crBase = crBuffer, *cbBase = cbBuffer, *yBase = yBuffer;
1488
1489 yBase[y * hdrImgDescriptor.stride[UHDR_PLANE_Y] + x] =
1490 ScaleQuantumToShort(GetPixelY(image, p)) & 0xFFC0;
1491 if ((y % 2 == 0) && (x % 2 == 0))
1492 {
1493 cbBase[y / 2 * hdrImgDescriptor.stride[UHDR_PLANE_UV] + x] =
1494 ScaleQuantumToShort(GetPixelCb(image, p)) & 0xFFC0;
1495 crBase[y / 2 * hdrImgDescriptor.stride[UHDR_PLANE_UV] + x] =
1496 ScaleQuantumToShort(GetPixelCr(image, p)) & 0xFFC0;
1497 }
1498 }
1499 else if (hdrImgDescriptor.fmt == UHDR_IMG_FMT_64bppRGBAHalfFloat)
1500 {
1501 uint64_t
1502 *rgbaBase = yBuffer;
1503
1504 unsigned short
1505 r, g, b, a;
1506
1507 r = SinglePrecisionToHalf(QuantumScale * GetPixelRed(image, p));
1508 g = SinglePrecisionToHalf(QuantumScale * GetPixelGreen(image, p));
1509 b = SinglePrecisionToHalf(QuantumScale * GetPixelBlue(image, p));
1510 a = SinglePrecisionToHalf(QuantumScale * GetPixelAlpha(image, p));
1511
1512 rgbaBase[y * hdrImgDescriptor.stride[UHDR_PLANE_PACKED] + x] =
1513 ((uint64_t)a << 48) | ((uint64_t)b << 32) | (g << 16) | (r);
1514 }
1515 else
1516 {
1517 uint32_t
1518 *rgbBase = yBuffer;
1519
1520 unsigned short
1521 r, g, b;
1522
1523 r = ScaleQuantumToShort(GetPixelRed(image, p)) & 0xFFC0;
1524 g = ScaleQuantumToShort(GetPixelGreen(image, p)) & 0xFFC0;
1525 b = ScaleQuantumToShort(GetPixelBlue(image, p)) & 0xFFC0;
1526
1527 rgbBase[y * hdrImgDescriptor.stride[UHDR_PLANE_PACKED] + x] =
1528 (0x3U << 30) | (b << 14) | (g << 4) | (r >> 6);
1529 }
1530 }
1531 else if (image->depth == 8)
1532 {
1533 if (sdrImgDescriptor.fmt == UHDR_IMG_FMT_12bppYCbCr420)
1534 {
1535 uint8_t
1536 *crBase = crBuffer, *cbBase = cbBuffer, *yBase = yBuffer;
1537
1538 yBase[y * sdrImgDescriptor.stride[UHDR_PLANE_Y] + x] =
1539 ScaleQuantumToChar(GetPixelY(image, p));
1540 if ((y % 2 == 0) && (x % 2 == 0))
1541 {
1542 cbBase[y / 2 * sdrImgDescriptor.stride[UHDR_PLANE_U] + x / 2] =
1543 ScaleQuantumToChar(GetPixelCb(image, p));
1544 crBase[y / 2 * sdrImgDescriptor.stride[UHDR_PLANE_V] + x / 2] =
1545 ScaleQuantumToChar(GetPixelCr(image, p));
1546 }
1547 }
1548 else
1549 {
1550 uint32_t
1551 *rgbBase = yBuffer;
1552
1553 unsigned char
1554 r, g, b;
1555
1556 r = ScaleQuantumToChar(GetPixelRed(image, p));
1557 g = ScaleQuantumToChar(GetPixelGreen(image, p));
1558 b = ScaleQuantumToChar(GetPixelBlue(image, p));
1559
1560 rgbBase[y * sdrImgDescriptor.stride[UHDR_PLANE_PACKED] + x] = (b << 16) | (g << 8) | r;
1561 }
1562 }
1563 p += GetPixelChannels(image);
1564 }
1565 }
1566
1567 next_image:
1568 if (i != (ssize_t) image_count - 1)
1569 {
1570 if (GetNextImageInList(image) == (Image *) NULL)
1571 {
1572 status = MagickFalse;
1573 break;
1574 }
1575 image = SyncNextImageInList(image);
1576 if (image == (Image *) NULL)
1577 break;
1578 }
1579
1580 status = SetImageProgress(image, SaveImageTag, (MagickOffsetType)i,
1581 image_count);
1582 if (status == MagickFalse)
1583 break;
1584 }
1585
1586 if (status != MagickFalse)
1587 {
1588 uhdr_codec_private_t *handle = uhdr_create_encoder();
1589
1590 #define CHECK_IF_ERR(x) \
1591 { \
1592 uhdr_error_info_t retval = (x); \
1593 if (retval.error_code != UHDR_CODEC_OK) \
1594 { \
1595 (void)ThrowMagickException(exception, GetMagickModule(), CoderError, \
1596 retval.has_detail ? retval.detail : "unknown error", "`%s'", \
1597 image->filename); \
1598 uhdr_release_encoder(handle); \
1599 status = MagickFalse; \
1600 } \
1601 }
1602
1603 if (handle == NULL)
1604 {
1605 (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
1606 "FailedToCreateEncoder","`%s'",image->filename);
1607 status=MagickFalse;
1608 }
1609
1610 if ((status != MagickFalse) && (preserve_gainmap != MagickFalse))
1611 {
1612 CHECK_IF_ERR(uhdr_enc_set_compressed_image(handle,&base_image,
1613 UHDR_BASE_IMG))
1614 if (status != MagickFalse)
1615 CHECK_IF_ERR(uhdr_enc_set_gainmap_image(handle,&gainmap_image,
1616 &gainmap_info))
1617 }
1618 else
1619 {
1620 /* Configure hdr and sdr intents */
1621 if (status != MagickFalse && hdrImgDescriptor.planes[UHDR_PLANE_Y])
1622 {
1623 CHECK_IF_ERR(uhdr_enc_set_raw_image(handle, &hdrImgDescriptor, UHDR_HDR_IMG))
1624 if (hdr_profile.data_sz != 0)
1625 CHECK_IF_ERR(uhdr_enc_set_exif_data(handle, &hdr_profile))
1626 }
1627
1628 if (status != MagickFalse && sdrImgDescriptor.planes[UHDR_PLANE_Y])
1629 {
1630 CHECK_IF_ERR(uhdr_enc_set_raw_image(handle, &sdrImgDescriptor, UHDR_SDR_IMG))
1631 if (sdr_profile.data_sz != 0)
1632 CHECK_IF_ERR(uhdr_enc_set_exif_data(handle, &sdr_profile))
1633 }
1634 }
1635
1636 /* Configure encoding settings */
1637 if (status != MagickFalse && image->quality > 0 && image->quality <= 100)
1638 CHECK_IF_ERR(uhdr_enc_set_quality(handle, image->quality, UHDR_BASE_IMG))
1639
1640 const char
1641 *option;
1642
1643 if ((status != MagickFalse) && (preserve_gainmap == MagickFalse))
1644 {
1645 option = GetImageOption(image_info, "uhdr:gainmap-quality");
1646 if (option != (const char *)NULL)
1647 CHECK_IF_ERR(uhdr_enc_set_quality(handle, atoi(option), UHDR_GAIN_MAP_IMG))
1648 }
1649
1650 if ((status != MagickFalse) && (preserve_gainmap == MagickFalse))
1651 CHECK_IF_ERR(uhdr_enc_set_using_multi_channel_gainmap(handle, 1))
1652
1653 if ((status != MagickFalse) && (preserve_gainmap == MagickFalse))
1654 CHECK_IF_ERR(uhdr_enc_set_gainmap_scale_factor(handle, 1))
1655
1656 if ((status != MagickFalse) && (preserve_gainmap == MagickFalse))
1657 CHECK_IF_ERR(uhdr_enc_set_preset(handle, UHDR_USAGE_BEST_QUALITY))
1658
1659 /* Configure gainmap metadata */
1660 if ((status != MagickFalse) && (preserve_gainmap == MagickFalse))
1661 {
1662 option = GetImageOption(image_info, "uhdr:gainmap-gamma");
1663 if (option != (const char *)NULL)
1664 CHECK_IF_ERR(uhdr_enc_set_gainmap_gamma(handle, atof(option)))
1665 }
1666
1667 if ((status != MagickFalse) && (preserve_gainmap == MagickFalse))
1668 {
1669 option = GetImageOption(image_info, "uhdr:gainmap-min-content-boost");
1670 float minContentBoost = option != (const char *)NULL ? atof(option) : FLT_MIN;
1671
1672 option = GetImageOption(image_info, "uhdr:gainmap-max-content-boost");
1673 float maxContentBoost = option != (const char *)NULL ? atof(option) : FLT_MAX;
1674
1675 if (minContentBoost != FLT_MIN || maxContentBoost != FLT_MAX)
1676 CHECK_IF_ERR(uhdr_enc_set_min_max_content_boost(handle, minContentBoost, maxContentBoost))
1677 }
1678
1679 if ((status != MagickFalse) && (preserve_gainmap == MagickFalse))
1680 {
1681 option = GetImageOption(image_info, "uhdr:target-display-peak-brightness");
1682 float targetDispPeakBrightness = option != (const char *)NULL ? atof(option) : -1.0f;
1683
1684 if (targetDispPeakBrightness > 0.0f)
1685
1686 CHECK_IF_ERR(uhdr_enc_set_target_display_peak_brightness(handle, targetDispPeakBrightness))
1687 }
1688
1689 if (status != MagickFalse)
1690 CHECK_IF_ERR(uhdr_encode(handle))
1691
1692 if (status != MagickFalse)
1693 {
1694 uhdr_compressed_image_t *output = uhdr_get_encoded_stream(handle);
1695
1696 (void) WriteBlob(image, output->data_sz, output->data);
1697
1698 uhdr_release_encoder(handle);
1699 }
1700 }
1701 #undef CHECK_IF_ERR
1702
1703 if (CloseBlob(image) == MagickFalse)
1704 status = MagickFalse;
1705
1706 if (hdrImgDescriptor.planes[UHDR_PLANE_Y])
1707 RelinquishMagickMemory(hdrImgDescriptor.planes[UHDR_PLANE_Y]);
1708
1709 if (sdrImgDescriptor.planes[UHDR_PLANE_Y])
1710 RelinquishMagickMemory(sdrImgDescriptor.planes[UHDR_PLANE_Y]);
1711
1712 if (resized_gainmap_profile != (StringInfo *) NULL)
1713 resized_gainmap_profile=DestroyStringInfo(resized_gainmap_profile);
1714
1715 if (base_image_profile != (StringInfo *) NULL)
1716 base_image_profile=DestroyStringInfo(base_image_profile);
1717
1718 return status;
1719 }
1720 #endif