]> granicus.if.org Git - imagemagick/blob - coders/jp2.c
(no commit message)
[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-2014 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 == MagickSignature);
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 == MagickSignature);
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   if ((image->columns != 0) && (image->rows != 0))
352     {
353       /*
354         Extract an area from the image.
355       */
356       jp2_status=opj_set_decode_area(jp2_codec,jp2_image,image->extract_info.x,
357         image->extract_info.y,image->extract_info.x+(ssize_t) image->columns,
358         image->extract_info.y+(ssize_t) image->rows);
359       if (jp2_status == 0)
360         {
361           opj_stream_destroy(jp2_stream);
362           opj_destroy_codec(jp2_codec);
363           opj_image_destroy(jp2_image);
364           ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
365         }
366     }
367   if (image_info->number_scenes != 0)
368     jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
369       (unsigned int) image_info->scene);
370   else
371     {
372       jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
373       if (jp2_status != 0)
374         jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
375     }
376   if (jp2_status == 0)
377     {
378       opj_stream_destroy(jp2_stream);
379       opj_destroy_codec(jp2_codec);
380       opj_image_destroy(jp2_image);
381       ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
382     }
383   opj_stream_destroy(jp2_stream);
384   for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
385   {
386     if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0))
387       {
388         opj_destroy_codec(jp2_codec);
389         opj_image_destroy(jp2_image);
390         ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
391       }
392   }
393   /*
394     Convert JP2 image.
395   */
396   image->columns=(size_t) jp2_image->comps[0].w;
397   image->rows=(size_t) jp2_image->comps[0].h;
398   image->depth=jp2_image->comps[0].prec;
399   image->compression=JPEG2000Compression;
400   if (jp2_image->numcomps <= 2)
401     {
402       SetImageColorspace(image,GRAYColorspace,exception);
403       if (jp2_image->numcomps > 1)
404         image->alpha_trait=BlendPixelTrait;
405     }
406   if (jp2_image->numcomps > 3)
407     image->alpha_trait=BlendPixelTrait;
408   for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
409     if ((jp2_image->comps[i].dx > 1) || (jp2_image->comps[i].dy > 1))
410       SetImageColorspace(image,YUVColorspace,exception);
411   if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
412     {
413       StringInfo
414         *profile;
415
416       profile=BlobToStringInfo(jp2_image->icc_profile_buf,
417         jp2_image->icc_profile_len);
418       if (profile != (StringInfo *) NULL)
419         SetImageProfile(image,"icc",profile,exception);
420     }
421   for (y=0; y < (ssize_t) image->rows; y++)
422   {
423     register Quantum
424       *restrict q;
425
426     register ssize_t
427       x;
428
429     q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
430     if (q == (Quantum *) NULL)
431       break;
432     for (x=0; x < (ssize_t) image->columns; x++)
433     {
434       register ssize_t
435         i;
436
437       for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
438       {
439         double
440           pixel,
441           scale;
442
443         scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
444         pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
445           image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
446           (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
447         switch (i)
448         {
449            case 0:
450            {
451              SetPixelRed(image,ClampToQuantum(pixel),q);
452              SetPixelGreen(image,ClampToQuantum(pixel),q);
453              SetPixelBlue(image,ClampToQuantum(pixel),q);
454              SetPixelAlpha(image,OpaqueAlpha,q);
455              break;
456            }
457            case 1:
458            {
459              if (jp2_image->numcomps == 2)
460                {
461                  SetPixelAlpha(image,ClampToQuantum(pixel),q);
462                  break;
463                }
464              SetPixelGreen(image,ClampToQuantum(pixel),q);
465              break;
466            }
467            case 2:
468            {
469              SetPixelBlue(image,ClampToQuantum(pixel),q);
470              break;
471            }
472            case 3:
473            {
474              SetPixelAlpha(image,ClampToQuantum(pixel),q);
475              break;
476            }
477         }
478       }
479       q+=GetPixelChannels(image);
480     }
481     if (SyncAuthenticPixels(image,exception) == MagickFalse)
482       break;
483     status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
484       image->rows);
485     if (status == MagickFalse)
486       break;
487   }
488   /*
489     Free resources.
490   */
491   opj_destroy_codec(jp2_codec);
492   opj_image_destroy(jp2_image);
493   opj_destroy_cstr_index(&codestream_index);
494   return(GetFirstImageInList(image));
495 }
496 #endif
497 \f
498 /*
499 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
500 %                                                                             %
501 %                                                                             %
502 %                                                                             %
503 %   R e g i s t e r J P 2 I m a g e                                           %
504 %                                                                             %
505 %                                                                             %
506 %                                                                             %
507 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
508 %
509 %  RegisterJP2Image() adds attributes for the JP2 image format to the list of
510 %  supported formats.  The attributes include the image format tag, a method
511 %  method to read and/or write the format, whether the format supports the
512 %  saving of more than one frame to the same file or blob, whether the format
513 %  supports native in-memory I/O, and a brief description of the format.
514 %
515 %  The format of the RegisterJP2Image method is:
516 %
517 %      size_t RegisterJP2Image(void)
518 %
519 */
520 ModuleExport size_t RegisterJP2Image(void)
521 {
522   char
523     version[MaxTextExtent];
524
525   MagickInfo
526     *entry;
527
528   *version='\0';
529 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
530   (void) FormatLocaleString(version,MaxTextExtent,"%s",opj_version());
531 #endif
532   entry=SetMagickInfo("JP2");
533   entry->description=ConstantString("JPEG-2000 File Format Syntax");
534   if (*version != '\0')
535     entry->version=ConstantString(version);
536   entry->mime_type=ConstantString("image/jp2");
537   entry->module=ConstantString("JP2");
538   entry->magick=(IsImageFormatHandler *) IsJP2;
539   entry->adjoin=MagickFalse;
540   entry->seekable_stream=MagickTrue;
541   entry->thread_support=NoThreadSupport;
542 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
543   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
544   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
545 #endif
546   (void) RegisterMagickInfo(entry);
547   entry=SetMagickInfo("J2C");
548   entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
549   if (*version != '\0')
550     entry->version=ConstantString(version);
551   entry->mime_type=ConstantString("image/jp2");
552   entry->module=ConstantString("JP2");
553   entry->magick=(IsImageFormatHandler *) IsJ2K;
554   entry->adjoin=MagickFalse;
555   entry->seekable_stream=MagickTrue;
556   entry->thread_support=NoThreadSupport;
557 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
558   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
559   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
560 #endif
561   (void) RegisterMagickInfo(entry);
562   entry=SetMagickInfo("J2K");
563   entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
564   if (*version != '\0')
565     entry->version=ConstantString(version);
566   entry->mime_type=ConstantString("image/jp2");
567   entry->module=ConstantString("JP2");
568   entry->magick=(IsImageFormatHandler *) IsJ2K;
569   entry->adjoin=MagickFalse;
570   entry->seekable_stream=MagickTrue;
571   entry->thread_support=NoThreadSupport;
572 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
573   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
574   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
575 #endif
576   (void) RegisterMagickInfo(entry);
577   entry=SetMagickInfo("JPM");
578   entry->description=ConstantString("JPEG-2000 File Format Syntax");
579   if (*version != '\0')
580     entry->version=ConstantString(version);
581   entry->mime_type=ConstantString("image/jp2");
582   entry->module=ConstantString("JP2");
583   entry->magick=(IsImageFormatHandler *) IsJP2;
584   entry->adjoin=MagickFalse;
585   entry->seekable_stream=MagickTrue;
586   entry->thread_support=NoThreadSupport;
587 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
588   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
589   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
590 #endif
591   (void) RegisterMagickInfo(entry);
592   entry=SetMagickInfo("JPT");
593   entry->description=ConstantString("JPEG-2000 File Format Syntax");
594   if (*version != '\0')
595     entry->version=ConstantString(version);
596   entry->mime_type=ConstantString("image/jp2");
597   entry->module=ConstantString("JP2");
598   entry->magick=(IsImageFormatHandler *) IsJP2;
599   entry->adjoin=MagickFalse;
600   entry->seekable_stream=MagickTrue;
601   entry->thread_support=NoThreadSupport;
602 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
603   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
604   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
605 #endif
606   (void) RegisterMagickInfo(entry);
607   entry=SetMagickInfo("JPC");
608   entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
609   if (*version != '\0')
610     entry->version=ConstantString(version);
611   entry->mime_type=ConstantString("image/jp2");
612   entry->module=ConstantString("JP2");
613   entry->magick=(IsImageFormatHandler *) IsJP2;
614   entry->adjoin=MagickFalse;
615   entry->seekable_stream=MagickTrue;
616   entry->thread_support=NoThreadSupport;
617 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
618   entry->decoder=(DecodeImageHandler *) ReadJP2Image;
619   entry->encoder=(EncodeImageHandler *) WriteJP2Image;
620 #endif
621   (void) RegisterMagickInfo(entry);
622   return(MagickImageCoderSignature);
623 }
624 \f
625 /*
626 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
627 %                                                                             %
628 %                                                                             %
629 %                                                                             %
630 %   U n r e g i s t e r J P 2 I m a g e                                       %
631 %                                                                             %
632 %                                                                             %
633 %                                                                             %
634 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
635 %
636 %  UnregisterJP2Image() removes format registrations made by the JP2 module
637 %  from the list of supported formats.
638 %
639 %  The format of the UnregisterJP2Image method is:
640 %
641 %      UnregisterJP2Image(void)
642 %
643 */
644 ModuleExport void UnregisterJP2Image(void)
645 {
646   (void) UnregisterMagickInfo("JPC");
647   (void) UnregisterMagickInfo("JPT");
648   (void) UnregisterMagickInfo("JPM");
649   (void) UnregisterMagickInfo("JP2");
650   (void) UnregisterMagickInfo("J2K");
651 }
652 \f
653 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
654 /*
655 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
656 %                                                                             %
657 %                                                                             %
658 %                                                                             %
659 %   W r i t e J P 2 I m a g e                                                 %
660 %                                                                             %
661 %                                                                             %
662 %                                                                             %
663 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
664 %
665 %  WriteJP2Image() writes an image in the JPEG 2000 image format.
666 %
667 %  JP2 support originally written by Nathan Brown, nathanbrown@letu.edu
668 %
669 %  The format of the WriteJP2Image method is:
670 %
671 %      MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image,
672 %        ExceptionInfo *exception)
673 %
674 %  A description of each parameter follows.
675 %
676 %    o image_info: the image info.
677 %
678 %    o image:  The image.
679 %
680 */
681
682 static void CinemaProfileCompliance(const opj_image_t *jp2_image,
683   opj_cparameters_t *parameters)
684 {
685   /*
686     Digital Cinema 4K profile compliant codestream.
687   */
688   parameters->tile_size_on=OPJ_FALSE;
689   parameters->cp_tdx=1;
690   parameters->cp_tdy=1;
691   parameters->tp_flag='C';
692   parameters->tp_on=1;
693   parameters->cp_tx0=0;
694   parameters->cp_ty0=0;
695   parameters->image_offset_x0=0;
696   parameters->image_offset_y0=0;
697   parameters->cblockw_init=32;
698   parameters->cblockh_init=32;
699   parameters->csty|=0x01;
700   parameters->prog_order=OPJ_CPRL;
701   parameters->roi_compno=(-1);
702   parameters->subsampling_dx=1;
703   parameters->subsampling_dy=1;
704   parameters->irreversible=1;
705   if ((jp2_image->comps[0].w == 2048) || (jp2_image->comps[0].h == 1080))
706     {
707       /*
708         Digital Cinema 2K.
709       */
710       parameters->cp_cinema=OPJ_CINEMA2K_24;
711       parameters->cp_rsiz=OPJ_CINEMA2K;
712       parameters->max_comp_size=1041666;
713       if (parameters->numresolution > 6)
714         parameters->numresolution=6;
715
716     }
717   if ((jp2_image->comps[0].w == 4096) || (jp2_image->comps[0].h == 2160))
718     {
719       /*
720         Digital Cinema 4K.
721       */
722       parameters->cp_cinema=OPJ_CINEMA4K_24;
723       parameters->cp_rsiz=OPJ_CINEMA4K;
724       parameters->max_comp_size=1041666;
725       if (parameters->numresolution < 1)
726         parameters->numresolution=1;
727       if (parameters->numresolution > 7)
728         parameters->numresolution=7;
729       parameters->numpocs=2;
730       parameters->POC[0].tile=1;
731       parameters->POC[0].resno0=0;
732       parameters->POC[0].compno0=0;
733       parameters->POC[0].layno1=1;
734       parameters->POC[0].resno1=parameters->numresolution-1;
735       parameters->POC[0].compno1=3;
736       parameters->POC[0].prg1=OPJ_CPRL;
737       parameters->POC[1].tile=1;
738       parameters->POC[1].resno0=parameters->numresolution-1;
739       parameters->POC[1].compno0=0;
740       parameters->POC[1].layno1=1;
741       parameters->POC[1].resno1=parameters->numresolution;
742       parameters->POC[1].compno1=3;
743       parameters->POC[1].prg1=OPJ_CPRL;
744     }
745   parameters->tcp_numlayers=1;
746   parameters->tcp_rates[0]=((float) (jp2_image->numcomps*jp2_image->comps[0].w*
747     jp2_image->comps[0].h*jp2_image->comps[0].prec))/(parameters->max_comp_size*
748     8*jp2_image->comps[0].dx*jp2_image->comps[0].dy);
749   parameters->cp_disto_alloc=1;
750 }
751
752 static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image,
753   ExceptionInfo *exception)
754 {
755   const char
756     *option,
757     *property;
758
759   int
760     jp2_status;
761
762   MagickBooleanType
763     status;
764
765   opj_codec_t
766     *jp2_codec;
767
768   OPJ_COLOR_SPACE
769     jp2_colorspace;
770
771   opj_cparameters_t
772     parameters;
773
774   opj_image_cmptparm_t
775     jp2_info[5];
776
777   opj_image_t
778     *jp2_image;
779
780   opj_stream_t
781     *jp2_stream;
782
783   register ssize_t
784     i;
785
786   ssize_t
787     y;
788
789   size_t
790     channels;
791
792   /*
793     Open image file.
794   */
795   assert(image_info != (const ImageInfo *) NULL);
796   assert(image_info->signature == MagickSignature);
797   assert(image != (Image *) NULL);
798   assert(image->signature == MagickSignature);
799   if (image->debug != MagickFalse)
800     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
801   assert(exception != (ExceptionInfo *) NULL);
802   assert(exception->signature == MagickSignature);
803   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
804   if (status == MagickFalse)
805     return(status);
806   /*
807     Initialize JPEG 2000 API.
808   */
809   opj_set_default_encoder_parameters(&parameters);
810   for (i=1; i < 6; i++)
811     if (((1U << (i+2)) > image->columns) && ((1U << (i+2)) > image->rows))
812       break;
813   parameters.numresolution=i;
814   option=GetImageOption(image_info,"jp2:number-resolutions");
815   if (option != (const char *) NULL)
816     parameters.numresolution=StringToInteger(option);
817   parameters.tcp_numlayers=1;
818   parameters.tcp_rates[0]=0;  /* lossless */
819   parameters.cp_disto_alloc=1;
820   if (image->quality != 0)
821     {
822       parameters.tcp_distoratio[0]=(double) image->quality;
823       parameters.cp_fixed_quality=OPJ_TRUE;
824     }
825   if (image_info->extract != (char *) NULL)
826     {
827       RectangleInfo
828         geometry;
829
830       int
831         flags;
832
833       /*
834         Set tile size.
835       */
836       flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
837       parameters.cp_tdx=(ssize_t) geometry.width;
838       parameters.cp_tdy=(ssize_t) geometry.width;
839       if ((flags & HeightValue) != 0)
840         parameters.cp_tdy=(ssize_t) geometry.height;
841       if ((flags & XValue) != 0)
842         parameters.cp_tx0=geometry.x;
843       if ((flags & YValue) != 0)
844         parameters.cp_ty0=geometry.y;
845       parameters.tile_size_on=OPJ_TRUE;
846     }
847   option=GetImageOption(image_info,"jp2:quality");
848   if (option != (const char *) NULL)
849     {
850       register const char
851         *p;
852
853       /*
854         Set quality PSNR.
855       */
856       p=option;
857       for (i=0; sscanf(p,"%f",&parameters.tcp_distoratio[i]) == 1; i++)
858       {
859         if (i > 100)
860           break;
861         while ((*p != '\0') && (*p != ','))
862           p++;
863         if (*p == '\0')
864           break;
865         p++;
866       }
867       parameters.tcp_numlayers=i+1;
868       parameters.cp_fixed_quality=OPJ_TRUE;
869     }
870   option=GetImageOption(image_info,"jp2:progression-order");
871   if (option != (const char *) NULL)
872     {
873       if (LocaleCompare(option,"LRCP") == 0)
874         parameters.prog_order=OPJ_LRCP;
875       if (LocaleCompare(option,"RLCP") == 0)
876         parameters.prog_order=OPJ_RLCP;
877       if (LocaleCompare(option,"RPCL") == 0)
878         parameters.prog_order=OPJ_RPCL;
879       if (LocaleCompare(option,"PCRL") == 0)
880         parameters.prog_order=OPJ_PCRL;
881       if (LocaleCompare(option,"CPRL") == 0)
882         parameters.prog_order=OPJ_CPRL;
883     }
884   option=GetImageOption(image_info,"jp2:rate");
885   if (option != (const char *) NULL)
886     {
887       register const char
888         *p;
889
890       /*
891         Set compression rate.
892       */
893       p=option;
894       for (i=0; sscanf(p,"%f",&parameters.tcp_rates[i]) == 1; i++)
895       {
896         if (i >= 100)
897           break;
898         while ((*p != '\0') && (*p != ','))
899           p++;
900         if (*p == '\0')
901           break;
902         p++;
903       }
904       parameters.tcp_numlayers=i+1;
905       parameters.cp_disto_alloc=OPJ_TRUE;
906     }
907   if (image_info->sampling_factor != (const char *) NULL)
908     (void) sscanf(image_info->sampling_factor,"%d,%d",
909       &parameters.subsampling_dx,&parameters.subsampling_dy);
910   property=GetImageProperty(image,"comment",exception);
911   if (property != (const char *) NULL)
912     parameters.cp_comment=ConstantString(property);
913   channels=3;
914   jp2_colorspace=OPJ_CLRSPC_SRGB;
915   if (image->colorspace == YUVColorspace)
916     {
917       jp2_colorspace=OPJ_CLRSPC_SYCC;
918       parameters.subsampling_dx=2;
919     }
920   else
921     {
922       (void) TransformImageColorspace(image,sRGBColorspace,exception);
923       if (IsGrayColorspace(image->colorspace) != MagickFalse)
924         {
925           channels=1;
926           jp2_colorspace=OPJ_CLRSPC_GRAY;
927         }
928       if (image->alpha_trait == BlendPixelTrait)
929         channels++;
930     }
931   parameters.tcp_mct=channels == 3 ? 1 : 0;
932   ResetMagickMemory(jp2_info,0,sizeof(jp2_info));
933   for (i=0; i < (ssize_t) channels; i++)
934   {
935     jp2_info[i].prec=image->depth;
936     jp2_info[i].bpp=image->depth;
937     if ((image->depth == 1) &&
938         ((LocaleCompare(image_info->magick,"JPT") == 0) ||
939          (LocaleCompare(image_info->magick,"JP2") == 0)))
940       {
941         jp2_info[i].prec++;  /* OpenJPEG returns exception for depth @ 1 */
942         jp2_info[i].bpp++;
943       }
944     jp2_info[i].sgnd=0;
945     jp2_info[i].dx=parameters.subsampling_dx;
946     jp2_info[i].dy=parameters.subsampling_dy;
947     jp2_info[i].w=image->columns;
948     jp2_info[i].h=image->rows;
949   }
950   jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace);
951   if (jp2_image == (opj_image_t *) NULL)
952     ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
953   jp2_image->x0=parameters.image_offset_x0;
954   jp2_image->y0=parameters.image_offset_y0;
955   jp2_image->x1=2*parameters.image_offset_x0+(image->columns-1)*
956     parameters.subsampling_dx+1;
957   jp2_image->y1=2*parameters.image_offset_y0+(image->rows-1)*
958     parameters.subsampling_dx+1;
959   if ((image->depth == 12) &&
960       ((image->columns == 2048) || (image->rows == 1080) ||
961        (image->columns == 4096) || (image->rows == 2160)))
962     CinemaProfileCompliance(jp2_image,&parameters);
963   /*
964     Convert to JP2 pixels.
965   */
966   for (y=0; y < (ssize_t) image->rows; y++)
967   {
968     register const Quantum
969       *p;
970
971     ssize_t
972       x;
973
974     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
975     if (p == (const Quantum *) NULL)
976       break;
977     for (x=0; x < (ssize_t) image->columns; x++)
978     {
979       for (i=0; i < (ssize_t) channels; i++)
980       {
981         double
982           scale;
983
984         register int
985           *q;
986
987         scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange;
988         q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy*
989           image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx);
990         switch (i)
991         {
992           case 0:
993           {
994             if (jp2_colorspace == OPJ_CLRSPC_GRAY)
995               {
996                 *q=(int) (scale*GetPixelLuma(image,p));
997                 break;
998               }
999             *q=(int) (scale*GetPixelRed(image,p));
1000             break;
1001           }
1002           case 1:
1003           {
1004             if (jp2_colorspace == OPJ_CLRSPC_GRAY)
1005               {
1006                 *q=(int) (scale*GetPixelAlpha(image,p));
1007                 break;
1008               }
1009             *q=(int) (scale*GetPixelGreen(image,p));
1010             break;
1011           }
1012           case 2:
1013           {
1014             *q=(int) (scale*GetPixelBlue(image,p));
1015             break;
1016           }
1017           case 3:
1018           {
1019             *q=(int) (scale*GetPixelAlpha(image,p));
1020             break;
1021           }
1022         }
1023       }
1024       p+=GetPixelChannels(image);
1025     }
1026     status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1027       image->rows);
1028     if (status == MagickFalse)
1029       break;
1030   }
1031   if (LocaleCompare(image_info->magick,"JPT") == 0)
1032     jp2_codec=opj_create_compress(OPJ_CODEC_JPT);
1033   else
1034     if (LocaleCompare(image_info->magick,"J2K") == 0)
1035       jp2_codec=opj_create_compress(OPJ_CODEC_J2K);
1036     else
1037       jp2_codec=opj_create_compress(OPJ_CODEC_JP2);
1038   opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
1039   opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
1040   opj_setup_encoder(jp2_codec,&parameters,jp2_image);
1041   jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE);
1042   opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
1043   opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
1044   opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
1045   opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
1046   opj_stream_set_user_data(jp2_stream,image,NULL);
1047   if (jp2_stream == (opj_stream_t *) NULL)
1048     ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
1049   jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream);
1050   if (jp2_status == 0)
1051     ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
1052   if ((opj_encode(jp2_codec,jp2_stream) == 0) ||
1053       (opj_end_compress(jp2_codec,jp2_stream) == 0))
1054     {
1055       opj_stream_destroy(jp2_stream);
1056       opj_destroy_codec(jp2_codec);
1057       opj_image_destroy(jp2_image);
1058       ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
1059     }
1060   /*
1061     Free resources.
1062   */
1063   opj_stream_destroy(jp2_stream);
1064   opj_destroy_codec(jp2_codec);
1065   opj_image_destroy(jp2_image);
1066   (void) CloseBlob(image);
1067   return(MagickTrue);
1068 }
1069 #endif