root / ImageMagick / trunk / coders / palm.c

Revision 12114, 36.0 kB (checked in by cristy, 30 hours ago)
Line 
1/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3%                                                                             %
4%                                                                             %
5%                                                                             %
6%                        PPPP    AAA   L      M   M                           %
7%                        P   P  A   A  L      MM MM                           %
8%                        PPPP   AAAAA  L      M M M                           %
9%                        P      A   A  L      M   M                           %
10%                        P      A   A  LLLLL  M   M                           %
11%                                                                             %
12%                                                                             %
13%                          Read/Write Palm Pixmap.                            %
14%                                                                             %
15%                                                                             %
16%                              Software Design                                %
17%                            Christopher R. Hawks                             %
18%                               December 2001                                 %
19%                                                                             %
20%  Copyright 1999-2004 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%  Based on pnmtopalm by Bill Janssen and ppmtobmp by Ian Goldberg.
38%
39*/
40
41/*
42  Include declarations.
43*/
44#include "magick/studio.h"
45#include "magick/blob.h"
46#include "magick/blob-private.h"
47#include "magick/color.h"
48#include "magick/color-private.h"
49#include "magick/colorspace.h"
50#include "magick/constitute.h"
51#include "magick/exception.h"
52#include "magick/image.h"
53#include "magick/list.h"
54#include "magick/magick.h"
55#include "magick/memory_.h"
56#include "magick/monitor.h"
57#include "magick/monitor-private.h"
58#include "magick/paint.h"
59#include "magick/pixel-private.h"
60#include "magick/property.h"
61#include "magick/quantize.h"
62#include "magick/quantum-private.h"
63#include "magick/static.h"
64#include "magick/string_.h"
65#include "magick/module.h"
66#include "magick/utility.h"
67
68/*
69  Define declarations.
70*/
71#define PALM_IS_COMPRESSED_FLAG  0x8000
72#define PALM_HAS_COLORMAP_FLAG  0x4000
73#define PALM_HAS_FOUR_BYTE_FIELD  0x0200
74#define PALM_HAS_TRANSPARENCY_FLAG  0x2000
75#define PALM_IS_INDIRECT  0x1000
76#define PALM_IS_FOR_SCREEN  0x0800
77#define PALM_IS_DIRECT_COLOR  0x0400
78#define PALM_COMPRESSION_SCANLINE  0x00
79#define PALM_COMPRESSION_RLE  0x01
80#define PALM_COMPRESSION_NONE  0xFF
81
82/*
83 The 256 color system palette for Palm Computing Devices.
84*/
85static unsigned char
86  PalmPalette[256][3] =
87  {
88    {255, 255,255}, {255, 204,255}, {255, 153,255}, {255, 102,255},
89    {255,  51,255}, {255,   0,255}, {255, 255,204}, {255, 204,204},
90    {255, 153,204}, {255, 102,204}, {255,  51,204}, {255,   0,204},
91    {255, 255,153}, {255, 204,153}, {255, 153,153}, {255, 102,153},
92    {255,  51,153}, {255,   0,153}, {204, 255,255}, {204, 204,255},
93    {204, 153,255}, {204, 102,255}, {204,  51,255}, {204,   0,255},
94    {204, 255,204}, {204, 204,204}, {204, 153,204}, {204, 102,204},
95    {204,  51,204}, {204,   0,204}, {204, 255,153}, {204, 204,153},
96    {204, 153,153}, {204, 102,153}, {204,  51,153}, {204,   0,153},
97    {153, 255,255}, {153, 204,255}, {153, 153,255}, {153, 102,255},
98    {153,  51,255}, {153,   0,255}, {153, 255,204}, {153, 204,204},
99    {153, 153,204}, {153, 102,204}, {153,  51,204}, {153,   0,204},
100    {153, 255,153}, {153, 204,153}, {153, 153,153}, {153, 102,153},
101    {153,  51,153}, {153,   0,153}, {102, 255,255}, {102, 204,255},
102    {102, 153,255}, {102, 102,255}, {102,  51,255}, {102,   0,255},
103    {102, 255,204}, {102, 204,204}, {102, 153,204}, {102, 102,204},
104    {102,  51,204}, {102,   0,204}, {102, 255,153}, {102, 204,153},
105    {102, 153,153}, {102, 102,153}, {102,  51,153}, {102,   0,153},
106    { 51, 255,255}, { 51, 204,255}, { 51, 153,255}, { 51, 102,255},
107    { 51,  51,255}, { 51,   0,255}, { 51, 255,204}, { 51, 204,204},
108    { 51, 153,204}, { 51, 102,204}, { 51,  51,204}, { 51,   0,204},
109    { 51, 255,153}, { 51, 204,153}, { 51, 153,153}, { 51, 102,153},
110    { 51,  51,153}, { 51,   0,153}, {  0, 255,255}, {  0, 204,255},
111    {  0, 153,255}, {  0, 102,255}, {  0,  51,255}, {  0,   0,255},
112    {  0, 255,204}, {  0, 204,204}, {  0, 153,204}, {  0, 102,204},
113    {  0,  51,204}, {  0,   0,204}, {  0, 255,153}, {  0, 204,153},
114    {  0, 153,153}, {  0, 102,153}, {  0,  51,153}, {  0,   0,153},
115    {255, 255,102}, {255, 204,102}, {255, 153,102}, {255, 102,102},
116    {255,  51,102}, {255,   0,102}, {255, 255, 51}, {255, 204, 51},
117    {255, 153, 51}, {255, 102, 51}, {255,  51, 51}, {255,   0, 51},
118    {255, 255,  0}, {255, 204,  0}, {255, 153,  0}, {255, 102,  0},
119    {255,  51,  0}, {255,   0,  0}, {204, 255,102}, {204, 204,102},
120    {204, 153,102}, {204, 102,102}, {204,  51,102}, {204,   0,102},
121    {204, 255, 51}, {204, 204, 51}, {204, 153, 51}, {204, 102, 51},
122    {204,  51, 51}, {204,   0, 51}, {204, 255,  0}, {204, 204,  0},
123    {204, 153,  0}, {204, 102,  0}, {204,  51,  0}, {204,   0,  0},
124    {153, 255,102}, {153, 204,102}, {153, 153,102}, {153, 102,102},
125    {153,  51,102}, {153,   0,102}, {153, 255, 51}, {153, 204, 51},
126    {153, 153, 51}, {153, 102, 51}, {153,  51, 51}, {153,   0, 51},
127    {153, 255,  0}, {153, 204,  0}, {153, 153,  0}, {153, 102,  0},
128    {153,  51,  0}, {153,   0,  0}, {102, 255,102}, {102, 204,102},
129    {102, 153,102}, {102, 102,102}, {102,  51,102}, {102,   0,102},
130    {102, 255, 51}, {102, 204, 51}, {102, 153, 51}, {102, 102, 51},
131    {102,  51, 51}, {102,   0, 51}, {102, 255,  0}, {102, 204,  0},
132    {102, 153,  0}, {102, 102,  0}, {102,  51,  0}, {102,   0,  0},
133    { 51, 255,102}, { 51, 204,102}, { 51, 153,102}, { 51, 102,102},
134    { 51,  51,102}, { 51,   0,102}, { 51, 255, 51}, { 51, 204, 51},
135    { 51, 153, 51}, { 51, 102, 51}, { 51,  51, 51}, { 51,   0, 51},
136    { 51, 255,  0}, { 51, 204,  0}, { 51, 153,  0}, { 51, 102,  0},
137    { 51,  51,  0}, { 51,   0,  0}, {  0, 255,102}, {  0, 204,102},
138    {  0, 153,102}, {  0, 102,102}, {  0,  51,102}, {  0,   0,102},
139    {  0, 255, 51}, {  0, 204, 51}, {  0, 153, 51}, {  0, 102, 51},
140    {  0,  51, 51}, {  0,   0, 51}, {  0, 255,  0}, {  0, 204,  0},
141    {  0, 153,  0}, {  0, 102,  0}, {  0,  51,  0}, { 17,  17, 17},
142    { 34,  34, 34}, { 68,  68, 68}, { 85,  85, 85}, {119, 119,119},
143    {136, 136,136}, {170, 170,170}, {187, 187,187}, {221, 221,221},
144    {238, 238,238}, {192, 192,192}, {128,   0,  0}, {128,   0,128},
145    {  0, 128,  0}, {  0, 128,128}, {  0,   0,  0}, {  0,   0,  0},
146    {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0},
147    {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0},
148    {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0},
149    {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0},
150    {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0},
151    {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0}, {  0,   0,  0}
152  };
153
154/*
155  Forward declarations.
156*/
157static MagickBooleanType
158  WritePALMImage(const ImageInfo *,Image *);
159
160/*
161%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
162%                                                                             %
163%                                                                             %
164%                                                                             %
165%   F i n d C o l o r                                                         %
166%                                                                             %
167%                                                                             %
168%                                                                             %
169%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
170%
171%  FindColor() returns the index of the matching entry from PalmPalette for a
172%  given PixelPacket.
173%
174%  The format of the FindColor method is:
175%
176%      int FindColor(PixelPacket *pixel)
177%
178%  A description of each parameter follows:
179%
180%    o int: the index of the matching color or -1 if not found/
181%
182%    o pixel: a pointer to the PixelPacket to be matched.
183%
184*/
185static int FindColor(PixelPacket *pixel)
186{
187  register long
188    i;
189
190  for (i=0; i < 256; i++)
191    if (ScaleQuantumToChar(pixel->red) == PalmPalette[i][0] &&
192        ScaleQuantumToChar(pixel->green) == PalmPalette[i][1] &&
193        ScaleQuantumToChar(pixel->blue) == PalmPalette[i][2])
194      return(i);
195  return(-1);
196}
197
198/*
199%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
200%                                                                             %
201%                                                                             %
202%                                                                             %
203%   R e a d P A L M I m a g e                                                 %
204%                                                                             %
205%                                                                             %
206%                                                                             %
207%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
208%
209%  ReadPALMImage() reads an image of raw bites in LSB order and returns it.  It
210%  allocates the memory necessary for the new Image structure and returns a
211%  pointer to the new image.
212%
213%  The format of the ReadPALMImage method is:
214%
215%      Image *ReadPALMImage(const ImageInfo *image_info,
216%        ExceptionInfo *exception)
217%
218%  A description of each parameter follows:
219%
220%    o image_info: Specifies a pointer to an ImageInfo structure.
221%
222%    o exception: return any errors or warnings in this structure.
223%
224*/
225
226static inline long MagickMax(const long x,const long y)
227{
228  if (x > y)
229    return(x);
230  return(y);
231}
232
233static inline ssize_t MagickMin(const ssize_t x,const ssize_t y)
234{
235  if (x < y)
236    return(x);
237  return(y);
238}
239
240static Image *ReadPALMImage(const ImageInfo *image_info,
241  ExceptionInfo *exception)
242{
243  Image
244    *image;
245
246  IndexPacket
247    index;
248
249  long
250    y;
251
252  MagickBooleanType
253    status;
254
255  MagickPixelPacket
256    transpix;
257
258  register IndexPacket
259    *indexes;
260
261  register long
262    i,
263    x;
264
265  register PixelPacket
266    *q;
267
268  ssize_t
269    count;
270
271  unsigned char
272    *lastrow,
273    *one_row,
274    *ptr;
275
276  unsigned long
277    bytes_per_row,
278    flags,
279    bits_per_pixel,
280    version,
281    nextDepthOffset,
282    transparentIndex,
283    compressionType,
284    byte,
285    mask,
286    redbits,
287    greenbits,
288    bluebits,
289    pad,
290    size,
291    bit;
292
293  unsigned short
294    color16;
295
296  MagickOffsetType
297    totalOffset,
298    seekNextDepth;
299
300  /*
301    Open image file.
302  */
303  assert(image_info != (const ImageInfo *) NULL);
304  assert(image_info->signature == MagickSignature);
305  if (image_info->debug != MagickFalse)
306    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
307      image_info->filename);
308  assert(exception != (ExceptionInfo *) NULL);
309  assert(exception->signature == MagickSignature);
310  image=AcquireImage(image_info);
311  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
312  if (status == MagickFalse)
313    {
314      (void) DestroyImageList(image);
315      return((Image *) NULL);
316    }
317  totalOffset=0;
318  do
319  {
320    image->columns=ReadBlobMSBShort(image);
321    image->rows=ReadBlobMSBShort(image);
322    if (EOFBlob(image) != MagickFalse)
323      ThrowReaderException(CorruptImageError,"ImproperImageHeader");
324    /*
325      Copied from coders/pnm.c. TODO other checks ...
326    */
327    if ((image->columns == 0) || (image->rows == 0))
328      ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
329    bytes_per_row=ReadBlobMSBShort(image);
330    flags=ReadBlobMSBShort(image);
331    bits_per_pixel=(unsigned long) ReadBlobByte(image);
332    if (bits_per_pixel > 16)
333      ThrowReaderException(CorruptImageError,"ImproperImageHeader");
334    version=(unsigned long) ReadBlobByte(image);
335    nextDepthOffset=(unsigned long) ReadBlobMSBShort(image);
336    transparentIndex=(unsigned long) ReadBlobByte(image);
337    compressionType=(unsigned long) ReadBlobByte(image);
338    pad=ReadBlobMSBShort(image);
339    /*
340      Initialize image colormap.
341    */
342    if ((bits_per_pixel < 16) &&
343        (AcquireImageColormap(image,1L << bits_per_pixel) == MagickFalse))
344      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
345    GetMagickPixelPacket(image,&transpix);
346    if (bits_per_pixel == 16)  /* Direct Color */
347      {
348        redbits=(unsigned long) ReadBlobByte(image);  /* # of bits of red */
349        greenbits=(unsigned long) ReadBlobByte(image);  /* # of bits of green */
350        bluebits=(unsigned long) ReadBlobByte(image);  /* # of bits of blue */
351        ReadBlobByte(image);  /* reserved by Palm */
352        ReadBlobByte(image);  /* reserved by Palm */
353        transpix.red=(MagickRealType) (QuantumRange*ReadBlobByte(image)/31);
354        transpix.green=(MagickRealType) (QuantumRange*ReadBlobByte(image)/63);
355        transpix.blue=(MagickRealType) (QuantumRange*ReadBlobByte(image)/31);
356      }
357    if (bits_per_pixel == 8)
358      {
359        IndexPacket
360          index;
361
362        if (flags & PALM_HAS_COLORMAP_FLAG)
363          {
364            count=(ssize_t) ReadBlobMSBShort(image);
365            for (i=0; i < (long) count; i++)
366            {
367              ReadBlobByte(image);
368              index=ConstrainColormapIndex(image,255-i);
369              image->colormap[(int) index].red=
370                ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
371              image->colormap[(int) index].green=
372                ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
373              image->colormap[(int) index].blue=
374                ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
375          }
376        }
377      else
378        {
379          for (i=0; i < (long) (1L << bits_per_pixel); i++)
380          {
381            index=ConstrainColormapIndex(image,255-i);
382            image->colormap[(int) index].red=
383              ScaleCharToQuantum(PalmPalette[i][0]);
384            image->colormap[(int) index].green=
385              ScaleCharToQuantum(PalmPalette[i][1]);
386            image->colormap[(int) index].blue=
387              ScaleCharToQuantum(PalmPalette[i][2]);
388          }
389        }
390      }
391    if (flags & PALM_IS_COMPRESSED_FLAG)
392      size=ReadBlobMSBShort(image);
393    image->storage_class=DirectClass;
394    if (bits_per_pixel < 16)
395      {
396        image->storage_class=PseudoClass;
397        image->depth=8;
398      }
399    if (SetImageExtent(image,0,0) == MagickFalse)
400      {
401        InheritException(exception,&image->exception);
402        return(DestroyImageList(image));
403      }
404    one_row=(unsigned char *) AcquireQuantumMemory(bytes_per_row,
405      sizeof(*one_row));
406    if (one_row == (unsigned char *) NULL)
407      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
408    lastrow=(unsigned char *) NULL;
409    if (compressionType == PALM_COMPRESSION_SCANLINE) {
410      lastrow=(unsigned char *) AcquireQuantumMemory(bytes_per_row,
411        sizeof(*lastrow));
412    if (lastrow == (unsigned char *) NULL)
413      ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
414    }
415    mask=(1l << bits_per_pixel)-1;
416    for (y = 0; y < (long) image->rows; y++)
417    {
418      if ((flags & PALM_IS_COMPRESSED_FLAG) == 0)
419        {
420          /* TODO move out of loop! */
421          image->compression=NoCompression;
422          count=ReadBlob(image,bytes_per_row,one_row);
423        }
424      else
425        {
426          if (compressionType == PALM_COMPRESSION_RLE)
427            {
428              /* TODO move out of loop! */
429              image->compression=RLECompression;
430              for (i=0; i < (long) bytes_per_row; )
431              {
432                count=(ssize_t) ReadBlobByte(image);
433                count=MagickMin(count,(ssize_t) bytes_per_row-i);
434                byte=(unsigned long) ReadBlobByte(image);
435                (void) ResetMagickMemory(one_row+i,(int) byte,(size_t) count);
436                i+=count;
437              }
438          }
439        else
440          if (compressionType == PALM_COMPRESSION_SCANLINE)
441            { 
442              /* TODO move out of loop! */
443              image->compression=FaxCompression;
444              for (i=0; i < (long) bytes_per_row; i+=8)
445              {
446                count=(ssize_t) ReadBlobByte(image);
447                byte=1UL*MagickMin((ssize_t) bytes_per_row-i,8);
448                for (bit=0; bit < byte; bit++)
449                {
450                  if ((y == 0) || (count & (1 << (7 - bit))))
451                    one_row[i+bit]=(unsigned char) ReadBlobByte(image);
452                  else
453                    one_row[i+bit]=lastrow[i+bit];
454                }
455              }
456              (void) CopyMagickMemory(lastrow, one_row, bytes_per_row);
457            }
458        }
459      ptr=one_row;
460      q=SetImagePixels(image,0,y,image->columns,1);
461      if (q == (PixelPacket *) NULL)
462        break;
463      indexes=GetIndexes(image);
464      if (bits_per_pixel == 16)
465        {
466          if (image->columns > (2*bytes_per_row))
467            ThrowReaderException(CorruptImageError,"CorruptImage");
468          for (x=0; x < (long) image->columns; x++)
469          {
470            color16=(*ptr++ << 8);
471            color16|=(*ptr++);
472            q->red=(Quantum) ((QuantumRange*((color16 >> 11) & 0x1f))/0x1f);
473            q->green=(Quantum) ((QuantumRange*((color16 >> 5) & 0x3f))/0x3f);
474            q->blue=(Quantum) ((QuantumRange*((color16 >> 0) & 0x1f))/0x1f);
475            q->opacity=OpaqueOpacity;
476            q++;
477          }
478        }
479      else
480        {
481          bit=8-bits_per_pixel;
482          for (x=0; x < (long) image->columns; x++)
483          {
484            if ((size_t) (ptr-one_row) >= bytes_per_row)
485              ThrowReaderException(CorruptImageError,"CorruptImage");
486            index=(IndexPacket) (mask-(((*ptr) & (mask << bit)) >> bit));
487            indexes[x]=index;
488            *q++=image->colormap[(long) index];
489            if (bit)
490              bit-=bits_per_pixel;
491            else
492              {
493                ptr++;
494                bit=8-bits_per_pixel;
495              }
496          }
497          if (SyncImagePixels(image) == MagickFalse)
498            break;
499        }
500        if (image->previous == (Image *) NULL)
501          {
502            status=SetImageProgress(image,LoadImageTag,y,image->rows);
503            if (status == MagickFalse)
504              break;
505          }
506      }
507    if (flags & PALM_HAS_TRANSPARENCY_FLAG)
508      {
509        if (bits_per_pixel != 16)
510          SetMagickPixelPacket(image,image->colormap+(mask-transparentIndex),
511            (const IndexPacket *) NULL,&transpix);
512        (void) TransparentPaintImage(image,&transpix,(Quantum)
513          TransparentOpacity,MagickFalse);
514      }
515    one_row=(unsigned char *) RelinquishMagickMemory(one_row);
516    if (compressionType == PALM_COMPRESSION_SCANLINE)
517    lastrow=(unsigned char *) RelinquishMagickMemory(lastrow);
518    /*
519      Proceed to next image. Copied from coders/pnm.c
520    */
521    if (image_info->number_scenes != 0)
522      if (image->scene >= (image_info->scene+image_info->number_scenes-1))
523        break;
524    if (nextDepthOffset != 0)
525      {
526        /*
527          Skip to next image.
528        */
529        totalOffset+=(MagickOffsetType) (nextDepthOffset*4);
530        if (totalOffset >= (MagickOffsetType) GetBlobSize(image))
531          {
532            ThrowReaderException(CorruptImageError,"ImproperImageHeader");
533          }
534        else
535          {
536            seekNextDepth=SeekBlob(image,totalOffset,SEEK_SET);
537          }
538        if (seekNextDepth != totalOffset)
539          ThrowReaderException(CorruptImageError,"ImproperImageHeader");
540        /*
541          Allocate next image structure. Copied from coders/pnm.c
542        */
543        AcquireNextImage(image_info,image);
544        if (GetNextImageInList(image) == (Image *) NULL)
545          {
546            (void) DestroyImageList(image);
547            return((Image *) NULL);
548          }
549        image=SyncNextImageInList(image);
550        status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
551          GetBlobSize(image));
552        if (status == MagickFalse)
553          break;
554      }
555  } while (nextDepthOffset != 0);
556  (void) CloseBlob(image);
557  return(GetFirstImageInList(image));
558}
559
560/*
561%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
562%                                                                             %
563%                                                                             %
564%                                                                             %
565%   R e g i s t e r P A L M I m a g e                                         %
566%                                                                             %
567%                                                                             %
568%                                                                             %
569%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
570%
571%  RegisterPALMImage() adds properties for the PALM image format to the list of
572%  supported formats.  The properties include the image format tag, a method to
573%  read and/or write the format, whether the format supports the saving of more
574%  than one frame to the same file or blob, whether the format supports native
575%  in-memory I/O, and a brief description of the format.
576%
577%  The format of the RegisterPALMImage method is:
578%
579%      unsigned long RegisterPALMImage(void)
580%
581*/
582ModuleExport unsigned long RegisterPALMImage(void)
583{
584  MagickInfo
585    *entry;
586
587  entry=SetMagickInfo("PALM");
588  entry->decoder=(DecodeImageHandler *) ReadPALMImage;
589  entry->encoder=(EncodeImageHandler *) WritePALMImage;
590  entry->seekable_stream=MagickTrue;
591  entry->description=ConstantString("Palm pixmap");
592  entry->module=ConstantString("PALM");
593  (void) RegisterMagickInfo(entry);
594  return(MagickImageCoderSignature);
595}
596
597/*
598%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
599%                                                                             %
600%                                                                             %
601%                                                                             %
602%   U n r e g i s t e r P A L M I m a g e                                     %
603%                                                                             %
604%                                                                             %
605%                                                                             %
606%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
607%
608%  UnregisterPALMImage() removes format registrations made by the PALM
609%  module from the list of supported formats.
610%
611%  The format of the UnregisterPALMImage method is:
612%
613%      UnregisterPALMImage(void)
614%
615*/
616ModuleExport void UnregisterPALMImage(void)
617{
618  (void) UnregisterMagickInfo("PALM");
619}
620
621/*
622%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
623%                                                                             %
624%                                                                             %
625%                                                                             %
626%   W r i t e P A L M I m a g e                                               %
627%                                                                             %
628%                                                                             %
629%                                                                             %
630%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
631%
632%  WritePALMImage() writes an image of raw bits in LSB order to a file.
633%
634%  The format of the WritePALMImage method is:
635%
636%      MagickBooleanType WritePALMImage(const ImageInfo *image_info,
637%        Image *image)
638%
639%  A description of each parameter follows.
640%
641%    o image_info: Specifies a pointer to an ImageInfo structure.
642%
643%    o image:  A pointer to a Image structure.
644%
645*/
646static MagickBooleanType WritePALMImage(const ImageInfo *image_info,
647  Image *image)
648{
649  int
650    y;
651
652  ExceptionInfo
653    exception;
654
655  MagickBooleanType
656    status;
657
658  MagickOffsetType
659    currentOffset,
660    offset,
661    scene;
662
663  MagickSizeType
664    cc;
665
666  PixelPacket
667    transpix;
668
669  QuantizeInfo
670    *quantize_info;
671
672  register IndexPacket
673    *indexes;
674
675  register long
676    x;
677
678  register PixelPacket
679    *p;
680
681  unsigned char
682    bit,
683    byte,
684    color,
685    *lastrow,
686    *one_row,
687    *ptr,
688    version;
689
690  unsigned int
691    transparentIndex;
692
693  unsigned long
694    count,
695    bits_per_pixel,
696    bytes_per_row,
697    nextDepthOffset;
698
699  unsigned short
700    color16,
701    flags;
702
703
704  /*
705    Open output image file.
706  */
707  assert(image_info != (const ImageInfo *) NULL);
708  assert(image_info->signature == MagickSignature);
709  assert(image != (Image *) NULL);
710  assert(image->signature == MagickSignature);
711  if (image->debug != MagickFalse)
712    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
713  status=OpenBlob(image_info,image,WriteBinaryBlobMode,&exception);
714  if (status == MagickFalse)
715    return(status);
716  GetExceptionInfo(&exception);
717  quantize_info=AcquireQuantizeInfo(image_info);
718  flags=0;
719  currentOffset=0;
720  transparentIndex=0;
721  transpix.red=0;
722  transpix.green=0;
723  transpix.blue=0;
724  transpix.opacity=0;
725  version=0;
726  scene=0;
727  do
728  {
729    if (image->colorspace != RGBColorspace)
730      (void) SetImageColorspace(image,RGBColorspace);
731    count=GetNumberColors(image,NULL,&exception);
732    for (bits_per_pixel=1;  (1UL << bits_per_pixel) < count;  bits_per_pixel*=2) ;
733    if (image_info->depth > 100)
734      bits_per_pixel=image_info->depth-100;
735    if (bits_per_pixel < 16)
736      (void) SetImageColorspace(image,image->colorspace);
737    if (bits_per_pixel < 8)
738      {
739        (void) SetImageColorspace(image,GRAYColorspace);
740        (void) SetImageType(image,PaletteType);
741        (void) SortColormapByIntensity(image);
742      }
743    if ((image->storage_class == PseudoClass) && (image->colors > 256))
744      (void) SetImageStorageClass(image,DirectClass);
745    if (image->storage_class == PseudoClass)
746      flags|=PALM_HAS_COLORMAP_FLAG;
747    else
748      flags|=PALM_IS_DIRECT_COLOR;
749    (void) WriteBlobMSBShort(image,(unsigned short) image->columns); /* width */
750    (void) WriteBlobMSBShort(image,(unsigned short) image->rows);  /* height */
751    bytes_per_row=((image->columns+(16/bits_per_pixel-1))/(16/
752      bits_per_pixel))*2;
753    (void) WriteBlobMSBShort(image,(unsigned short) bytes_per_row);
754    if ((image_info->compression == RLECompression) ||
755        (image_info->compression == FaxCompression))
756      flags|=PALM_IS_COMPRESSED_FLAG;
757    (void) WriteBlobMSBShort(image, flags);
758    (void) WriteBlobByte(image,(unsigned char) bits_per_pixel);
759    if (bits_per_pixel > 1)
760      version=1;
761    if ((image_info->compression == RLECompression) ||
762        (image_info->compression == FaxCompression))
763      version=2;
764    (void) WriteBlobByte(image,version);
765    (void) WriteBlobMSBShort(image,0);  /* nextDepthOffset */
766    (void) WriteBlobByte(image,(unsigned char) transparentIndex);
767    if (image_info->compression == RLECompression)
768      (void) WriteBlobByte(image,PALM_COMPRESSION_RLE);
769    else
770      if (image_info->compression == FaxCompression)
771        (void) WriteBlobByte(image,PALM_COMPRESSION_SCANLINE);
772      else
773        (void) WriteBlobByte(image,PALM_COMPRESSION_NONE);
774    (void) WriteBlobMSBShort(image,0);  /* reserved */
775    offset=16;
776    if (bits_per_pixel == 16)
777      {
778        (void) WriteBlobByte(image,5);  /* # of bits of red */
779        (void) WriteBlobByte(image,6);  /* # of bits of green */
780        (void) WriteBlobByte(image,5);  /* # of bits of blue */
781        (void) WriteBlobByte(image,0);  /* reserved by Palm */
782        (void) WriteBlobMSBLong(image,0);  /* no transparent color, YET */
783        offset+=8;
784      }
785    if (bits_per_pixel == 8)
786      {
787        if (flags & PALM_HAS_COLORMAP_FLAG)  /* Write out colormap */
788          {
789            quantize_info->dither=IsPaletteImage(image,&image->exception);
790            quantize_info->number_colors=image->colors;
791            (void) QuantizeImage(quantize_info,image);
792            (void) WriteBlobMSBShort(image,(unsigned short) image->colors);
793            for (count = 0; count < image->colors; count++)
794            {
795              (void) WriteBlobByte(image,(unsigned char) count);
796              (void) WriteBlobByte(image,ScaleQuantumToChar(
797                image->colormap[count].red));
798              (void) WriteBlobByte(image,
799                ScaleQuantumToChar(image->colormap[count].green));
800              (void) WriteBlobByte(image,
801                ScaleQuantumToChar(image->colormap[count].blue));
802            }
803            offset+=2+count*4;
804          }
805      else  /* Map colors to Palm standard colormap */
806        {
807          Image
808            *affinity_image;
809
810          affinity_image=ConstituteImage(256,1,"RGB",CharPixel,&PalmPalette,
811            &exception);
812          (void) SetImageColorspace(affinity_image,affinity_image->colorspace);
813          (void) AffinityImage(quantize_info,image,affinity_image);
814          for (y=0; y < (long) image->rows; y++)
815          {
816            p=GetImagePixels(image,0,y,image->columns,1);
817            indexes=GetIndexes(image);
818            for (x=0; x < (long) image->columns; x++)
819              indexes[x]=(IndexPacket) FindColor(&image->colormap[(long)
820                indexes[x]]);
821          }
822          affinity_image=DestroyImage(affinity_image);
823        }
824      }
825    if (flags & PALM_IS_COMPRESSED_FLAG)
826      (void) WriteBlobMSBShort(image,0);  /* fill in size later */
827    lastrow=(unsigned char *) NULL;
828    if (image_info->compression == FaxCompression)
829      lastrow=(unsigned char *) AcquireQuantumMemory(bytes_per_row,
830        sizeof(*lastrow));
831      /* TODO check whether memory really was acquired? */
832    one_row=(unsigned char *) AcquireQuantumMemory(bytes_per_row,
833      sizeof(*one_row));
834    if (one_row == (unsigned char *) NULL)
835      ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
836    for (y=0; y < (int) image->rows; y++)
837    {
838      ptr=one_row;
839      (void) ResetMagickMemory(ptr,0,bytes_per_row);
840      p=GetImagePixels(image,0,y,image->columns,1);
841      if (p == (PixelPacket *) NULL)
842        break;
843      indexes=GetIndexes(image);
844      if (bits_per_pixel == 16)
845        {
846          for (x=0; x < (int) image->columns; x++)
847          {
848            color16=(unsigned short) ((((31*(unsigned long) p->red)/
849              (unsigned long) QuantumRange) << 11) |
850              (((63*(unsigned long) p->green)/(unsigned long) QuantumRange) << 5) |
851              ((31*(unsigned long) p->blue)/(unsigned long) QuantumRange));
852            if (p->opacity == (Quantum) TransparentOpacity)
853              {
854                transpix.red=p->red;
855                transpix.green=p->green;
856                transpix.blue=p->blue;
857                transpix.opacity=p->opacity;
858                flags|=PALM_HAS_TRANSPARENCY_FLAG;
859              }
860            *ptr++=(unsigned char) ((color16 >> 8) & 0xff);
861            *ptr++=(unsigned char) (color16 & 0xff);
862            p++;
863          }
864        }
865      else
866        {
867          byte=0x00;
868          bit=(unsigned char) (8-bits_per_pixel);
869          for (x=0; x < (int) image->columns; x++)
870          {
871            if (bits_per_pixel >= 8)
872              color=(unsigned char) indexes[x];
873            else
874              color=(unsigned char) (indexes[x]*((1 << bits_per_pixel)-1)/
875                MagickMax(1L*image->colors-1L,1L));
876            byte|=color << bit;
877            if (bit != 0)
878              bit-=bits_per_pixel;
879            else
880              {
881                *ptr++=byte;
882                byte=0x00;
883                bit=(unsigned char) (8-bits_per_pixel);
884              }
885          }
886          if ((image->columns % (8/bits_per_pixel)) != 0)
887            *ptr++=byte;
888        }
889      if (image_info->compression == RLECompression)
890        {
891          x=0;
892          while (x < (long) bytes_per_row)
893          {
894            byte=one_row[x];
895            count=1;
896            while ((one_row[++x] == byte) && (count < 255) &&
897                   (x < (long) bytes_per_row))
898              count++;
899            (void) WriteBlobByte(image,(unsigned char) count);
900            (void) WriteBlobByte(image,(unsigned char) byte);
901          }
902        }
903      else
904        if (image_info->compression == FaxCompression)
905          {
906            char
907              tmpbuf[8],
908              *tptr;
909 
910            for (x = 0;  x < (long) bytes_per_row;  x += 8)
911            {
912              tptr = tmpbuf;
913              for (bit=0, byte=0; bit < (unsigned char) MagickMin(8,(ssize_t) bytes_per_row-x); bit++)
914              {
915                if ((y == 0) || (lastrow[x + bit] != one_row[x + bit]))
916                  {
917                  byte |= (1 << (7 - bit));
918                  *tptr++ = (char) one_row[x + bit];
919                }
920              }
921              (void) WriteBlobByte(image, byte);
922              (void) WriteBlob(image,tptr-tmpbuf,(unsigned char *) tmpbuf);
923            }
924            (void) CopyMagickMemory(lastrow,one_row,bytes_per_row);
925          }
926        else
927          (void) WriteBlob(image,bytes_per_row,one_row);
928      }
929    if (flags & PALM_HAS_TRANSPARENCY_FLAG)
930      {
931        offset=SeekBlob(image,currentOffset+6,SEEK_SET);
932        (void) WriteBlobMSBShort(image,flags);
933        offset=SeekBlob(image,currentOffset+12,SEEK_SET);
934        (void) WriteBlobByte(image,(unsigned char) transparentIndex);  /* trans index */
935      }
936    if (bits_per_pixel == 16)
937      {
938        offset=SeekBlob(image,currentOffset+20,SEEK_SET);
939        (void) WriteBlobByte(image,0);  /* reserved by Palm */
940        (void) WriteBlobByte(image,(unsigned char) ((31*transpix.red)/QuantumRange));
941        (void) WriteBlobByte(image,(unsigned char) ((63*transpix.green)/QuantumRange));
942        (void) WriteBlobByte(image,(unsigned char) ((31*transpix.blue)/QuantumRange));
943      }
944    if (flags & PALM_IS_COMPRESSED_FLAG)  /* fill in size now */
945      {
946        offset=SeekBlob(image,currentOffset+offset,SEEK_SET);
947        (void) WriteBlobMSBShort(image,(unsigned short) (GetBlobSize(image)-
948          currentOffset-offset));
949      }
950    if (one_row != (unsigned char *) NULL)
951      one_row=(unsigned char *) RelinquishMagickMemory(one_row);
952    if (lastrow != (unsigned char *) NULL)
953      lastrow=(unsigned char *) RelinquishMagickMemory(lastrow);
954    if (GetNextImageInList(image) == (Image *) NULL)
955      break;
956    /* padding to 4 byte word */
957    for (cc = (GetBlobSize(image))%4; cc > 0; cc--)
958    {
959      (void) WriteBlobByte(image,0);
960    }