]> granicus.if.org Git - imagemagick/blob - coders/rle.c
55eef4a7eba2b2ed9bf17d2cd96d8ef3d4fa44b2
[imagemagick] / coders / rle.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                            RRRR   L      EEEEE                              %
7 %                            R   R  L      E                                  %
8 %                            RRRR   L      EEE                                %
9 %                            R R    L      E                                  %
10 %                            R  R   LLLLL  EEEEE                              %
11 %                                                                             %
12 %                                                                             %
13 %                          Read URT RLE Image Format                          %
14 %                                                                             %
15 %                              Software Design                                %
16 %                                John Cristy                                  %
17 %                                 July 1992                                   %
18 %                                                                             %
19 %                                                                             %
20 %  Copyright 1999-2012 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/property.h"
44 #include "MagickCore/blob.h"
45 #include "MagickCore/blob-private.h"
46 #include "MagickCore/cache.h"
47 #include "MagickCore/colormap.h"
48 #include "MagickCore/exception.h"
49 #include "MagickCore/exception-private.h"
50 #include "MagickCore/image.h"
51 #include "MagickCore/image-private.h"
52 #include "MagickCore/list.h"
53 #include "MagickCore/magick.h"
54 #include "MagickCore/memory_.h"
55 #include "MagickCore/monitor.h"
56 #include "MagickCore/monitor-private.h"
57 #include "MagickCore/pixel-accessor.h"
58 #include "MagickCore/quantum-private.h"
59 #include "MagickCore/pixel.h"
60 #include "MagickCore/static.h"
61 #include "MagickCore/string_.h"
62 #include "MagickCore/module.h"
63 \f
64 /*
65 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
66 %                                                                             %
67 %                                                                             %
68 %                                                                             %
69 %   I s R L E                                                                 %
70 %                                                                             %
71 %                                                                             %
72 %                                                                             %
73 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
74 %
75 %  IsRLE() returns MagickTrue if the image format type, identified by the
76 %  magick string, is RLE.
77 %
78 %  The format of the ReadRLEImage method is:
79 %
80 %      MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
81 %
82 %  A description of each parameter follows:
83 %
84 %    o magick: compare image format pattern against these bytes.
85 %
86 %    o length: Specifies the length of the magick string.
87 %
88 %
89 */
90 static MagickBooleanType IsRLE(const unsigned char *magick,const size_t length)
91 {
92   if (length < 2)
93     return(MagickFalse);
94   if (memcmp(magick,"\122\314",2) == 0)
95     return(MagickTrue);
96   return(MagickFalse);
97 }
98 \f
99 /*
100 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
101 %                                                                             %
102 %                                                                             %
103 %                                                                             %
104 %   R e a d R L E I m a g e                                                   %
105 %                                                                             %
106 %                                                                             %
107 %                                                                             %
108 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
109 %
110 %  ReadRLEImage() reads a run-length encoded Utah Raster Toolkit
111 %  image file and returns it.  It allocates the memory necessary for the new
112 %  Image structure and returns a pointer to the new image.
113 %
114 %  The format of the ReadRLEImage method is:
115 %
116 %      Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
117 %
118 %  A description of each parameter follows:
119 %
120 %    o image_info: the image info.
121 %
122 %    o exception: return any errors or warnings in this structure.
123 %
124 %
125 */
126 static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
127 {
128 #define SkipLinesOp  0x01
129 #define SetColorOp  0x02
130 #define SkipPixelsOp  0x03
131 #define ByteDataOp  0x05
132 #define RunDataOp  0x06
133 #define EOFOp  0x07
134
135   char
136     magick[12];
137
138   Image
139     *image;
140
141   int
142     opcode,
143     operand,
144     status;
145
146   MagickStatusType
147     flags;
148
149   MagickSizeType
150     number_pixels;
151
152   register ssize_t
153     x;
154
155   register Quantum
156     *q;
157
158   register ssize_t
159     i;
160
161   register unsigned char
162     *p;
163
164   size_t
165     bits_per_pixel,
166     map_length,
167     number_colormaps,
168     number_planes,
169     one;
170
171   ssize_t
172     count,
173     y;
174
175   unsigned char
176     background_color[256],
177     *colormap,
178     pixel,
179     plane,
180     *rle_pixels;
181
182   /*
183     Open image file.
184   */
185   assert(image_info != (const ImageInfo *) NULL);
186   assert(image_info->signature == MagickSignature);
187   if (image_info->debug != MagickFalse)
188     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
189       image_info->filename);
190   assert(exception != (ExceptionInfo *) NULL);
191   assert(exception->signature == MagickSignature);
192   image=AcquireImage(image_info,exception);
193   status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
194   if (status == MagickFalse)
195     {
196       image=DestroyImageList(image);
197       return((Image *) NULL);
198     }
199   /*
200     Determine if this a RLE file.
201   */
202   count=ReadBlob(image,2,(unsigned char *) magick);
203   if ((count == 0) || (memcmp(magick,"\122\314",2) != 0))
204     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
205   do
206   {
207     /*
208       Read image header.
209     */
210     (void) ReadBlobLSBShort(image);
211     (void) ReadBlobLSBShort(image);
212     image->columns=ReadBlobLSBShort(image);
213     image->rows=ReadBlobLSBShort(image);
214     flags=(MagickStatusType) ReadBlobByte(image);
215     image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait;
216     number_planes=1UL*ReadBlobByte(image);
217     bits_per_pixel=1UL*ReadBlobByte(image);
218     number_colormaps=1UL*ReadBlobByte(image);
219     one=1;
220     map_length=one << ReadBlobByte(image);
221     if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) ||
222         (image->columns == 0))
223       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
224     if (flags & 0x02)
225       {
226         /*
227           No background color-- initialize to black.
228         */
229         for (i=0; i < (ssize_t) number_planes; i++)
230           background_color[i]=0;
231         (void) ReadBlobByte(image);
232       }
233     else
234       {
235         /*
236           Initialize background color.
237         */
238         p=background_color;
239         for (i=0; i < (ssize_t) number_planes; i++)
240           *p++=(unsigned char) ReadBlobByte(image);
241       }
242     if ((number_planes & 0x01) == 0)
243       (void) ReadBlobByte(image);
244     colormap=(unsigned char *) NULL;
245     if (number_colormaps != 0)
246       {
247         /*
248           Read image colormaps.
249         */
250         colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
251           map_length*sizeof(*colormap));
252         if (colormap == (unsigned char *) NULL)
253           ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
254         p=colormap;
255         for (i=0; i < (ssize_t) number_colormaps; i++)
256           for (x=0; x < (ssize_t) map_length; x++)
257             *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
258       }
259     if ((flags & 0x08) != 0)
260       {
261         char
262           *comment;
263
264         size_t
265           length;
266
267         /*
268           Read image comment.
269         */
270         length=ReadBlobLSBShort(image);
271         if (length != 0)
272           {
273             comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
274             if (comment == (char *) NULL)
275               ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
276             count=ReadBlob(image,length-1,(unsigned char *) comment);
277             comment[length-1]='\0';
278             (void) SetImageProperty(image,"comment",comment,exception);
279             comment=DestroyString(comment);
280             if ((length & 0x01) == 0)
281               (void) ReadBlobByte(image);
282           }
283       }
284     if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
285       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
286         break;
287     /*
288       Allocate RLE pixels.
289     */
290     if (image->alpha_trait == BlendPixelTrait)
291       number_planes++;
292     number_pixels=(MagickSizeType) image->columns*image->rows;
293     if ((number_pixels*number_planes) != (size_t) (number_pixels*number_planes))
294       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
295     rle_pixels=(unsigned char *) AcquireQuantumMemory(image->columns,
296       image->rows*number_planes*sizeof(*rle_pixels));
297     if (rle_pixels == (unsigned char *) NULL)
298       ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
299     if ((flags & 0x01) && !(flags & 0x02))
300       {
301         ssize_t
302           j;
303
304         /*
305           Set background color.
306         */
307         p=rle_pixels;
308         for (i=0; i < (ssize_t) number_pixels; i++)
309         {
310           if (image->alpha_trait != BlendPixelTrait)
311             for (j=0; j < (ssize_t) number_planes; j++)
312               *p++=background_color[j];
313           else
314             {
315               for (j=0; j < (ssize_t) (number_planes-1); j++)
316                 *p++=background_color[j];
317               *p++=0;  /* initialize matte channel */
318             }
319         }
320       }
321     /*
322       Read runlength-encoded image.
323     */
324     plane=0;
325     x=0;
326     y=0;
327     opcode=ReadBlobByte(image);
328     do
329     {
330       switch (opcode & 0x3f)
331       {
332         case SkipLinesOp:
333         {
334           operand=ReadBlobByte(image);
335           if (opcode & 0x40)
336             operand=(int) ReadBlobLSBShort(image);
337           x=0;
338           y+=operand;
339           break;
340         }
341         case SetColorOp:
342         {
343           operand=ReadBlobByte(image);
344           plane=(unsigned char) operand;
345           if (plane == 255)
346             plane=(unsigned char) (number_planes-1);
347           x=0;
348           break;
349         }
350         case SkipPixelsOp:
351         {
352           operand=ReadBlobByte(image);
353           if (opcode & 0x40)
354             operand=(int) ReadBlobLSBShort(image);
355           x+=operand;
356           break;
357         }
358         case ByteDataOp:
359         {
360           operand=ReadBlobByte(image);
361           if (opcode & 0x40)
362             operand=(int) ReadBlobLSBShort(image);
363           p=rle_pixels+((image->rows-y-1)*image->columns*number_planes)+
364             x*number_planes+plane;
365           operand++;
366           for (i=0; i < (ssize_t) operand; i++)
367           {
368             pixel=(unsigned char) ReadBlobByte(image);
369             if ((y < (ssize_t) image->rows) &&
370                 ((x+i) < (ssize_t) image->columns))
371               *p=pixel;
372             p+=number_planes;
373           }
374           if (operand & 0x01)
375             (void) ReadBlobByte(image);
376           x+=operand;
377           break;
378         }
379         case RunDataOp:
380         {
381           operand=ReadBlobByte(image);
382           if (opcode & 0x40)
383             operand=(int) ReadBlobLSBShort(image);
384           pixel=(unsigned char) ReadBlobByte(image);
385           (void) ReadBlobByte(image);
386           operand++;
387           p=rle_pixels+((image->rows-y-1)*image->columns*number_planes)+
388             x*number_planes+plane;
389           for (i=0; i < (ssize_t) operand; i++)
390           {
391             if ((y < (ssize_t) image->rows) &&
392                 ((x+i) < (ssize_t) image->columns))
393               *p=pixel;
394             p+=number_planes;
395           }
396           x+=operand;
397           break;
398         }
399         default:
400           break;
401       }
402       opcode=ReadBlobByte(image);
403     } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
404     if (number_colormaps != 0)
405       {
406         MagickStatusType
407           mask;
408
409         /*
410           Apply colormap affineation to image.
411         */
412         mask=(MagickStatusType) (map_length-1);
413         p=rle_pixels;
414         if (number_colormaps == 1)
415           for (i=0; i < (ssize_t) number_pixels; i++)
416           {
417             *p=colormap[*p & mask];
418             p++;
419           }
420         else
421           if ((number_planes >= 3) && (number_colormaps >= 3))
422             for (i=0; i < (ssize_t) number_pixels; i++)
423               for (x=0; x < (ssize_t) number_planes; x++)
424               {
425                 *p=colormap[x*map_length+(*p & mask)];
426                 p++;
427               }
428       }
429     /*
430       Initialize image structure.
431     */
432     if (number_planes >= 3)
433       {
434         /*
435           Convert raster image to DirectClass pixel packets.
436         */
437         p=rle_pixels;
438         for (y=0; y < (ssize_t) image->rows; y++)
439         {
440           q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
441           if (q == (Quantum *) NULL)
442             break;
443           for (x=0; x < (ssize_t) image->columns; x++)
444           {
445             SetPixelRed(image,ScaleCharToQuantum(*p++),q);
446             SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
447             SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
448             if (image->alpha_trait == BlendPixelTrait)
449               SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
450             q+=GetPixelChannels(image);
451           }
452           if (SyncAuthenticPixels(image,exception) == MagickFalse)
453             break;
454           if (image->previous == (Image *) NULL)
455             {
456               status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
457                 image->rows);
458               if (status == MagickFalse)
459                 break;
460             }
461         }
462       }
463     else
464       {
465         /*
466           Create colormap.
467         */
468         if (number_colormaps == 0)
469           map_length=256;
470         if (AcquireImageColormap(image,map_length,exception) == MagickFalse)
471           ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
472         p=colormap;
473         if (number_colormaps == 1)
474           for (i=0; i < (ssize_t) image->colors; i++)
475           {
476             /*
477               Pseudocolor.
478             */
479             image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
480             image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
481             image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
482           }
483         else
484           if (number_colormaps > 1)
485             for (i=0; i < (ssize_t) image->colors; i++)
486             {
487               image->colormap[i].red=ScaleCharToQuantum(*p);
488               image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
489               image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
490               p++;
491             }
492         p=rle_pixels;
493         if (image->alpha_trait != BlendPixelTrait)
494           {
495             /*
496               Convert raster image to PseudoClass pixel packets.
497             */
498             for (y=0; y < (ssize_t) image->rows; y++)
499             {
500               q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
501               if (q == (Quantum *) NULL)
502                 break;
503               for (x=0; x < (ssize_t) image->columns; x++)
504               {
505                 SetPixelIndex(image,*p++,q);
506                 q+=GetPixelChannels(image);
507               }
508               if (SyncAuthenticPixels(image,exception) == MagickFalse)
509                 break;
510               if (image->previous == (Image *) NULL)
511                 {
512                   status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
513                     y,image->rows);
514                   if (status == MagickFalse)
515                     break;
516                 }
517             }
518             (void) SyncImage(image,exception);
519           }
520         else
521           {
522             /*
523               Image has a matte channel-- promote to DirectClass.
524             */
525             for (y=0; y < (ssize_t) image->rows; y++)
526             {
527               q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
528               if (q == (Quantum *) NULL)
529                 break;
530               for (x=0; x < (ssize_t) image->columns; x++)
531               {
532                 SetPixelRed(image,image->colormap[*p++].red,q);
533                 SetPixelGreen(image,image->colormap[*p++].green,q);
534                 SetPixelBlue(image,image->colormap[*p++].blue,q);
535                 SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
536                 q+=GetPixelChannels(image);
537               }
538               if (SyncAuthenticPixels(image,exception) == MagickFalse)
539                 break;
540               if (image->previous == (Image *) NULL)
541                 {
542                   status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
543                     y,image->rows);
544                   if (status == MagickFalse)
545                     break;
546                 }
547             }
548             image->colormap=(PixelInfo *) RelinquishMagickMemory(
549               image->colormap);
550             image->storage_class=DirectClass;
551             image->colors=0;
552           }
553       }
554     if (number_colormaps != 0)
555       colormap=(unsigned char *) RelinquishMagickMemory(colormap);
556     rle_pixels=(unsigned char *) RelinquishMagickMemory(rle_pixels);
557     if (EOFBlob(image) != MagickFalse)
558       {
559         ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
560           image->filename);
561         break;
562       }
563     /*
564       Proceed to next image.
565     */
566     if (image_info->number_scenes != 0)
567       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
568         break;
569     (void) ReadBlobByte(image);
570     count=ReadBlob(image,2,(unsigned char *) magick);
571     if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
572       {
573         /*
574           Allocate next image structure.
575         */
576         AcquireNextImage(image_info,image,exception);
577         if (GetNextImageInList(image) == (Image *) NULL)
578           {
579             image=DestroyImageList(image);
580             return((Image *) NULL);
581           }
582         image=SyncNextImageInList(image);
583         status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
584           GetBlobSize(image));
585         if (status == MagickFalse)
586           break;
587       }
588   } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
589   (void) CloseBlob(image);
590   return(GetFirstImageInList(image));
591 }
592 \f
593 /*
594 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
595 %                                                                             %
596 %                                                                             %
597 %                                                                             %
598 %   R e g i s t e r R L E I m a g e                                           %
599 %                                                                             %
600 %                                                                             %
601 %                                                                             %
602 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
603 %
604 %  RegisterRLEImage() adds attributes for the RLE image format to
605 %  the list of supported formats.  The attributes include the image format
606 %  tag, a method to read and/or write the format, whether the format
607 %  supports the saving of more than one frame to the same file or blob,
608 %  whether the format supports native in-memory I/O, and a brief
609 %  description of the format.
610 %
611 %  The format of the RegisterRLEImage method is:
612 %
613 %      size_t RegisterRLEImage(void)
614 %
615 */
616 ModuleExport size_t RegisterRLEImage(void)
617 {
618   MagickInfo
619     *entry;
620
621   entry=SetMagickInfo("RLE");
622   entry->decoder=(DecodeImageHandler *) ReadRLEImage;
623   entry->magick=(IsImageFormatHandler *) IsRLE;
624   entry->adjoin=MagickFalse;
625   entry->description=ConstantString("Utah Run length encoded image");
626   entry->module=ConstantString("RLE");
627   (void) RegisterMagickInfo(entry);
628   return(MagickImageCoderSignature);
629 }
630 \f
631 /*
632 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
633 %                                                                             %
634 %                                                                             %
635 %                                                                             %
636 %   U n r e g i s t e r R L E I m a g e                                       %
637 %                                                                             %
638 %                                                                             %
639 %                                                                             %
640 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
641 %
642 %  UnregisterRLEImage() removes format registrations made by the
643 %  RLE module from the list of supported formats.
644 %
645 %  The format of the UnregisterRLEImage method is:
646 %
647 %      UnregisterRLEImage(void)
648 %
649 */
650 ModuleExport void UnregisterRLEImage(void)
651 {
652   (void) UnregisterMagickInfo("RLE");
653 }