]> granicus.if.org Git - imagemagick/blob - coders/jp2.c
Fix improper cast that could cause an overflow as demonstrated in #347.
[imagemagick] / coders / jp2.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                              JJJ  PPPP    222                               %
7 %                               J   P   P  2   2                              %
8 %                               J   PPPP     22                               %
9 %                            J  J   P       2                                 %
10 %                             JJ    P      22222                              %
11 %                                                                             %
12 %                                                                             %
13 %                     Read/Write JPEG-2000 Image Format                       %
14 %                                                                             %
15 %                                   Cristy                                    %
16 %                                Nathan Brown                                 %
17 %                                 June 2001                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization      %
21 %  dedicated to making software imaging solutions freely available.           %
22 %                                                                             %
23 %  You may not use this file except in compliance with the License.  You may  %
24 %  obtain a copy of the License at                                            %
25 %                                                                             %
26 %    http://www.imagemagick.org/script/license.php                            %
27 %                                                                             %
28 %  Unless required by applicable law or agreed to in writing, software        %
29 %  distributed under the License is distributed on an "AS IS" BASIS,          %
30 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
31 %  See the License for the specific language governing permissions and        %
32 %  limitations under the License.                                             %
33 %                                                                             %
34 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
35 %
36 %
37 */
38 \f
39 /*
40   Include declarations.
41 */
42 #include "MagickCore/studio.h"
43 #include "MagickCore/artifact.h"
44 #include "MagickCore/attribute.h"
45 #include "MagickCore/blob.h"
46 #include "MagickCore/blob-private.h"
47 #include "MagickCore/cache.h"
48 #include "MagickCore/colorspace.h"
49 #include "MagickCore/colorspace-private.h"
50 #include "MagickCore/color.h"
51 #include "MagickCore/color-private.h"
52 #include "MagickCore/exception.h"
53 #include "MagickCore/exception-private.h"
54 #include "MagickCore/image.h"
55 #include "MagickCore/image-private.h"
56 #include "MagickCore/list.h"
57 #include "MagickCore/magick.h"
58 #include "MagickCore/memory_.h"
59 #include "MagickCore/monitor.h"
60 #include "MagickCore/monitor-private.h"
61 #include "MagickCore/option.h"
62 #include "MagickCore/pixel-accessor.h"
63 #include "MagickCore/profile.h"
64 #include "MagickCore/property.h"
65 #include "MagickCore/quantum-private.h"
66 #include "MagickCore/semaphore.h"
67 #include "MagickCore/static.h"
68 #include "MagickCore/statistic.h"
69 #include "MagickCore/string_.h"
70 #include "MagickCore/string-private.h"
71 #include "MagickCore/module.h"
72 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
73 #include <openjpeg.h>
74 #endif
75 \f
76 /*
77   Forward declarations.
78 */
79 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
80 static MagickBooleanType
81   WriteJP2Image(const ImageInfo *,Image *,ExceptionInfo *);
82 #endif
83 \f
84 /*
85 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
86 %                                                                             %
87 %                                                                             %
88 %                                                                             %
89 %   I s J 2 K                                                                 %
90 %                                                                             %
91 %                                                                             %
92 %                                                                             %
93 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
94 %
95 %  IsJ2K() returns MagickTrue if the image format type, identified by the
96 %  magick string, is J2K.
97 %
98 %  The format of the IsJ2K method is:
99 %
100 %      MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
101 %
102 %  A description of each parameter follows:
103 %
104 %    o magick: compare image format pattern against these bytes.
105 %
106 %    o length: Specifies the length of the magick string.
107 %
108 */
109 static MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
110 {
111   if (length < 4)
112     return(MagickFalse);
113   if (memcmp(magick,"\xff\x4f\xff\x51",4) == 0)
114     return(MagickTrue);
115   return(MagickFalse);
116 }
117 \f
118 /*
119 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
120 %                                                                             %
121 %                                                                             %
122 %                                                                             %
123 %   I s J P 2                                                                 %
124 %                                                                             %
125 %                                                                             %
126 %                                                                             %
127 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
128 %
129 %  IsJP2() returns MagickTrue if the image format type, identified by the
130 %  magick string, is JP2.
131 %
132 %  The format of the IsJP2 method is:
133 %
134 %      MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
135 %
136 %  A description of each parameter follows:
137 %
138 %    o magick: compare image format pattern against these bytes.
139 %
140 %    o length: Specifies the length of the magick string.
141 %
142 */
143 static MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
144 {
145   if (length < 4)
146     return(MagickFalse);
147   if (memcmp(magick,"\x0d\x0a\x87\x0a",4) == 0)
148     return(MagickTrue);
149   if (length < 12)
150     return(MagickFalse);
151   if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0)
152     return(MagickTrue);
153   return(MagickFalse);
154 }
155 \f
156 /*
157 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
158 %                                                                             %
159 %                                                                             %
160 %                                                                             %
161 %   R e a d J P 2 I m a g e                                                   %
162 %                                                                             %
163 %                                                                             %
164 %                                                                             %
165 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
166 %
167 %  ReadJP2Image() reads a JPEG 2000 Image file (JP2) or JPEG 2000
168 %  codestream (JPC) image file and returns it.  It allocates the memory
169 %  necessary for the new Image structure and returns a pointer to the new
170 %  image or set of images.
171 %
172 %  JP2 support is originally written by Nathan Brown, nathanbrown@letu.edu.
173 %
174 %  The format of the ReadJP2Image method is:
175 %
176 %      Image *ReadJP2Image(const ImageInfo *image_info,
177 %        ExceptionInfo *exception)
178 %
179 %  A description of each parameter follows:
180 %
181 %    o image_info: the image info.
182 %
183 %    o exception: return any errors or warnings in this structure.
184 %
185 */
186 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
187 static void JP2ErrorHandler(const char *message,void *client_data)
188 {
189   ExceptionInfo
190     *exception;
191
192   exception=(ExceptionInfo *) client_data;
193   (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
194     message,"`%s'","OpenJP2");
195 }
196
197 static OPJ_SIZE_T JP2ReadHandler(void *buffer,OPJ_SIZE_T length,void *context)
198 {
199   Image
200     *image;
201
202   ssize_t
203     count;
204
205   image=(Image *) context;
206   count=ReadBlob(image,(ssize_t) length,(unsigned char *) buffer);
207   if (count == 0)
208     return((OPJ_SIZE_T) -1);
209   return((OPJ_SIZE_T) count);
210 }
211
212 static OPJ_BOOL JP2SeekHandler(OPJ_OFF_T offset,void *context)
213 {
214   Image
215     *image;
216
217   image=(Image *) context;
218   return(SeekBlob(image,offset,SEEK_SET) < 0 ? OPJ_FALSE : OPJ_TRUE);
219 }
220
221 static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context)
222 {
223   Image
224     *image;
225
226   image=(Image *) context;
227   return(SeekBlob(image,offset,SEEK_CUR) < 0 ? -1 : offset);
228 }
229
230 static void JP2WarningHandler(const char *message,void *client_data)
231 {
232   ExceptionInfo
233     *exception;
234
235   exception=(ExceptionInfo *) client_data;
236   (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
237     message,"`%s'","OpenJP2");
238 }
239
240 static OPJ_SIZE_T JP2WriteHandler(void *buffer,OPJ_SIZE_T length,void *context)
241 {
242   Image
243     *image;
244
245   ssize_t
246     count;
247
248   image=(Image *) context;
249   count=WriteBlob(image,(ssize_t) length,(unsigned char *) buffer);
250   return((OPJ_SIZE_T) count);
251 }
252
253 static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
254 {
255   const char
256     *option;
257
258   Image
259     *image;
260
261   int
262     jp2_status;
263
264   MagickBooleanType
265     status;
266
267   opj_codec_t
268     *jp2_codec;
269
270   opj_codestream_index_t
271     *codestream_index = (opj_codestream_index_t *) NULL;
272
273   opj_dparameters_t
274     parameters;
275
276   opj_image_t
277     *jp2_image;
278
279   opj_stream_t
280     *jp2_stream;
281
282   register ssize_t
283     i;
284
285   ssize_t
286     y;
287
288   unsigned char
289     sans[4];
290
291   /*
292     Open image file.
293   */
294   assert(image_info != (const ImageInfo *) NULL);
295   assert(image_info->signature == MagickCoreSignature);
296   if (image_info->debug != MagickFalse)
297     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
298       image_info->filename);
299   assert(exception != (ExceptionInfo *) NULL);
300   assert(exception->signature == MagickCoreSignature);
301   image=AcquireImage(image_info,exception);
302   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
303   if (status == MagickFalse)
304     {
305       image=DestroyImageList(image);
306       return((Image *) NULL);
307     }
308   /*
309     Initialize JP2 codec.
310   */
311   if (ReadBlob(image,4,sans) != 4)
312     {
313       image=DestroyImageList(image);
314       return((Image *) NULL);
315     }
316   (void) SeekBlob(image,SEEK_SET,0);
317   if (LocaleCompare(image_info->magick,"JPT") == 0)
318     jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
319   else
320     if (IsJ2K(sans,4) != MagickFalse)
321       jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
322     else
323       jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
324   opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
325   opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
326   opj_set_default_decoder_parameters(&parameters);
327   option=GetImageOption(image_info,"jp2:reduce-factor");
328   if (option != (const char *) NULL)
329     parameters.cp_reduce=StringToInteger(option);
330   option=GetImageOption(image_info,"jp2:quality-layers");
331   if (option != (const char *) NULL)
332     parameters.cp_layer=StringToInteger(option);
333   if (opj_setup_decoder(jp2_codec,&parameters) == 0)
334     {
335       opj_destroy_codec(jp2_codec);
336       ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
337     }
338   jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,1);
339   opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
340   opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
341   opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
342   opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
343   opj_stream_set_user_data(jp2_stream,image,NULL);
344   opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
345   if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
346     {
347       opj_stream_destroy(jp2_stream);
348       opj_destroy_codec(jp2_codec);
349       ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
350     }
351   jp2_status=1;
352   if ((image->columns != 0) && (image->rows != 0))
353     {
354       /*
355         Extract an area from the image.
356       */
357       jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
358         (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
359         (OPJ_INT32) (image->extract_info.x+(ssize_t) image->columns),
360         (OPJ_INT32) (image->extract_info.y+(ssize_t) image->rows));
361       if (jp2_status == 0)
362         {
363           opj_stream_destroy(jp2_stream);
364           opj_destroy_codec(jp2_codec);
365           opj_image_destroy(jp2_image);
366           ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
367         }
368     }
369    if ((image_info->number_scenes != 0) && (image_info->scene != 0))
370     jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
371       (unsigned int) image_info->scene-1);
372   else
373     if (image->ping == MagickFalse)
374       {
375         jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
376         if (jp2_status != 0)
377           jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
378       }
379   if (jp2_status == 0)
380     {
381       opj_stream_destroy(jp2_stream);
382       opj_destroy_codec(jp2_codec);
383       opj_image_destroy(jp2_image);
384       ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
385     }
386   opj_stream_destroy(jp2_stream);
387   for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
388   {
389     if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0))
390       {
391         opj_destroy_codec(jp2_codec);
392         opj_image_destroy(jp2_image);
393         ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
394       }
395   }
396   /*
397     Convert JP2 image.
398   */
399   image->columns=(size_t) jp2_image->comps[0].w;
400   image->rows=(size_t) jp2_image->comps[0].h;
401   image->depth=jp2_image->comps[0].prec;
402   status=SetImageExtent(image,image->columns,image->rows,exception);
403   if (status == MagickFalse)
404     return(DestroyImageList(image));
405   image->compression=JPEG2000Compression;
406   if (jp2_image->numcomps <= 2)
407     {
408       SetImageColorspace(image,GRAYColorspace,exception);
409       if (jp2_image->numcomps > 1)
410         image->alpha_trait=BlendPixelTrait;
411     }
412   if (jp2_image->numcomps > 3)
413     image->alpha_trait=BlendPixelTrait;
414   for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
415     if ((jp2_image->comps[i].dx > 1) || (jp2_image->comps[i].dy > 1))
416       SetImageColorspace(image,YUVColorspace,exception);
417   if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
418     {
419       StringInfo
420         *profile;
421
422       profile=BlobToStringInfo(jp2_image->icc_profile_buf,
423         jp2_image->icc_profile_len);
424       if (profile != (StringInfo *) NULL)
425         SetImageProfile(image,"icc",profile,exception);
426     }
427   if (image->ping != MagickFalse)
428     {
429       opj_destroy_codec(jp2_codec);
430       opj_image_destroy(jp2_image);
431       opj_destroy_cstr_index(&codestream_index);
432       return(GetFirstImageInList(image));
433     }
434   for (y=0; y < (ssize_t) image->rows; y++)
435   {
436     register Quantum
437       *magick_restrict q;
438
439     register ssize_t
440       x;
441
442     q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
443     if (q == (Quantum *) NULL)
444       break;
445     for (x=0; x < (ssize_t) image->columns; x++)
446     {
447       register ssize_t
448         i;
449
450       for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
451       {
452         double
453           pixel,
454           scale;
455
456         scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
457         pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
458           image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
459           (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
460         switch (i)
461         {
462            case 0:
463            {
464              SetPixelRed(image,ClampToQuantum(pixel),q);
465              SetPixelGreen(image,ClampToQuantum(pixel),q);
466              SetPixelBlue(image,ClampToQuantum(pixel),q);
467              SetPixelAlpha(image,OpaqueAlpha,q);
468              break;
469            }
470            case 1:
471            {
472              if (jp2_image->numcomps == 2)
473                {
474                  SetPixelAlpha(image,ClampToQuantum(pixel),q);
475                  break;
476                }
477              SetPixelGreen(image,ClampToQuantum(pixel),q);
478              break;
479            }
480            case 2:
481            {
482              SetPixelBlue(image,ClampToQuantum(pixel),q);
483              break;
484            }
485            case 3:
486            {
487              SetPixelAlpha(image,ClampToQuantum(pixel),q);
488              break;
489            }
490         }
491       }
492       q+=GetPixelChannels(image);
493     }
494     if (SyncAuthenticPixels(image,exception) == MagickFalse)
495       break;
496     status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
497       image->rows);
498     if (status == MagickFalse)
499       break;
500   }
501   /*
502     Free resources.
503   */
504   opj_destroy_codec(jp2_codec);
505   opj_image_destroy(jp2_image);
506   opj_destroy_cstr_index(&codestream_index);
507   (void) CloseBlob(image);
508   return(GetFirstImageInList(image));
509 }
510 #endif
511 \f
512 /*
513 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
514 %                                                                             %
515 %                                                                             %
516 %                                                                             %
517 %   R e g i s t e r J P 2 I m a g e                                           %
518 %                                                                             %
519 %                                                                             %
520 %                                                                             %
521 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
522 %
523 %  RegisterJP2Image() adds attributes for the JP2 image format to the list of
524 %  supported formats.  The attributes include the image format tag, a method
525 %  method to read and/or write the format, whether the format supports the
526 %  saving of more than one frame to the same file or blob, whether the format
527 %  supports native in-memory I/O, and a brief description of the format.
528 %
529 %  The format of the RegisterJP2Image method is:
530 %
531 %      size_t RegisterJP2Image(void)
532 %
533 */
534 ModuleExport size_t RegisterJP2Image(void)
535 {
536   char
537     version[MagickPathExtent];
538
539   MagickInfo
540     *entry;
541
542   *version='\0';
543 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
544   (void) FormatLocaleString(version,MagickPathExtent,"%s",opj_version());
545 #endif
546   entry=AcquireMagickInfo("JP2","JP2","JPEG-2000 File Format Syntax");
547   if (*version != '\0')
548     entry->version=ConstantString(version);
549   entry->mime_type=ConstantString("image/jp2");
550   entry->magick=(IsImageFormatHandler *) IsJP2;
551   entry->flags^=CoderAdjoinFlag;
552   entry->flags|=CoderSeekableStreamFlag;
553 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
554   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
555   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
556 #endif
557   (void) RegisterMagickInfo(entry);
558   entry=AcquireMagickInfo("JP2","J2C","JPEG-2000 Code Stream Syntax");
559   if (*version != '\0')
560     entry->version=ConstantString(version);
561   entry->mime_type=ConstantString("image/jp2");
562   entry->magick=(IsImageFormatHandler *) IsJ2K;
563   entry->flags^=CoderAdjoinFlag;
564   entry->flags|=CoderSeekableStreamFlag;
565 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
566   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
567   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
568 #endif
569   (void) RegisterMagickInfo(entry);
570   entry=AcquireMagickInfo("JP2","J2K","JPEG-2000 Code Stream Syntax");
571   if (*version != '\0')
572     entry->version=ConstantString(version);
573   entry->mime_type=ConstantString("image/jp2");
574   entry->magick=(IsImageFormatHandler *) IsJ2K;
575   entry->flags^=CoderAdjoinFlag;
576   entry->flags|=CoderSeekableStreamFlag;
577 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
578   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
579   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
580 #endif
581   (void) RegisterMagickInfo(entry);
582   entry=AcquireMagickInfo("JP2","JPM","JPEG-2000 File Format Syntax");
583   if (*version != '\0')
584     entry->version=ConstantString(version);
585   entry->mime_type=ConstantString("image/jp2");
586   entry->magick=(IsImageFormatHandler *) IsJP2;
587   entry->flags^=CoderAdjoinFlag;
588   entry->flags|=CoderSeekableStreamFlag;
589 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
590   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
591   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
592 #endif
593   (void) RegisterMagickInfo(entry);
594   entry=AcquireMagickInfo("JP2","JPT","JPEG-2000 File Format Syntax");
595   if (*version != '\0')
596     entry->version=ConstantString(version);
597   entry->mime_type=ConstantString("image/jp2");
598   entry->magick=(IsImageFormatHandler *) IsJP2;
599   entry->flags^=CoderAdjoinFlag;
600   entry->flags|=CoderSeekableStreamFlag;
601 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
602   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
603   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
604 #endif
605   (void) RegisterMagickInfo(entry);
606   entry=AcquireMagickInfo("JP2","JPC","JPEG-2000 Code Stream Syntax");
607   if (*version != '\0')
608     entry->version=ConstantString(version);
609   entry->mime_type=ConstantString("image/jp2");
610   entry->magick=(IsImageFormatHandler *) IsJP2;
611   entry->flags^=CoderAdjoinFlag;
612   entry->flags|=CoderSeekableStreamFlag;
613 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
614   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
615   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
616 #endif
617   (void) RegisterMagickInfo(entry);
618   return(MagickImageCoderSignature);
619 }
620 \f
621 /*
622 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
623 %                                                                             %
624 %                                                                             %
625 %                                                                             %
626 %   U n r e g i s t e r J P 2 I m a g e                                       %
627 %                                                                             %
628 %                                                                             %
629 %                                                                             %
630 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
631 %
632 %  UnregisterJP2Image() removes format registrations made by the JP2 module
633 %  from the list of supported formats.
634 %
635 %  The format of the UnregisterJP2Image method is:
636 %
637 %      UnregisterJP2Image(void)
638 %
639 */
640 ModuleExport void UnregisterJP2Image(void)
641 {
642   (void) UnregisterMagickInfo("JPC");
643   (void) UnregisterMagickInfo("JPT");
644   (void) UnregisterMagickInfo("JPM");
645   (void) UnregisterMagickInfo("JP2");
646   (void) UnregisterMagickInfo("J2K");
647 }
648 \f
649 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
650 /*
651 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
652 %                                                                             %
653 %                                                                             %
654 %                                                                             %
655 %   W r i t e J P 2 I m a g e                                                 %
656 %                                                                             %
657 %                                                                             %
658 %                                                                             %
659 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
660 %
661 %  WriteJP2Image() writes an image in the JPEG 2000 image format.
662 %
663 %  JP2 support originally written by Nathan Brown, nathanbrown@letu.edu
664 %
665 %  The format of the WriteJP2Image method is:
666 %
667 %      MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image,
668 %        ExceptionInfo *exception)
669 %
670 %  A description of each parameter follows.
671 %
672 %    o image_info: the image info.
673 %
674 %    o image:  The image.
675 %
676 */
677
678 static void CinemaProfileCompliance(const opj_image_t *jp2_image,
679   opj_cparameters_t *parameters)
680 {
681   /*
682     Digital Cinema 4K profile compliant codestream.
683   */
684   parameters->tile_size_on=OPJ_FALSE;
685   parameters->cp_tdx=1;
686   parameters->cp_tdy=1;
687   parameters->tp_flag='C';
688   parameters->tp_on=1;
689   parameters->cp_tx0=0;
690   parameters->cp_ty0=0;
691   parameters->image_offset_x0=0;
692   parameters->image_offset_y0=0;
693   parameters->cblockw_init=32;
694   parameters->cblockh_init=32;
695   parameters->csty|=0x01;
696   parameters->prog_order=OPJ_CPRL;
697   parameters->roi_compno=(-1);
698   parameters->subsampling_dx=1;
699   parameters->subsampling_dy=1;
700   parameters->irreversible=1;
701   if ((jp2_image->comps[0].w == 2048) || (jp2_image->comps[0].h == 1080))
702     {
703       /*
704         Digital Cinema 2K.
705       */
706       parameters->cp_cinema=OPJ_CINEMA2K_24;
707       parameters->cp_rsiz=OPJ_CINEMA2K;
708       parameters->max_comp_size=1041666;
709       if (parameters->numresolution > 6)
710         parameters->numresolution=6;
711
712     }
713   if ((jp2_image->comps[0].w == 4096) || (jp2_image->comps[0].h == 2160))
714     {
715       /*
716         Digital Cinema 4K.
717       */
718       parameters->cp_cinema=OPJ_CINEMA4K_24;
719       parameters->cp_rsiz=OPJ_CINEMA4K;
720       parameters->max_comp_size=1041666;
721       if (parameters->numresolution < 1)
722         parameters->numresolution=1;
723       if (parameters->numresolution > 7)
724         parameters->numresolution=7;
725       parameters->numpocs=2;
726       parameters->POC[0].tile=1;
727       parameters->POC[0].resno0=0;
728       parameters->POC[0].compno0=0;
729       parameters->POC[0].layno1=1;
730       parameters->POC[0].resno1=parameters->numresolution-1;
731       parameters->POC[0].compno1=3;
732       parameters->POC[0].prg1=OPJ_CPRL;
733       parameters->POC[1].tile=1;
734       parameters->POC[1].resno0=parameters->numresolution-1;
735       parameters->POC[1].compno0=0;
736       parameters->POC[1].layno1=1;
737       parameters->POC[1].resno1=parameters->numresolution;
738       parameters->POC[1].compno1=3;
739       parameters->POC[1].prg1=OPJ_CPRL;
740     }
741   parameters->tcp_numlayers=1;
742   parameters->tcp_rates[0]=((float) (jp2_image->numcomps*jp2_image->comps[0].w*
743     jp2_image->comps[0].h*jp2_image->comps[0].prec))/(parameters->max_comp_size*
744     8*jp2_image->comps[0].dx*jp2_image->comps[0].dy);
745   parameters->cp_disto_alloc=1;
746 }
747
748 static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image,
749   ExceptionInfo *exception)
750 {
751   const char
752     *option,
753     *property;
754
755   int
756     jp2_status;
757
758   MagickBooleanType
759     status;
760
761   opj_codec_t
762     *jp2_codec;
763
764   OPJ_COLOR_SPACE
765     jp2_colorspace;
766
767   opj_cparameters_t
768     parameters;
769
770   opj_image_cmptparm_t
771     jp2_info[5];
772
773   opj_image_t
774     *jp2_image;
775
776   opj_stream_t
777     *jp2_stream;
778
779   register ssize_t
780     i;
781
782   ssize_t
783     y;
784
785   unsigned int
786     channels;
787
788   /*
789     Open image file.
790   */
791   assert(image_info != (const ImageInfo *) NULL);
792   assert(image_info->signature == MagickCoreSignature);
793   assert(image != (Image *) NULL);
794   assert(image->signature == MagickCoreSignature);
795   if (image->debug != MagickFalse)
796     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
797   assert(exception != (ExceptionInfo *) NULL);
798   assert(exception->signature == MagickCoreSignature);
799   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
800   if (status == MagickFalse)
801     return(status);
802   /*
803     Initialize JPEG 2000 API.
804   */
805   opj_set_default_encoder_parameters(&parameters);
806   for (i=1; i < 6; i++)
807     if (((size_t) (1UL << (i+2)) > image->columns) &&
808         ((size_t) (1UL << (i+2)) > image->rows))
809       break;
810   parameters.numresolution=i;
811   option=GetImageOption(image_info,"jp2:number-resolutions");
812   if (option != (const char *) NULL)
813     parameters.numresolution=StringToInteger(option);
814   parameters.tcp_numlayers=1;
815   parameters.tcp_rates[0]=0;  /* lossless */
816   parameters.cp_disto_alloc=1;
817   if ((image_info->quality != 0) && (image_info->quality != 100))
818     {
819       parameters.tcp_distoratio[0]=(double) image_info->quality;
820       parameters.cp_fixed_quality=OPJ_TRUE;
821     }
822   if (image_info->extract != (char *) NULL)
823     {
824       RectangleInfo
825         geometry;
826
827       int
828         flags;
829
830       /*
831         Set tile size.
832       */
833       flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
834       parameters.cp_tdx=(int) geometry.width;
835       parameters.cp_tdy=(int) geometry.width;
836       if ((flags & HeightValue) != 0)
837         parameters.cp_tdy=(int) geometry.height;
838       if ((flags & XValue) != 0)
839         parameters.cp_tx0=geometry.x;
840       if ((flags & YValue) != 0)
841         parameters.cp_ty0=geometry.y;
842       parameters.tile_size_on=OPJ_TRUE;
843     }
844   option=GetImageOption(image_info,"jp2:quality");
845   if (option != (const char *) NULL)
846     {
847       register const char
848         *p;
849
850       /*
851         Set quality PSNR.
852       */
853       p=option;
854       for (i=0; sscanf(p,"%f",&parameters.tcp_distoratio[i]) == 1; i++)
855       {
856         if (i > 100)
857           break;
858         while ((*p != '\0') && (*p != ','))
859           p++;
860         if (*p == '\0')
861           break;
862         p++;
863       }
864       parameters.tcp_numlayers=i+1;
865       parameters.cp_fixed_quality=OPJ_TRUE;
866     }
867   option=GetImageOption(image_info,"jp2:progression-order");
868   if (option != (const char *) NULL)
869     {
870       if (LocaleCompare(option,"LRCP") == 0)
871         parameters.prog_order=OPJ_LRCP;
872       if (LocaleCompare(option,"RLCP") == 0)
873         parameters.prog_order=OPJ_RLCP;
874       if (LocaleCompare(option,"RPCL") == 0)
875         parameters.prog_order=OPJ_RPCL;
876       if (LocaleCompare(option,"PCRL") == 0)
877         parameters.prog_order=OPJ_PCRL;
878       if (LocaleCompare(option,"CPRL") == 0)
879         parameters.prog_order=OPJ_CPRL;
880     }
881   option=GetImageOption(image_info,"jp2:rate");
882   if (option != (const char *) NULL)
883     {
884       register const char
885         *p;
886
887       /*
888         Set compression rate.
889       */
890       p=option;
891       for (i=0; sscanf(p,"%f",&parameters.tcp_rates[i]) == 1; i++)
892       {
893         if (i >= 100)
894           break;
895         while ((*p != '\0') && (*p != ','))
896           p++;
897         if (*p == '\0')
898           break;
899         p++;
900       }
901       parameters.tcp_numlayers=i+1;
902       parameters.cp_disto_alloc=OPJ_TRUE;
903     }
904   if (image_info->sampling_factor != (const char *) NULL)
905     (void) sscanf(image_info->sampling_factor,"%d,%d",
906       &parameters.subsampling_dx,&parameters.subsampling_dy);
907   property=GetImageProperty(image,"comment",exception);
908   if (property != (const char *) NULL)
909     parameters.cp_comment=ConstantString(property);
910   channels=3;
911   jp2_colorspace=OPJ_CLRSPC_SRGB;
912   if (image->colorspace == YUVColorspace)
913     {
914       jp2_colorspace=OPJ_CLRSPC_SYCC;
915       parameters.subsampling_dx=2;
916     }
917   else
918     {
919       if (IsGrayColorspace(image->colorspace) != MagickFalse)
920         {
921           channels=1;
922           jp2_colorspace=OPJ_CLRSPC_GRAY;
923         }
924       else
925         (void) TransformImageColorspace(image,sRGBColorspace,exception);
926       if (image->alpha_trait != UndefinedPixelTrait)
927         channels++;
928     }
929   parameters.tcp_mct=channels == 3 ? 1 : 0;
930   ResetMagickMemory(jp2_info,0,sizeof(jp2_info));
931   for (i=0; i < (ssize_t) channels; i++)
932   {
933     jp2_info[i].prec=(OPJ_UINT32) image->depth;
934     jp2_info[i].bpp=(OPJ_UINT32) image->depth;
935     if ((image->depth == 1) &&
936         ((LocaleCompare(image_info->magick,"JPT") == 0) ||
937          (LocaleCompare(image_info->magick,"JP2") == 0)))
938       {
939         jp2_info[i].prec++;  /* OpenJPEG returns exception for depth @ 1 */
940         jp2_info[i].bpp++;
941       }
942     jp2_info[i].sgnd=0;
943     jp2_info[i].dx=parameters.subsampling_dx;
944     jp2_info[i].dy=parameters.subsampling_dy;
945     jp2_info[i].w=(OPJ_UINT32) image->columns;
946     jp2_info[i].h=(OPJ_UINT32) image->rows;
947   }
948   jp2_image=opj_image_create((OPJ_UINT32) channels,jp2_info,jp2_colorspace);
949   if (jp2_image == (opj_image_t *) NULL)
950     ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
951   jp2_image->x0=parameters.image_offset_x0;
952   jp2_image->y0=parameters.image_offset_y0;
953   jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)*
954     parameters.subsampling_dx+1);
955   jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)*
956     parameters.subsampling_dx+1);
957   if ((image->depth == 12) &&
958       ((image->columns == 2048) || (image->rows == 1080) ||
959        (image->columns == 4096) || (image->rows == 2160)))
960     CinemaProfileCompliance(jp2_image,&parameters);
961   if (channels == 4)
962     jp2_image->comps[3].alpha=1;
963   else
964    if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY))
965      jp2_image->comps[1].alpha=1;
966   /*
967     Convert to JP2 pixels.
968   */
969   for (y=0; y < (ssize_t) image->rows; y++)
970   {
971     register const Quantum
972       *p;
973
974     ssize_t
975       x;
976
977     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
978     if (p == (const Quantum *) NULL)
979       break;
980     for (x=0; x < (ssize_t) image->columns; x++)
981     {
982       for (i=0; i < (ssize_t) channels; i++)
983       {
984         double
985           scale;
986
987         register int
988           *q;
989
990         scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange;
991         q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy*
992           image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx);
993         switch (i)
994         {
995           case 0:
996           {
997             if (jp2_colorspace == OPJ_CLRSPC_GRAY)
998               {
999                 *q=(int) (scale*GetPixelLuma(image,p));
1000                 break;
1001               }
1002             *q=(int) (scale*GetPixelRed(image,p));
1003             break;
1004           }
1005           case 1:
1006           {
1007             if (jp2_colorspace == OPJ_CLRSPC_GRAY)
1008               {
1009                 *q=(int) (scale*GetPixelAlpha(image,p));
1010                 break;
1011               }
1012             *q=(int) (scale*GetPixelGreen(image,p));
1013             break;
1014           }
1015           case 2:
1016           {
1017             *q=(int) (scale*GetPixelBlue(image,p));
1018             break;
1019           }
1020           case 3:
1021           {
1022             *q=(int) (scale*GetPixelAlpha(image,p));
1023             break;
1024           }
1025         }
1026       }
1027       p+=GetPixelChannels(image);
1028     }
1029     status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1030       image->rows);
1031     if (status == MagickFalse)
1032       break;
1033   }
1034   if (LocaleCompare(image_info->magick,"JPT") == 0)
1035     jp2_codec=opj_create_compress(OPJ_CODEC_JPT);
1036   else
1037     if (LocaleCompare(image_info->magick,"J2K") == 0)
1038       jp2_codec=opj_create_compress(OPJ_CODEC_J2K);
1039     else
1040       jp2_codec=opj_create_compress(OPJ_CODEC_JP2);
1041   opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
1042   opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
1043   opj_setup_encoder(jp2_codec,&parameters,jp2_image);
1044   jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE);
1045   opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
1046   opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
1047   opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
1048   opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
1049   opj_stream_set_user_data(jp2_stream,image,NULL);
1050   if (jp2_stream == (opj_stream_t *) NULL)
1051     ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
1052   jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream);
1053   if (jp2_status == 0)
1054     ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
1055   if ((opj_encode(jp2_codec,jp2_stream) == 0) ||
1056       (opj_end_compress(jp2_codec,jp2_stream) == 0))
1057     {
1058       opj_stream_destroy(jp2_stream);
1059       opj_destroy_codec(jp2_codec);
1060       opj_image_destroy(jp2_image);
1061       ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
1062     }
1063   /*
1064     Free resources.
1065   */
1066   opj_stream_destroy(jp2_stream);
1067   opj_destroy_codec(jp2_codec);
1068   opj_image_destroy(jp2_image);
1069   (void) CloseBlob(image);
1070   return(MagickTrue);
1071 }
1072 #endif