]> granicus.if.org Git - imagemagick/blob - coders/pcx.c
Make MagickMax()/MagickMin() a macro rather than an inline.
[imagemagick] / coders / pcx.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            PPPP    CCCC  X   X                              %
7 %                            P   P  C       X X                               %
8 %                            PPPP   C        X                                %
9 %                            P      C       X X                               %
10 %                            P       CCCC  X   X                              %
11 %                                                                             %
12 %                                                                             %
13 %                Read/Write ZSoft IBM PC Paintbrush Image Format              %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                   Cristy                                    %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2015 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/attribute.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/blob-private.h"
46 #include "MagickCore/cache.h"
47 #include "MagickCore/color.h"
48 #include "MagickCore/color-private.h"
49 #include "MagickCore/colormap.h"
50 #include "MagickCore/colorspace.h"
51 #include "MagickCore/colorspace-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/pixel-accessor.h"
62 #include "MagickCore/quantum-private.h"
63 #include "MagickCore/static.h"
64 #include "MagickCore/string_.h"
65 #include "MagickCore/module.h"
66 \f
67 /*
68   Typedef declarations.
69 */
70 typedef struct _PCXInfo
71 {
72   unsigned char
73     identifier,
74     version,
75     encoding,
76     bits_per_pixel;
77
78   unsigned short
79     left,
80     top,
81     right,
82     bottom,
83     horizontal_resolution,
84     vertical_resolution;
85
86   unsigned char
87     reserved,
88     planes;
89
90   unsigned short
91     bytes_per_line,
92     palette_info;
93
94   unsigned char
95     colormap_signature;
96 } PCXInfo;
97 \f
98 /*
99   Forward declarations.
100 */
101 static MagickBooleanType
102   WritePCXImage(const ImageInfo *,Image *,ExceptionInfo *);
103 \f
104 /*
105 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
106 %                                                                             %
107 %                                                                             %
108 %                                                                             %
109 %   I s D C X                                                                 %
110 %                                                                             %
111 %                                                                             %
112 %                                                                             %
113 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
114 %
115 %  IsDCX() returns MagickTrue if the image format type, identified by the
116 %  magick string, is DCX.
117 %
118 %  The format of the IsDCX method is:
119 %
120 %      MagickBooleanType IsDCX(const unsigned char *magick,const size_t length)
121 %
122 %  A description of each parameter follows:
123 %
124 %    o magick: compare image format pattern against these bytes.
125 %
126 %    o length: Specifies the length of the magick string.
127 %
128 */
129 static MagickBooleanType IsDCX(const unsigned char *magick,const size_t length)
130 {
131   if (length < 4)
132     return(MagickFalse);
133   if (memcmp(magick,"\261\150\336\72",4) == 0)
134     return(MagickTrue);
135   return(MagickFalse);
136 }
137 \f
138 /*
139 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
140 %                                                                             %
141 %                                                                             %
142 %                                                                             %
143 %   I s P C X                                                                 %
144 %                                                                             %
145 %                                                                             %
146 %                                                                             %
147 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
148 %
149 %  IsPCX() returns MagickTrue if the image format type, identified by the
150 %  magick string, is PCX.
151 %
152 %  The format of the IsPCX method is:
153 %
154 %      MagickBooleanType IsPCX(const unsigned char *magick,const size_t length)
155 %
156 %  A description of each parameter follows:
157 %
158 %    o magick: compare image format pattern against these bytes.
159 %
160 %    o length: Specifies the length of the magick string.
161 %
162 */
163 static MagickBooleanType IsPCX(const unsigned char *magick,const size_t length)
164 {
165   if (length < 2)
166     return(MagickFalse);
167   if (memcmp(magick,"\012\002",2) == 0)
168     return(MagickTrue);
169   if (memcmp(magick,"\012\005",2) == 0)
170     return(MagickTrue);
171   return(MagickFalse);
172 }
173 \f
174 /*
175 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
176 %                                                                             %
177 %                                                                             %
178 %                                                                             %
179 %   R e a d P C X I m a g e                                                   %
180 %                                                                             %
181 %                                                                             %
182 %                                                                             %
183 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
184 %
185 %  ReadPCXImage() reads a ZSoft IBM PC Paintbrush file and returns it.
186 %  It allocates the memory necessary for the new Image structure and returns
187 %  a pointer to the new image.
188 %
189 %  The format of the ReadPCXImage method is:
190 %
191 %      Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception)
192 %
193 %  A description of each parameter follows:
194 %
195 %    o image_info: the image info.
196 %
197 %    o exception: return any errors or warnings in this structure.
198 %
199 */
200 static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception)
201 {
202 #define ThrowPCXException(severity,tag) \
203   { \
204     scanline=(unsigned char *) RelinquishMagickMemory(scanline); \
205     pixel_info=RelinquishVirtualMemory(pixel_info); \
206     ThrowReaderException(severity,tag); \
207   }
208
209   Image
210     *image;
211
212   int
213     bits,
214     id,
215     mask;
216
217   MagickBooleanType
218     status;
219
220   MagickOffsetType
221     offset,
222     *page_table;
223
224   MemoryInfo
225     *pixel_info;
226
227   PCXInfo
228     pcx_info;
229
230   register ssize_t
231     x;
232
233   register Quantum
234     *q;
235
236   register ssize_t
237     i;
238
239   register unsigned char
240     *p,
241     *r;
242
243   size_t
244     one,
245     pcx_packets;
246
247   ssize_t
248     count,
249     y;
250
251   unsigned char
252     packet,
253     pcx_colormap[768],
254     *pixels,
255     *scanline;
256
257   /*
258     Open image file.
259   */
260   assert(image_info != (const ImageInfo *) NULL);
261   assert(image_info->signature == MagickSignature);
262   if (image_info->debug != MagickFalse)
263     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
264       image_info->filename);
265   assert(exception != (ExceptionInfo *) NULL);
266   assert(exception->signature == MagickSignature);
267   image=AcquireImage(image_info,exception);
268   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
269   if (status == MagickFalse)
270     {
271       image=DestroyImageList(image);
272       return((Image *) NULL);
273     }
274   /*
275     Determine if this a PCX file.
276   */
277   page_table=(MagickOffsetType *) NULL;
278   if (LocaleCompare(image_info->magick,"DCX") == 0)
279     {
280       size_t
281         magic;
282
283       /*
284         Read the DCX page table.
285       */
286       magic=ReadBlobLSBLong(image);
287       if (magic != 987654321)
288         ThrowReaderException(CorruptImageError,"ImproperImageHeader");
289       page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL,
290         sizeof(*page_table));
291       if (page_table == (MagickOffsetType *) NULL)
292         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
293       for (id=0; id < 1024; id++)
294       {
295         page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image);
296         if (page_table[id] == 0)
297           break;
298       }
299     }
300   if (page_table != (MagickOffsetType *) NULL)
301     {
302       offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET);
303       if (offset < 0)
304         ThrowReaderException(CorruptImageError,"ImproperImageHeader");
305     }
306   count=ReadBlob(image,1,&pcx_info.identifier);
307   for (id=1; id < 1024; id++)
308   {
309     int
310       bits_per_pixel;
311
312     /*
313       Verify PCX identifier.
314     */
315     pcx_info.version=(unsigned char) ReadBlobByte(image);
316     if ((count == 0) || (pcx_info.identifier != 0x0a))
317       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
318     pcx_info.encoding=(unsigned char) ReadBlobByte(image);
319     bits_per_pixel=ReadBlobByte(image);
320     if (bits_per_pixel == -1)
321       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
322     pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel;
323     pcx_info.left=ReadBlobLSBShort(image);
324     pcx_info.top=ReadBlobLSBShort(image);
325     pcx_info.right=ReadBlobLSBShort(image);
326     pcx_info.bottom=ReadBlobLSBShort(image);
327     pcx_info.horizontal_resolution=ReadBlobLSBShort(image);
328     pcx_info.vertical_resolution=ReadBlobLSBShort(image);
329     /*
330       Read PCX raster colormap.
331     */
332     image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right-
333       pcx_info.left)+1UL;
334     image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom-
335       pcx_info.top)+1UL;
336     if ((image->columns == 0) || (image->rows == 0) ||
337         (pcx_info.bits_per_pixel == 0))
338       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
339     image->depth=pcx_info.bits_per_pixel <= 8 ? 8U : MAGICKCORE_QUANTUM_DEPTH;
340     image->units=PixelsPerInchResolution;
341     image->resolution.x=(double) pcx_info.horizontal_resolution;
342     image->resolution.y=(double) pcx_info.vertical_resolution;
343     image->colors=16;
344     count=ReadBlob(image,3*image->colors,pcx_colormap);
345     pcx_info.reserved=(unsigned char) ReadBlobByte(image);
346     pcx_info.planes=(unsigned char) ReadBlobByte(image);
347     if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64)
348       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
349     one=1;
350     if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1))
351       if ((pcx_info.version == 3) || (pcx_info.version == 5) ||
352           ((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
353         image->colors=(size_t) MagickMin(one << (1UL*
354           (pcx_info.bits_per_pixel*pcx_info.planes)),256UL);
355     if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
356       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
357     if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1))
358       image->storage_class=DirectClass;
359     p=pcx_colormap;
360     for (i=0; i < (ssize_t) image->colors; i++)
361     {
362       image->colormap[i].red=ScaleCharToQuantum(*p++);
363       image->colormap[i].green=ScaleCharToQuantum(*p++);
364       image->colormap[i].blue=ScaleCharToQuantum(*p++);
365     }
366     pcx_info.bytes_per_line=ReadBlobLSBShort(image);
367     pcx_info.palette_info=ReadBlobLSBShort(image);
368     for (i=0; i < 58; i++)
369       (void) ReadBlobByte(image);
370     if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
371       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
372         break;
373     status=SetImageExtent(image,image->columns,image->rows,exception);
374     if (status == MagickFalse)
375       return(DestroyImageList(image));
376     /*
377       Read image data.
378     */
379     pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line*pcx_info.planes;
380     if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) >
381         (pcx_packets*8U))
382       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
383     scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns,
384       pcx_info.bytes_per_line),MagickMax(8,pcx_info.planes)*sizeof(*scanline));
385     pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels));
386     if ((scanline == (unsigned char *) NULL) ||
387         (pixel_info == (MemoryInfo *) NULL))
388       {
389         if (scanline != (unsigned char *) NULL)
390           scanline=(unsigned char *) RelinquishMagickMemory(scanline);
391         if (pixel_info != (MemoryInfo *) NULL)
392           pixel_info=RelinquishVirtualMemory(pixel_info);
393         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
394       }
395     pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
396     /*
397       Uncompress image data.
398     */
399     p=pixels;
400     if (pcx_info.encoding == 0)
401       while (pcx_packets != 0)
402       {
403         packet=(unsigned char) ReadBlobByte(image);
404         if (EOFBlob(image) != MagickFalse)
405           ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
406         *p++=packet;
407         pcx_packets--;
408       }
409     else
410       while (pcx_packets != 0)
411       {
412         packet=(unsigned char) ReadBlobByte(image);
413         if (EOFBlob(image) != MagickFalse)
414           ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
415         if ((packet & 0xc0) != 0xc0)
416           {
417             *p++=packet;
418             pcx_packets--;
419             continue;
420           }
421         count=(ssize_t) (packet & 0x3f);
422         packet=(unsigned char) ReadBlobByte(image);
423         if (EOFBlob(image) != MagickFalse)
424           ThrowPCXException(CorruptImageError,"UnexpectedEndOfFile");
425         for ( ; count != 0; count--)
426         {
427           *p++=packet;
428           pcx_packets--;
429           if (pcx_packets == 0)
430             break;
431         }
432       }
433     if (image->storage_class == DirectClass)
434       image->alpha_trait=pcx_info.planes > 3 ? BlendPixelTrait :
435         UndefinedPixelTrait;
436     else
437       if ((pcx_info.version == 5) ||
438           ((pcx_info.bits_per_pixel*pcx_info.planes) == 1))
439         {
440           /*
441             Initialize image colormap.
442           */
443           if (image->colors > 256)
444             ThrowPCXException(CorruptImageError,"ColormapExceeds256Colors");
445           if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)
446             {
447               /*
448                 Monochrome colormap.
449               */
450               image->colormap[0].red=(Quantum) 0;
451               image->colormap[0].green=(Quantum) 0;
452               image->colormap[0].blue=(Quantum) 0;
453               image->colormap[1].red=QuantumRange;
454               image->colormap[1].green=QuantumRange;
455               image->colormap[1].blue=QuantumRange;
456             }
457           else
458             if (image->colors > 16)
459               {
460                 /*
461                   256 color images have their color map at the end of the file.
462                 */
463                 pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image);
464                 count=ReadBlob(image,3*image->colors,pcx_colormap);
465                 p=pcx_colormap;
466                 for (i=0; i < (ssize_t) image->colors; i++)
467                 {
468                   image->colormap[i].red=ScaleCharToQuantum(*p++);
469                   image->colormap[i].green=ScaleCharToQuantum(*p++);
470                   image->colormap[i].blue=ScaleCharToQuantum(*p++);
471                 }
472             }
473         }
474     /*
475       Convert PCX raster image to pixel packets.
476     */
477     for (y=0; y < (ssize_t) image->rows; y++)
478     {
479       p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes);
480       q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
481       if (q == (Quantum *) NULL)
482         break;
483       r=scanline;
484       if (image->storage_class == DirectClass)
485         for (i=0; i < pcx_info.planes; i++)
486         {
487           r=scanline+i;
488           for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
489           {
490             switch (i)
491             {
492               case 0:
493               {
494                 *r=(*p++);
495                 break;
496               }
497               case 1:
498               {
499                 *r=(*p++);
500                 break;
501               }
502               case 2:
503               {
504                 *r=(*p++);
505                 break;
506               }
507               case 3:
508               default:
509               {
510                 *r=(*p++);
511                 break;
512               }
513             }
514             r+=pcx_info.planes;
515           }
516         }
517       else
518         if (pcx_info.planes > 1)
519           {
520             for (x=0; x < (ssize_t) image->columns; x++)
521               *r++=0;
522             for (i=0; i < pcx_info.planes; i++)
523             {
524               r=scanline;
525               for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
526               {
527                  bits=(*p++);
528                  for (mask=0x80; mask != 0; mask>>=1)
529                  {
530                    if (bits & mask)
531                      *r|=1 << i;
532                    r++;
533                  }
534                }
535             }
536           }
537         else
538           switch (pcx_info.bits_per_pixel)
539           {
540             case 1:
541             {
542               register ssize_t
543                 bit;
544
545               for (x=0; x < ((ssize_t) image->columns-7); x+=8)
546               {
547                 for (bit=7; bit >= 0; bit--)
548                   *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
549                 p++;
550               }
551               if ((image->columns % 8) != 0)
552                 {
553                   for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--)
554                     *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00);
555                   p++;
556                 }
557               break;
558             }
559             case 2:
560             {
561               for (x=0; x < ((ssize_t) image->columns-3); x+=4)
562               {
563                 *r++=(*p >> 6) & 0x3;
564                 *r++=(*p >> 4) & 0x3;
565                 *r++=(*p >> 2) & 0x3;
566                 *r++=(*p) & 0x3;
567                 p++;
568               }
569               if ((image->columns % 4) != 0)
570                 {
571                   for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--)
572                     *r++=(unsigned char) ((*p >> (i*2)) & 0x03);
573                   p++;
574                 }
575               break;
576             }
577             case 4:
578             {
579               for (x=0; x < ((ssize_t) image->columns-1); x+=2)
580               {
581                 *r++=(*p >> 4) & 0xf;
582                 *r++=(*p) & 0xf;
583                 p++;
584               }
585               if ((image->columns % 2) != 0)
586                 *r++=(*p++ >> 4) & 0xf;
587               break;
588             }
589             case 8:
590             {
591               (void) CopyMagickMemory(r,p,image->columns);
592               break;
593             }
594             default:
595               break;
596           }
597       /*
598         Transfer image scanline.
599       */
600       r=scanline;
601       for (x=0; x < (ssize_t) image->columns; x++)
602       {
603         if (image->storage_class == PseudoClass)
604           SetPixelIndex(image,*r++,q);
605         else
606           {
607             SetPixelRed(image,ScaleCharToQuantum(*r++),q);
608             SetPixelGreen(image,ScaleCharToQuantum(*r++),q);
609             SetPixelBlue(image,ScaleCharToQuantum(*r++),q);
610             if (image->alpha_trait != UndefinedPixelTrait)
611               SetPixelAlpha(image,ScaleCharToQuantum(*r++),q);
612           }
613         q+=GetPixelChannels(image);
614       }
615       if (SyncAuthenticPixels(image,exception) == MagickFalse)
616         break;
617       if (image->previous == (Image *) NULL)
618         {
619           status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
620             image->rows);
621           if (status == MagickFalse)
622             break;
623         }
624     }
625     if (image->storage_class == PseudoClass)
626       (void) SyncImage(image,exception);
627     scanline=(unsigned char *) RelinquishMagickMemory(scanline);
628     pixel_info=RelinquishVirtualMemory(pixel_info);
629     if (EOFBlob(image) != MagickFalse)
630       {
631         ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
632           image->filename);
633         break;
634       }
635     /*
636       Proceed to next image.
637     */
638     if (image_info->number_scenes != 0)
639       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
640         break;
641     if (page_table == (MagickOffsetType *) NULL)
642       break;
643     if (page_table[id] == 0)
644       break;
645     offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET);
646     if (offset < 0)
647       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
648     count=ReadBlob(image,1,&pcx_info.identifier);
649     if ((count != 0) && (pcx_info.identifier == 0x0a))
650       {
651         /*
652           Allocate next image structure.
653         */
654         AcquireNextImage(image_info,image,exception);
655         if (GetNextImageInList(image) == (Image *) NULL)
656           {
657             image=DestroyImageList(image);
658             return((Image *) NULL);
659           }
660         image=SyncNextImageInList(image);
661         status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
662           GetBlobSize(image));
663         if (status == MagickFalse)
664           break;
665       }
666   }
667   if (page_table != (MagickOffsetType *) NULL)
668     page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table);
669   (void) CloseBlob(image);
670   return(GetFirstImageInList(image));
671 }
672 \f
673 /*
674 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
675 %                                                                             %
676 %                                                                             %
677 %                                                                             %
678 %   R e g i s t e r P C X I m a g e                                           %
679 %                                                                             %
680 %                                                                             %
681 %                                                                             %
682 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
683 %
684 %  RegisterPCXImage() adds attributes for the PCX image format to
685 %  the list of supported formats.  The attributes include the image format
686 %  tag, a method to read and/or write the format, whether the format
687 %  supports the saving of more than one frame to the same file or blob,
688 %  whether the format supports native in-memory I/O, and a brief
689 %  description of the format.
690 %
691 %  The format of the RegisterPCXImage method is:
692 %
693 %      size_t RegisterPCXImage(void)
694 %
695 */
696 ModuleExport size_t RegisterPCXImage(void)
697 {
698   MagickInfo
699     *entry;
700
701   entry=SetMagickInfo("DCX");
702   entry->decoder=(DecodeImageHandler *) ReadPCXImage;
703   entry->encoder=(EncodeImageHandler *) WritePCXImage;
704   entry->seekable_stream=MagickTrue;
705   entry->magick=(IsImageFormatHandler *) IsDCX;
706   entry->description=ConstantString("ZSoft IBM PC multi-page Paintbrush");
707   entry->module=ConstantString("PCX");
708   (void) RegisterMagickInfo(entry);
709   entry=SetMagickInfo("PCX");
710   entry->decoder=(DecodeImageHandler *) ReadPCXImage;
711   entry->encoder=(EncodeImageHandler *) WritePCXImage;
712   entry->magick=(IsImageFormatHandler *) IsPCX;
713   entry->adjoin=MagickFalse;
714   entry->seekable_stream=MagickTrue;
715   entry->description=ConstantString("ZSoft IBM PC Paintbrush");
716   entry->module=ConstantString("PCX");
717   (void) RegisterMagickInfo(entry);
718   return(MagickImageCoderSignature);
719 }
720 \f
721 /*
722 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
723 %                                                                             %
724 %                                                                             %
725 %                                                                             %
726 %   U n r e g i s t e r P C X I m a g e                                       %
727 %                                                                             %
728 %                                                                             %
729 %                                                                             %
730 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
731 %
732 %  UnregisterPCXImage() removes format registrations made by the
733 %  PCX module from the list of supported formats.
734 %
735 %  The format of the UnregisterPCXImage method is:
736 %
737 %      UnregisterPCXImage(void)
738 %
739 */
740 ModuleExport void UnregisterPCXImage(void)
741 {
742   (void) UnregisterMagickInfo("DCX");
743   (void) UnregisterMagickInfo("PCX");
744 }
745 \f
746 /*
747 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
748 %                                                                             %
749 %                                                                             %
750 %                                                                             %
751 %   W r i t e P C X I m a g e                                                 %
752 %                                                                             %
753 %                                                                             %
754 %                                                                             %
755 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
756 %
757 %  WritePCXImage() writes an image in the ZSoft IBM PC Paintbrush file
758 %  format.
759 %
760 %  The format of the WritePCXImage method is:
761 %
762 %      MagickBooleanType WritePCXImage(const ImageInfo *image_info,
763 %        Image *image,ExceptionInfo *exception)
764 %
765 %  A description of each parameter follows.
766 %
767 %    o image_info: the image info.
768 %
769 %    o image:  The image.
770 %
771 %    o exception: return any errors or warnings in this structure.
772 %
773 */
774
775 static MagickBooleanType PCXWritePixels(PCXInfo *pcx_info,
776   const unsigned char *pixels,Image *image)
777 {
778   register const unsigned char
779     *q;
780
781   register ssize_t
782     i,
783     x;
784
785   ssize_t
786     count;
787
788   unsigned char
789     packet,
790     previous;
791
792   q=pixels;
793   for (i=0; i < (ssize_t) pcx_info->planes; i++)
794   {
795     if (pcx_info->encoding == 0)
796       {
797         for (x=0; x < (ssize_t) pcx_info->bytes_per_line; x++)
798           (void) WriteBlobByte(image,(unsigned char) (*q++));
799       }
800     else
801       {
802         previous=(*q++);
803         count=1;
804         for (x=0; x < (ssize_t) (pcx_info->bytes_per_line-1); x++)
805         {
806           packet=(*q++);
807           if ((packet == previous) && (count < 63))
808             {
809               count++;
810               continue;
811             }
812           if ((count > 1) || ((previous & 0xc0) == 0xc0))
813             {
814               count|=0xc0;
815               (void) WriteBlobByte(image,(unsigned char) count);
816             }
817           (void) WriteBlobByte(image,previous);
818           previous=packet;
819           count=1;
820         }
821         if ((count > 1) || ((previous & 0xc0) == 0xc0))
822           {
823             count|=0xc0;
824             (void) WriteBlobByte(image,(unsigned char) count);
825           }
826         (void) WriteBlobByte(image,previous);
827       }
828   }
829   return (MagickTrue);
830 }
831
832 static MagickBooleanType WritePCXImage(const ImageInfo *image_info,Image *image,
833   ExceptionInfo *exception)
834 {
835   MagickBooleanType
836     status;
837
838   MagickOffsetType
839     offset,
840     *page_table,
841     scene;
842
843   MemoryInfo
844     *pixel_info;
845
846   PCXInfo
847     pcx_info;
848
849   register const Quantum
850     *p;
851
852   register ssize_t
853     i,
854     x;
855
856   register unsigned char
857     *q;
858
859   size_t
860     length;
861
862   ssize_t
863     y;
864
865   unsigned char
866     *pcx_colormap,
867     *pixels;
868
869   /*
870     Open output image file.
871   */
872   assert(image_info != (const ImageInfo *) NULL);
873   assert(image_info->signature == MagickSignature);
874   assert(image != (Image *) NULL);
875   assert(image->signature == MagickSignature);
876   if (image->debug != MagickFalse)
877     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
878   assert(exception != (ExceptionInfo *) NULL);
879   assert(exception->signature == MagickSignature);
880   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
881   if (status == MagickFalse)
882     return(status);
883   (void) TransformImageColorspace(image,sRGBColorspace,exception);
884   page_table=(MagickOffsetType *) NULL;
885   if ((LocaleCompare(image_info->magick,"DCX") == 0) ||
886       ((GetNextImageInList(image) != (Image *) NULL) &&
887        (image_info->adjoin != MagickFalse)))
888     {
889       /*
890         Write the DCX page table.
891       */
892       (void) WriteBlobLSBLong(image,0x3ADE68B1L);
893       page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL,
894         sizeof(*page_table));
895       if (page_table == (MagickOffsetType *) NULL)
896         ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
897       for (scene=0; scene < 1024; scene++)
898         (void) WriteBlobLSBLong(image,0x00000000L);
899     }
900   scene=0;
901   do
902   {
903     if (page_table != (MagickOffsetType *) NULL)
904       page_table[scene]=TellBlob(image);
905     /*
906       Initialize PCX raster file header.
907     */
908     pcx_info.identifier=0x0a;
909     pcx_info.version=5;
910     pcx_info.encoding=image_info->compression == NoCompression ? 0 : 1;
911     pcx_info.bits_per_pixel=8;
912     if ((image->storage_class == PseudoClass) &&
913         (IsImageMonochrome(image,exception) != MagickFalse))
914       pcx_info.bits_per_pixel=1;
915     pcx_info.left=0;
916     pcx_info.top=0;
917     pcx_info.right=(unsigned short) (image->columns-1);
918     pcx_info.bottom=(unsigned short) (image->rows-1);
919     switch (image->units)
920     {
921       case UndefinedResolution:
922       case PixelsPerInchResolution:
923       default:
924       {
925         pcx_info.horizontal_resolution=(unsigned short) image->resolution.x;
926         pcx_info.vertical_resolution=(unsigned short) image->resolution.y;
927         break;
928       }
929       case PixelsPerCentimeterResolution:
930       {
931         pcx_info.horizontal_resolution=(unsigned short)
932           (2.54*image->resolution.x+0.5);
933         pcx_info.vertical_resolution=(unsigned short)
934           (2.54*image->resolution.y+0.5);
935         break;
936       }
937     }
938     pcx_info.reserved=0;
939     pcx_info.planes=1;
940     if ((image->storage_class == DirectClass) || (image->colors > 256))
941       {
942         pcx_info.planes=3;
943         if (image->alpha_trait != UndefinedPixelTrait)
944           pcx_info.planes++;
945       }
946     pcx_info.bytes_per_line=(unsigned short) (((size_t) image->columns*
947       pcx_info.bits_per_pixel+7)/8);
948     pcx_info.palette_info=1;
949     pcx_info.colormap_signature=0x0c;
950     /*
951       Write PCX header.
952     */
953     (void) WriteBlobByte(image,pcx_info.identifier);
954     (void) WriteBlobByte(image,pcx_info.version);
955     (void) WriteBlobByte(image,pcx_info.encoding);
956     (void) WriteBlobByte(image,pcx_info.bits_per_pixel);
957     (void) WriteBlobLSBShort(image,pcx_info.left);
958     (void) WriteBlobLSBShort(image,pcx_info.top);
959     (void) WriteBlobLSBShort(image,pcx_info.right);
960     (void) WriteBlobLSBShort(image,pcx_info.bottom);
961     (void) WriteBlobLSBShort(image,pcx_info.horizontal_resolution);
962     (void) WriteBlobLSBShort(image,pcx_info.vertical_resolution);
963     /*
964       Dump colormap to file.
965     */
966     pcx_colormap=(unsigned char *) AcquireQuantumMemory(256UL,
967       3*sizeof(*pcx_colormap));
968     if (pcx_colormap == (unsigned char *) NULL)
969       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
970     (void) memset(pcx_colormap,0,3*256*sizeof(*pcx_colormap));
971     q=pcx_colormap;
972     if ((image->storage_class == PseudoClass) && (image->colors <= 256))
973       for (i=0; i < (ssize_t) image->colors; i++)
974       {
975         *q++=ScaleQuantumToChar(image->colormap[i].red);
976         *q++=ScaleQuantumToChar(image->colormap[i].green);
977         *q++=ScaleQuantumToChar(image->colormap[i].blue);
978       }
979     (void) WriteBlob(image,3*16,(const unsigned char *) pcx_colormap);
980     (void) WriteBlobByte(image,pcx_info.reserved);
981     (void) WriteBlobByte(image,pcx_info.planes);
982     (void) WriteBlobLSBShort(image,pcx_info.bytes_per_line);
983     (void) WriteBlobLSBShort(image,pcx_info.palette_info);
984     for (i=0; i < 58; i++)
985       (void) WriteBlobByte(image,'\0');
986     length=(size_t) pcx_info.bytes_per_line;
987     pixel_info=AcquireVirtualMemory(length,pcx_info.planes*sizeof(*pixels));
988     if (pixel_info == (MemoryInfo *) NULL)
989       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
990     pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
991     q=pixels;
992     if ((image->storage_class == DirectClass) || (image->colors > 256))
993       {
994         /*
995           Convert DirectClass image to PCX raster pixels.
996         */
997         for (y=0; y < (ssize_t) image->rows; y++)
998         {
999           q=pixels;
1000           for (i=0; i < pcx_info.planes; i++)
1001           {
1002             p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1003             if (p == (const Quantum *) NULL)
1004               break;
1005             switch ((int) i)
1006             {
1007               case 0:
1008               {
1009                 for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
1010                 {
1011                   *q++=ScaleQuantumToChar(GetPixelRed(image,p));
1012                   p+=GetPixelChannels(image);
1013                 }
1014                 break;
1015               }
1016               case 1:
1017               {
1018                 for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
1019                 {
1020                   *q++=ScaleQuantumToChar(GetPixelGreen(image,p));
1021                   p+=GetPixelChannels(image);
1022                 }
1023                 break;
1024               }
1025               case 2:
1026               {
1027                 for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++)
1028                 {
1029                   *q++=ScaleQuantumToChar(GetPixelBlue(image,p));
1030                   p+=GetPixelChannels(image);
1031                 }
1032                 break;
1033               }
1034               case 3:
1035               default:
1036               {
1037                 for (x=(ssize_t) pcx_info.bytes_per_line; x != 0; x--)
1038                 {
1039                   *q++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p)));
1040                   p+=GetPixelChannels(image);
1041                 }
1042                 break;
1043               }
1044             }
1045           }
1046           if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
1047             break;
1048           if (image->previous == (Image *) NULL)
1049             {
1050               status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1051                 image->rows);
1052               if (status == MagickFalse)
1053                 break;
1054             }
1055         }
1056       }
1057     else
1058       {
1059         if (pcx_info.bits_per_pixel > 1)
1060           for (y=0; y < (ssize_t) image->rows; y++)
1061           {
1062             p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1063             if (p == (const Quantum *) NULL)
1064               break;
1065             q=pixels;
1066             for (x=0; x < (ssize_t) image->columns; x++)
1067             {
1068               *q++=(unsigned char) GetPixelIndex(image,p);
1069               p+=GetPixelChannels(image);
1070             }
1071             if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
1072               break;
1073             if (image->previous == (Image *) NULL)
1074               {
1075                 status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
1076                 image->rows);
1077                 if (status == MagickFalse)
1078                   break;
1079               }
1080           }
1081         else
1082           {
1083             register unsigned char
1084               bit,
1085               byte;
1086
1087             /*
1088               Convert PseudoClass image to a PCX monochrome image.
1089             */
1090             for (y=0; y < (ssize_t) image->rows; y++)
1091             {
1092               p=GetVirtualPixels(image,0,y,image->columns,1,exception);
1093               if (p == (const Quantum *) NULL)
1094                 break;
1095               bit=0;
1096               byte=0;
1097               q=pixels;
1098               for (x=0; x < (ssize_t) image->columns; x++)
1099               {
1100                 byte<<=1;
1101                 if (GetPixelLuma(image,p) >= (QuantumRange/2.0))
1102                   byte|=0x01;
1103                 bit++;
1104                 if (bit == 8)
1105                   {
1106                     *q++=byte;
1107                     bit=0;
1108                     byte=0;
1109                   }
1110                 p+=GetPixelChannels(image);
1111               }
1112               if (bit != 0)
1113                 *q++=byte << (8-bit);
1114               if (PCXWritePixels(&pcx_info,pixels,image) == MagickFalse)
1115                 break;
1116               if (image->previous == (Image *) NULL)
1117                 {
1118                   status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
1119                     y,image->rows);
1120                   if (status == MagickFalse)
1121                     break;
1122                 }
1123             }
1124           }
1125         (void) WriteBlobByte(image,pcx_info.colormap_signature);
1126         (void) WriteBlob(image,3*256,pcx_colormap);
1127       }
1128     pixel_info=RelinquishVirtualMemory(pixel_info);
1129     pcx_colormap=(unsigned char *) RelinquishMagickMemory(pcx_colormap);
1130     if (page_table == (MagickOffsetType *) NULL)
1131       break;
1132     if (scene >= 1023)
1133       break;
1134     if (GetNextImageInList(image) == (Image *) NULL)
1135       break;
1136     image=SyncNextImageInList(image);
1137     status=SetImageProgress(image,SaveImagesTag,scene++,
1138       GetImageListLength(image));
1139     if (status == MagickFalse)
1140       break;
1141   } while (image_info->adjoin != MagickFalse);
1142   if (page_table != (MagickOffsetType *) NULL)
1143     {
1144       /*
1145         Write the DCX page table.
1146       */
1147       page_table[scene+1]=0;
1148       offset=SeekBlob(image,0L,SEEK_SET);
1149       if (offset < 0)
1150         ThrowWriterException(CorruptImageError,"ImproperImageHeader");
1151       (void) WriteBlobLSBLong(image,0x3ADE68B1L);
1152       for (i=0; i <= (ssize_t) scene; i++)
1153         (void) WriteBlobLSBLong(image,(unsigned int) page_table[i]);
1154       page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table);
1155     }
1156   if (status == MagickFalse)
1157     {
1158       char
1159         *message;
1160
1161       message=GetExceptionMessage(errno);
1162       (void) ThrowMagickException(exception,GetMagickModule(),FileOpenError,
1163         "UnableToWriteFile","`%s': %s",image->filename,message);
1164       message=DestroyString(message);
1165     }
1166   (void) CloseBlob(image);
1167   return(MagickTrue);
1168 }