]> 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/static.h"
67 #include "MagickCore/statistic.h"
68 #include "MagickCore/string_.h"
69 #include "MagickCore/string-private.h"
70 #include "MagickCore/module.h"
71 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
72 #include <openjpeg.h>
73 #endif
74 \f
75 /*
76   Forward declarations.
77 */
78 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
79 static MagickBooleanType
80   WriteJP2Image(const ImageInfo *,Image *,ExceptionInfo *);
81 #endif
82 \f
83 /*
84 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
85 %                                                                             %
86 %                                                                             %
87 %                                                                             %
88 %   I s J 2 K                                                                 %
89 %                                                                             %
90 %                                                                             %
91 %                                                                             %
92 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
93 %
94 %  IsJ2K() returns MagickTrue if the image format type, identified by the
95 %  magick string, is J2K.
96 %
97 %  The format of the IsJ2K method is:
98 %
99 %      MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
100 %
101 %  A description of each parameter follows:
102 %
103 %    o magick: compare image format pattern against these bytes.
104 %
105 %    o length: Specifies the length of the magick string.
106 %
107 */
108 static MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
109 {
110   if (length < 4)
111     return(MagickFalse);
112   if (memcmp(magick,"\xff\x4f\xff\x51",4) == 0)
113     return(MagickTrue);
114   return(MagickFalse);
115 }
116 \f
117 /*
118 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
119 %                                                                             %
120 %                                                                             %
121 %                                                                             %
122 %   I s J P 2                                                                 %
123 %                                                                             %
124 %                                                                             %
125 %                                                                             %
126 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
127 %
128 %  IsJP2() returns MagickTrue if the image format type, identified by the
129 %  magick string, is JP2.
130 %
131 %  The format of the IsJP2 method is:
132 %
133 %      MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
134 %
135 %  A description of each parameter follows:
136 %
137 %    o magick: compare image format pattern against these bytes.
138 %
139 %    o length: Specifies the length of the magick string.
140 %
141 */
142 static MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
143 {
144   if (length < 12)
145     return(MagickFalse);
146   if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0)
147     return(MagickTrue);
148   if (memcmp(magick,"\x0d\x0a\x87\x0a",12) == 0)
149     return(MagickTrue);
150   return(MagickFalse);
151 }
152 \f
153 /*
154 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
155 %                                                                             %
156 %                                                                             %
157 %                                                                             %
158 %   I s J P C                                                                 %
159 %                                                                             %
160 %                                                                             %
161 %                                                                             %
162 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
163 %
164 %  IsJPC()() returns MagickTrue if the image format type, identified by the
165 %  magick string, is JPC.
166 %
167 %  The format of the IsJPC method is:
168 %
169 %      MagickBooleanType IsJPC(const unsigned char *magick,const size_t length)
170 %
171 %  A description of each parameter follows:
172 %
173 %    o magick: compare image format pattern against these bytes.
174 %
175 %    o length: Specifies the length of the magick string.
176 %
177 */
178 static MagickBooleanType IsJPC(const unsigned char *magick,const size_t length)
179 {
180   if (length < 12)
181     return(MagickFalse);
182   if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0)
183     return(MagickTrue);
184   if (memcmp(magick,"\x0d\x0a\x87\x0a",12) == 0)
185     return(MagickTrue);
186   return(MagickFalse);
187 }
188 \f
189 /*
190 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
191 %                                                                             %
192 %                                                                             %
193 %                                                                             %
194 %   R e a d J P 2 I m a g e                                                   %
195 %                                                                             %
196 %                                                                             %
197 %                                                                             %
198 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
199 %
200 %  ReadJP2Image() reads a JPEG 2000 Image file (JP2) or JPEG 2000
201 %  codestream (JPC) image file and returns it.  It allocates the memory
202 %  necessary for the new Image structure and returns a pointer to the new
203 %  image or set of images.
204 %
205 %  JP2 support is originally written by Nathan Brown, nathanbrown@letu.edu.
206 %
207 %  The format of the ReadJP2Image method is:
208 %
209 %      Image *ReadJP2Image(const ImageInfo *image_info,
210 %        ExceptionInfo *exception)
211 %
212 %  A description of each parameter follows:
213 %
214 %    o image_info: the image info.
215 %
216 %    o exception: return any errors or warnings in this structure.
217 %
218 */
219 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
220 static void JP2ErrorHandler(const char *message,void *client_data)
221 {
222   ExceptionInfo
223     *exception;
224
225   exception=(ExceptionInfo *) client_data;
226   (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
227     message,"`%s'","OpenJP2");
228 }
229
230 static OPJ_SIZE_T JP2ReadHandler(void *buffer,OPJ_SIZE_T length,void *context)
231 {
232   Image
233     *image;
234
235   ssize_t
236     count;
237
238   image=(Image *) context;
239   count=ReadBlob(image,(ssize_t) length,(unsigned char *) buffer);
240   if (count == 0)
241     return(-1);
242   return((OPJ_SIZE_T) count);
243 }
244
245 static OPJ_BOOL JP2SeekHandler(OPJ_OFF_T offset,void *context)
246 {
247   Image
248     *image;
249
250   image=(Image *) context;
251   return(SeekBlob(image,offset,SEEK_SET) < 0 ? 0 : 1);
252 }
253
254 static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context)
255 {
256   Image
257     *image;
258
259   image=(Image *) context;
260   return(SeekBlob(image,offset,SEEK_CUR) < 0 ? 0 : offset);
261 }
262
263 static void JP2WarningHandler(const char *message,void *client_data)
264 {
265   ExceptionInfo
266     *exception;
267
268   exception=(ExceptionInfo *) client_data;
269   (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
270     message,"`%s'","OpenJP2");
271 }
272
273 static OPJ_SIZE_T JP2WriteHandler(void *buffer,OPJ_SIZE_T length,void *context)
274 {
275   Image
276     *image;
277
278   ssize_t
279     count;
280
281   image=(Image *) context;
282   count=WriteBlob(image,(ssize_t) length,(unsigned char *) buffer);
283   return((OPJ_SIZE_T) count);
284 }
285
286 static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
287 {
288   const char
289     *option;
290
291   Image
292     *image;
293
294   int
295     jp2_status;
296
297   MagickBooleanType
298     status;
299
300   opj_codec_t
301     *jp2_codec;
302
303   opj_codestream_index_t
304     *codestream_index = (opj_codestream_index_t *) NULL;
305
306   opj_dparameters_t
307     parameters;
308
309   opj_image_t
310     *jp2_image;
311
312   opj_stream_t
313     *jp2_stream;
314
315   register ssize_t
316     i;
317
318   ssize_t
319     y;
320
321   /*
322     Open image file.
323   */
324   assert(image_info != (const ImageInfo *) NULL);
325   assert(image_info->signature == MagickSignature);
326   if (image_info->debug != MagickFalse)
327     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
328       image_info->filename);
329   assert(exception != (ExceptionInfo *) NULL);
330   assert(exception->signature == MagickSignature);
331   image=AcquireImage(image_info,exception);
332   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
333   if (status == MagickFalse)
334     {
335       image=DestroyImageList(image);
336       return((Image *) NULL);
337     }
338   /*
339     Initialize JP2 codec.
340   */
341   if (LocaleCompare(image_info->magick,"JPT") == 0)
342     jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
343   else
344     if (LocaleCompare(image_info->magick,"J2K") == 0)
345       jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
346     else
347       jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
348   opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
349   opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
350   opj_set_default_decoder_parameters(&parameters);
351   option=GetImageOption(image_info,"jp2:reduce-factor");
352   if (option != (const char *) NULL)
353     parameters.cp_reduce=StringToInteger(option);
354   option=GetImageOption(image_info,"jp2:quality-layers");
355   if (option != (const char *) NULL)
356     parameters.cp_layer=StringToInteger(option);
357   if (opj_setup_decoder(jp2_codec,&parameters) == 0)
358     {
359       opj_destroy_codec(jp2_codec);
360       ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
361     }
362   jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,1);
363   opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
364   opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
365   opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
366   opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
367   opj_stream_set_user_data(jp2_stream,image);
368   opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
369   if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
370     {
371       opj_stream_set_user_data(jp2_stream,NULL);
372       opj_stream_destroy_v3(jp2_stream);
373       opj_destroy_codec(jp2_codec);
374       ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
375     }
376   if ((image->columns != 0) && (image->rows != 0))
377     {
378       /*
379         Extract an area from the image.
380       */
381       jp2_status=opj_set_decode_area(jp2_codec,jp2_image,image->extract_info.x,
382         image->extract_info.y,image->extract_info.x+image->columns,
383         image->extract_info.y+image->rows);
384       if (jp2_status == 0)
385         {
386           opj_stream_set_user_data(jp2_stream,NULL);
387           opj_stream_destroy_v3(jp2_stream);
388           opj_destroy_codec(jp2_codec);
389           opj_image_destroy(jp2_image);
390           ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
391         }
392     }
393   if ((opj_decode(jp2_codec,jp2_stream,jp2_image) == 0) ||
394       (opj_end_decompress(jp2_codec,jp2_stream) == 0))
395     {
396       opj_stream_set_user_data(jp2_stream,NULL);
397       opj_stream_destroy_v3(jp2_stream);
398       opj_destroy_codec(jp2_codec);
399       opj_image_destroy(jp2_image);
400       ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
401     }
402   opj_stream_set_user_data(jp2_stream,NULL);
403   opj_stream_destroy_v3(jp2_stream);
404   for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
405   {
406     if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0))
407       {
408         opj_stream_set_user_data(jp2_stream,NULL);
409         opj_destroy_codec(jp2_codec);
410         opj_image_destroy(jp2_image);
411         ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
412       }
413   }
414   /*
415     Convert JP2 image.
416   */
417   image->columns=(size_t) jp2_image->comps[0].w;
418   image->rows=(size_t) jp2_image->comps[0].h;
419   image->depth=jp2_image->comps[0].prec;
420   image->compression=JPEG2000Compression;
421   if (jp2_image->numcomps <= 2)
422     {
423       SetImageColorspace(image,GRAYColorspace,exception);
424       if (jp2_image->numcomps > 1)
425         image->alpha_trait=BlendPixelTrait;
426     }
427   if (jp2_image->numcomps > 3)
428     image->alpha_trait=BlendPixelTrait;
429   for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
430   {
431     if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0))
432       {
433         opj_stream_set_user_data(jp2_stream,NULL);
434         opj_destroy_codec(jp2_codec);
435         opj_image_destroy(jp2_image);
436         ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
437       }
438     if ((jp2_image->comps[i].dx > 1) || (jp2_image->comps[i].dy > 1))
439       image->colorspace=YUVColorspace;
440   }
441   if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
442     {
443       StringInfo
444         *profile;
445
446       profile=BlobToStringInfo(jp2_image->icc_profile_buf,
447         jp2_image->icc_profile_len);
448       if (profile != (StringInfo *) NULL)
449         SetImageProfile(image,"icc",profile,exception);
450     }
451   for (y=0; y < (ssize_t) image->rows; y++)
452   {
453     register Quantum
454       *restrict q;
455
456     register ssize_t
457       x;
458
459     q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
460     if (q == (Quantum *) NULL)
461       break;
462     for (x=0; x < (ssize_t) image->columns; x++)
463     {
464       register ssize_t
465         i;
466
467       for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
468       {
469         double
470           pixel,
471           scale;
472
473         scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
474         pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
475           image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
476           (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
477         switch (i)
478         {
479            case 0:
480            {
481              SetPixelRed(image,ClampToQuantum(pixel),q);
482              SetPixelGreen(image,ClampToQuantum(pixel),q);
483              SetPixelBlue(image,ClampToQuantum(pixel),q);
484              SetPixelAlpha(image,OpaqueAlpha,q);
485              break;
486            }
487            case 1:
488            {
489              if (jp2_image->numcomps == 2)
490                {
491                  SetPixelAlpha(image,ClampToQuantum(pixel),q);
492                  break;
493                }
494              SetPixelGreen(image,ClampToQuantum(pixel),q);
495              break;
496            }
497            case 2:
498            {
499              SetPixelBlue(image,ClampToQuantum(pixel),q);
500              break;
501            }
502            case 3:
503            {
504              SetPixelAlpha(image,ClampToQuantum(pixel),q);
505              break;
506            }
507         }
508       }
509       q+=GetPixelChannels(image);
510     }
511     if (SyncAuthenticPixels(image,exception) == MagickFalse)
512       break;
513     status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
514       image->rows);
515     if (status == MagickFalse)
516       break;
517   }
518   /*
519     Free resources.
520   */
521   opj_destroy_codec(jp2_codec);
522   opj_image_destroy(jp2_image);
523   opj_destroy_cstr_index(&codestream_index);
524   return(GetFirstImageInList(image));
525 }
526 #endif
527 \f
528 /*
529 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
530 %                                                                             %
531 %                                                                             %
532 %                                                                             %
533 %   R e g i s t e r J P 2 I m a g e                                           %
534 %                                                                             %
535 %                                                                             %
536 %                                                                             %
537 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
538 %
539 %  RegisterJP2Image() adds attributes for the JP2 image format to the list of
540 %  supported formats.  The attributes include the image format tag, a method
541 %  method to read and/or write the format, whether the format supports the
542 %  saving of more than one frame to the same file or blob, whether the format
543 %  supports native in-memory I/O, and a brief description of the format.
544 %
545 %  The format of the RegisterJP2Image method is:
546 %
547 %      size_t RegisterJP2Image(void)
548 %
549 */
550 ModuleExport size_t RegisterJP2Image(void)
551 {
552   char
553     version[MaxTextExtent];
554
555   MagickInfo
556     *entry;
557
558   *version='\0';
559 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
560   (void) FormatLocaleString(version,MaxTextExtent,"%s",opj_version());
561 #endif
562   entry=SetMagickInfo("JP2");
563   entry->description=ConstantString("JPEG-2000 File Format 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 *) IsJP2;
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("J2K");
578   entry->description=ConstantString("JPEG-2000 Code Stream 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 *) IsJ2K;
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 *) IsJPC;
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("JP2");
649   (void) UnregisterMagickInfo("J2K");
650 }
651 \f
652 #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
653 /*
654 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
655 %                                                                             %
656 %                                                                             %
657 %                                                                             %
658 %   W r i t e J P 2 I m a g e                                                 %
659 %                                                                             %
660 %                                                                             %
661 %                                                                             %
662 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
663 %
664 %  WriteJP2Image() writes an image in the JPEG 2000 image format.
665 %
666 %  JP2 support originally written by Nathan Brown, nathanbrown@letu.edu
667 %
668 %  The format of the WriteJP2Image method is:
669 %
670 %      MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image,
671 %        ExceptionInfo *exception)
672 %
673 %  A description of each parameter follows.
674 %
675 %    o image_info: the image info.
676 %
677 %    o image:  The image.
678 %
679 */
680 static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image,
681   ExceptionInfo *exception)
682 {
683   const char
684     *value;
685
686   int
687     jp2_status;
688
689   MagickBooleanType
690     status;
691
692   opj_codec_t
693     *jp2_codec;
694
695   OPJ_COLOR_SPACE
696     jp2_colorspace;
697
698   opj_cparameters_t
699     parameters;
700
701   opj_image_cmptparm_t
702     jp2_info[5];
703
704   opj_image_t
705     *jp2_image;
706
707   opj_stream_t
708     *jp2_stream;
709
710   register ssize_t
711     i;
712
713   ssize_t
714     y;
715
716   size_t
717     channels;
718
719   /*
720     Open image file.
721   */
722   assert(image_info != (const ImageInfo *) NULL);
723   assert(image_info->signature == MagickSignature);
724   assert(image != (Image *) NULL);
725   assert(image->signature == MagickSignature);
726   if (image->debug != MagickFalse)
727     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
728   assert(exception != (ExceptionInfo *) NULL);
729   assert(exception->signature == MagickSignature);
730   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
731   if (status == MagickFalse)
732     return(status);
733   /*
734     Initialize JPEG 2000 API.
735   */
736   opj_set_default_encoder_parameters(&parameters);
737   for (i=1; i < 6; i++)
738     if (((1UL << (i+2)) > image->columns) && ((1UL << (i+2)) > image->rows))
739       break;
740   parameters.numresolution=i;
741   parameters.tcp_numlayers=1;
742   parameters.tcp_distoratio[0]=(double) image->quality;
743   parameters.cp_fixed_quality=OPJ_TRUE;
744   if (image_info->extract != (char *) NULL)
745     {
746       RectangleInfo
747         geometry;
748
749       int
750         flags;
751
752       /*
753         Set tile size.
754       */
755       flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
756       parameters.cp_tdx=geometry.width;
757       parameters.cp_tdy=geometry.width;
758       if ((flags & HeightValue) != 0)
759         parameters.cp_tdy=geometry.height;
760       if ((flags & XValue) != 0)
761         parameters.cp_tx0=geometry.x;
762       if ((flags & YValue) != 0)
763         parameters.cp_ty0=geometry.y;
764       parameters.tile_size_on=OPJ_TRUE;
765     }
766   value=GetImageArtifact(image,"jp2:quality");
767   if (value != (const char *) NULL)
768     {
769       register const char
770         *p;
771
772       /*
773         Set quality PSNR.
774       */
775       p=value;
776       for (i=1; sscanf(p,"%f",&parameters.tcp_distoratio[i]) == 1; i++)
777       {
778         if (i > 100)
779           break;
780         while ((*p != '\0') && (*p != ','))
781           p++;
782         if (*p == '\0')
783           break;
784         p++;
785       }
786       parameters.tcp_numlayers=i;
787       parameters.cp_fixed_quality=OPJ_TRUE;
788     }
789   value=GetImageArtifact(image,"jp2:rate");
790   if (value != (const char *) NULL)
791     {
792       register const char
793         *p;
794
795       /*
796         Set compression rate.
797       */
798       p=value;
799       for (i=1; sscanf(p,"%f",&parameters.tcp_rates[i]) == 1; i++)
800       {
801         if (i > 100)
802           break;
803         while ((*p != '\0') && (*p != ','))
804           p++;
805         if (*p == '\0')
806           break;
807         p++;
808       }
809       parameters.tcp_numlayers=i;
810       parameters.cp_disto_alloc=OPJ_TRUE;
811     }
812 #if defined(BUGINOPENJPEG)
813   if ((image->depth == 12) &&
814       ((image->columns == 2048) || (image->rows == 1080) ||
815        (image->columns == 4096) || (image->rows == 2160)))
816     {
817       /*
818         Digital Cinema profile compliance.
819       */
820       if ((image->columns == 2048) || (image->rows == 1080))
821         {
822           /*
823             Digital Cinema 2K.
824           */
825           parameters.cp_cinema=OPJ_CINEMA2K_48;
826           parameters.cp_rsiz=OPJ_CINEMA2K;
827         }
828       if ((image->columns == 4096) || (image->rows == 2160))
829         {
830           /*
831             Digital Cinema 4K.
832           */
833           parameters.cp_cinema=OPJ_CINEMA4K_24;
834           parameters.cp_rsiz=OPJ_CINEMA4K;
835         }
836     }
837 #endif
838   value=GetImageProperty(image,"comment",exception);
839   if (value != (const char *) NULL)
840     parameters.cp_comment=ConstantString(value);
841   channels=3;
842   jp2_colorspace=OPJ_CLRSPC_SRGB;
843   if (image->colorspace == YUVColorspace)
844     {
845       jp2_colorspace=OPJ_CLRSPC_SYCC;
846       parameters.subsampling_dx=2;
847     }
848   else
849     {
850       if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
851         (void) TransformImageColorspace(image,sRGBColorspace,exception);
852       if (IsGrayColorspace(image->colorspace) != MagickFalse)
853         {
854           channels=1;
855           jp2_colorspace=OPJ_CLRSPC_GRAY;
856         }
857       if (image->alpha_trait == BlendPixelTrait)
858         channels++;
859     }
860   ResetMagickMemory(jp2_info,0,sizeof(jp2_info));
861   for (i=0; i < (ssize_t) channels; i++)
862   {
863     jp2_info[i].prec=image->depth;
864     jp2_info[i].bpp=image->depth;
865     if ((image->depth == 1) &&
866         ((LocaleCompare(image_info->magick,"JPT") == 0) ||
867          (LocaleCompare(image_info->magick,"JP2") == 0)))
868       {
869         jp2_info[i].prec++;  /* OpenJPEG returns exception for depth @ 1 */
870         jp2_info[i].bpp++;
871       }
872     jp2_info[i].sgnd=0;
873     jp2_info[i].dx=parameters.subsampling_dx;
874     jp2_info[i].dy=parameters.subsampling_dy;
875     jp2_info[i].w=image->columns;
876     jp2_info[i].h=image->rows;
877   }
878   jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace);
879   if (jp2_image == (opj_image_t *) NULL)
880     ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
881   jp2_image->x0=parameters.image_offset_x0;
882   jp2_image->y0=parameters.image_offset_y0;
883   jp2_image->x1=2*parameters.image_offset_x0+(image->columns-1)*
884     parameters.subsampling_dx+1;
885   jp2_image->y1=2*parameters.image_offset_y0+(image->rows-1)*
886     parameters.subsampling_dx+1;
887   /*
888     Convert to JP2 pixels.
889   */
890   for (y=0; y < (ssize_t) image->rows; y++)
891   {
892     register const Quantum
893       *p;
894
895     ssize_t
896       x;
897
898     p=GetVirtualPixels(image,0,y,image->columns,1,exception);
899     if (p == (const Quantum *) NULL)
900       break;
901     for (x=0; x < (ssize_t) image->columns; x++)
902     {
903       for (i=0; i < (ssize_t) channels; i++)
904       {
905         double
906           scale;
907
908         register int
909           *q;
910
911         scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange;
912         q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy*
913           image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx);
914         switch (i)
915         {
916           case 0:
917           {
918             if (jp2_colorspace == OPJ_CLRSPC_GRAY)
919               {
920                 *q=(int) (scale*GetPixelLuma(image,p));
921                 break;
922               }
923             *q=(int) (scale*GetPixelRed(image,p));
924             break;
925           }
926           case 1:
927           {
928             if (jp2_colorspace == OPJ_CLRSPC_GRAY)
929               {
930                 *q=(int) (scale*GetPixelAlpha(image,p));
931                 break;
932               }
933             *q=(int) (scale*GetPixelGreen(image,p));
934             break;
935           }
936           case 2:
937           {
938             *q=(int) (scale*GetPixelBlue(image,p));
939             break;
940           }
941           case 3:
942           {
943             *q=(int) (scale*GetPixelAlpha(image,p));
944             break;
945           }
946         }
947       }
948       p++;
949     }
950     status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
951       image->rows);
952     if (status == MagickFalse)
953       break;
954   }
955   if (LocaleCompare(image_info->magick,"JPT") == 0)
956     jp2_codec=opj_create_compress(OPJ_CODEC_JPT);
957   else
958     if (LocaleCompare(image_info->magick,"J2K") == 0)
959       jp2_codec=opj_create_compress(OPJ_CODEC_J2K);
960     else
961       jp2_codec=opj_create_compress(OPJ_CODEC_JP2);
962   opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
963   opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
964   opj_setup_encoder(jp2_codec,&parameters,jp2_image);
965   jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE);
966   opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
967   opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
968   opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
969   opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
970   opj_stream_set_user_data(jp2_stream,image);
971   if (jp2_stream == (opj_stream_t *) NULL)
972     ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
973   jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream);
974   if (jp2_status == 0)
975     ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
976   if ((opj_encode(jp2_codec,jp2_stream) == 0) ||
977       (opj_end_compress(jp2_codec,jp2_stream) == 0))
978     {
979       opj_stream_set_user_data(jp2_stream,NULL);
980       opj_stream_destroy_v3(jp2_stream);
981       opj_destroy_codec(jp2_codec);
982       opj_image_destroy(jp2_image);
983       ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
984     }
985   /*
986     Free resources.
987   */
988   opj_stream_set_user_data(jp2_stream,NULL);
989   opj_stream_destroy_v3(jp2_stream);
990   opj_destroy_codec(jp2_codec);
991   opj_image_destroy(jp2_image);
992   (void) CloseBlob(image);
993   return(MagickTrue);
994 }
995 #endif