]> granicus.if.org Git - imagemagick/blob - coders/mat.c
Added missing calls to xmlFreeDoc to fix memory leak reported in #1766.
[imagemagick] / coders / mat.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                  M   M   AAA   TTTTT  L       AAA   BBBB                    %
6 %                  MM MM  A   A    T    L      A   A  B   B                   %
7 %                  M M M  AAAAA    T    L      AAAAA  BBBB                    %
8 %                  M   M  A   A    T    L      A   A  B   B                   %
9 %                  M   M  A   A    T    LLLLL  A   A  BBBB                    %
10 %                                                                             %
11 %                                                                             %
12 %                        Read MATLAB Image Format                             %
13 %                                                                             %
14 %                              Software Design                                %
15 %                              Jaroslav Fojtik                                %
16 %                                2001-2008                                    %
17 %                                                                             %
18 %                                                                             %
19 %  Permission is hereby granted, free of charge, to any person obtaining a    %
20 %  copy of this software and associated documentation files ("ImageMagick"),  %
21 %  to deal in ImageMagick without restriction, including without limitation   %
22 %  the rights to use, copy, modify, merge, publish, distribute, sublicense,   %
23 %  and/or sell copies of ImageMagick, and to permit persons to whom the       %
24 %  ImageMagick is furnished to do so, subject to the following conditions:    %
25 %                                                                             %
26 %  The above copyright notice and this permission notice shall be included in %
27 %  all copies or substantial portions of ImageMagick.                         %
28 %                                                                             %
29 %  The software is provided "as is", without warranty of any kind, express or %
30 %  implied, including but not limited to the warranties of merchantability,   %
31 %  fitness for a particular purpose and noninfringement.  In no event shall   %
32 %  ImageMagick Studio be liable for any claim, damages or other liability,    %
33 %  whether in an action of contract, tort or otherwise, arising from, out of  %
34 %  or in connection with ImageMagick or the use or other dealings in          %
35 %  ImageMagick.                                                               %
36 %                                                                             %
37 %  Except as contained in this notice, the name of the ImageMagick Studio     %
38 %  shall not be used in advertising or otherwise to promote the sale, use or  %
39 %  other dealings in ImageMagick without prior written authorization from the %
40 %  ImageMagick Studio.                                                        %
41 %                                                                             %
42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
43 %
44 %
45 */
46 \f
47 /*
48   Include declarations.
49 */
50 #include "MagickCore/studio.h"
51 #include "MagickCore/attribute.h"
52 #include "MagickCore/blob.h"
53 #include "MagickCore/blob-private.h"
54 #include "MagickCore/cache.h"
55 #include "MagickCore/color-private.h"
56 #include "MagickCore/colormap.h"
57 #include "MagickCore/colorspace-private.h"
58 #include "MagickCore/distort.h"
59 #include "MagickCore/exception.h"
60 #include "MagickCore/exception-private.h"
61 #include "MagickCore/image.h"
62 #include "MagickCore/image-private.h"
63 #include "MagickCore/list.h"
64 #include "MagickCore/magick.h"
65 #include "MagickCore/memory_.h"
66 #include "MagickCore/monitor.h"
67 #include "MagickCore/monitor-private.h"
68 #include "MagickCore/pixel-accessor.h"
69 #include "MagickCore/quantum.h"
70 #include "MagickCore/quantum-private.h"
71 #include "MagickCore/option.h"
72 #include "MagickCore/pixel.h"
73 #include "MagickCore/resource_.h"
74 #include "MagickCore/static.h"
75 #include "MagickCore/string_.h"
76 #include "MagickCore/module.h"
77 #include "MagickCore/timer-private.h"
78 #include "MagickCore/transform.h"
79 #include "MagickCore/utility-private.h"
80 #if defined(MAGICKCORE_ZLIB_DELEGATE)
81  #include "zlib.h"
82 #endif
83 \f
84 /*
85   Forward declaration.
86 */
87 static MagickBooleanType
88   WriteMATImage(const ImageInfo *,Image *,ExceptionInfo *);
89
90
91 /* Auto coloring method, sorry this creates some artefact inside data
92 MinReal+j*MaxComplex = red  MaxReal+j*MaxComplex = black
93 MinReal+j*0 = white          MaxReal+j*0 = black
94 MinReal+j*MinComplex = blue  MaxReal+j*MinComplex = black
95 */
96
97 typedef struct
98 {
99   char identific[124];
100   unsigned short Version;
101   char EndianIndicator[2];
102   unsigned int DataType;
103   unsigned int ObjectSize;
104   unsigned int unknown1;
105   unsigned int unknown2;
106
107   unsigned short unknown5;
108   unsigned char StructureFlag;
109   unsigned char StructureClass;
110   unsigned int unknown3;
111   unsigned int unknown4;
112   unsigned int DimFlag;
113
114   unsigned int SizeX;
115   unsigned int SizeY;
116   unsigned short Flag1;
117   unsigned short NameFlag;
118 }
119 MATHeader;
120
121 static const char
122   MonthsTab[12][4] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
123
124 static const char
125    DayOfWTab[7][4] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
126
127 static const char
128   OsDesc[] =
129 #if defined(MAGICKCORE_WINDOWS_SUPPORT)
130     "PCWIN";
131 #else
132  #ifdef __APPLE__
133     "MAC";
134  #else
135     "LNX86";
136  #endif
137 #endif
138
139 typedef enum
140   {
141     miINT8 = 1,      /* 8 bit signed */
142     miUINT8,      /* 8 bit unsigned */
143     miINT16,      /* 16 bit signed */
144     miUINT16,      /* 16 bit unsigned */
145     miINT32,      /* 32 bit signed */
146     miUINT32,      /* 32 bit unsigned */
147     miSINGLE,      /* IEEE 754 single precision float */
148     miRESERVE1,
149     miDOUBLE,      /* IEEE 754 double precision float */
150     miRESERVE2,
151     miRESERVE3,
152     miINT64,      /* 64 bit signed */
153     miUINT64,      /* 64 bit unsigned */
154     miMATRIX,            /* MATLAB array */
155     miCOMPRESSED,          /* Compressed Data */
156     miUTF8,            /* Unicode UTF-8 Encoded Character Data */
157     miUTF16,            /* Unicode UTF-16 Encoded Character Data */
158     miUTF32      /* Unicode UTF-32 Encoded Character Data */
159   } mat5_data_type;
160
161 typedef enum
162   {
163     mxCELL_CLASS=1,    /* cell array */
164     mxSTRUCT_CLASS,    /* structure */
165     mxOBJECT_CLASS,    /* object */
166     mxCHAR_CLASS,    /* character array */
167     mxSPARSE_CLASS,    /* sparse array */
168     mxDOUBLE_CLASS,    /* double precision array */
169     mxSINGLE_CLASS,    /* single precision floating point */
170     mxINT8_CLASS,    /* 8 bit signed integer */
171     mxUINT8_CLASS,    /* 8 bit unsigned integer */
172     mxINT16_CLASS,    /* 16 bit signed integer */
173     mxUINT16_CLASS,    /* 16 bit unsigned integer */
174     mxINT32_CLASS,    /* 32 bit signed integer */
175     mxUINT32_CLASS,    /* 32 bit unsigned integer */
176     mxINT64_CLASS,    /* 64 bit signed integer */
177     mxUINT64_CLASS,    /* 64 bit unsigned integer */
178     mxFUNCTION_CLASS            /* Function handle */
179   } arrayclasstype;
180
181 #define FLAG_COMPLEX 0x8
182 #define FLAG_GLOBAL  0x4
183 #define FLAG_LOGICAL 0x2
184
185 static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
186
187 static void InsertComplexDoubleRow(Image *image,double *p,int y,double MinVal,
188   double MaxVal,ExceptionInfo *exception)
189 {
190   double f;
191   int x;
192   register Quantum *q;
193
194   if (MinVal >= 0)
195     MinVal = -1;
196   if (MaxVal <= 0)
197     MaxVal = 1;
198
199   q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
200   if (q == (Quantum *) NULL)
201     return;
202   for (x = 0; x < (ssize_t) image->columns; x++)
203   {
204     if (*p > 0)
205       {
206         f=(*p/MaxVal)*(Quantum) (QuantumRange-GetPixelRed(image,q));
207         if ((f+GetPixelRed(image,q)) >= QuantumRange)
208           SetPixelRed(image,QuantumRange,q);
209         else
210           SetPixelRed(image,GetPixelRed(image,q)+ClampToQuantum(f),q);
211         f=GetPixelGreen(image,q)-f/2.0;
212         if (f <= 0.0)
213           {
214             SetPixelGreen(image,0,q);
215             SetPixelBlue(image,0,q);
216           }
217         else
218           {
219             SetPixelBlue(image,ClampToQuantum(f),q);
220             SetPixelGreen(image,ClampToQuantum(f),q);
221           }
222       }
223     if (*p < 0)
224       {
225         f=(*p/MinVal)*(Quantum) (QuantumRange-GetPixelBlue(image,q));
226         if ((f+GetPixelBlue(image,q)) >= QuantumRange)
227           SetPixelBlue(image,QuantumRange,q);
228         else
229           SetPixelBlue(image,GetPixelBlue(image,q)+ClampToQuantum(f),q);
230         f=GetPixelGreen(image,q)-f/2.0;
231         if (f <= 0.0)
232           {
233             SetPixelRed(image,0,q);
234             SetPixelGreen(image,0,q);
235           }
236         else
237           {
238             SetPixelRed(image,ClampToQuantum(f),q);
239             SetPixelGreen(image,ClampToQuantum(f),q);
240           }
241       }
242     p++;
243     q++;
244   }
245   if (!SyncAuthenticPixels(image,exception))
246     return;
247   return;
248 }
249
250 static void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal,
251   double MaxVal,ExceptionInfo *exception)
252 {
253   double f;
254   int x;
255   register Quantum *q;
256
257   if (MinVal >= 0)
258     MinVal = -1;
259   if (MaxVal <= 0)
260     MaxVal = 1;
261
262   q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
263   if (q == (Quantum *) NULL)
264     return;
265   for (x = 0; x < (ssize_t) image->columns; x++)
266   {
267     if (*p > 0)
268       {
269         f=(*p/MaxVal)*(Quantum) (QuantumRange-GetPixelRed(image,q));
270         if ((f+GetPixelRed(image,q)) < QuantumRange)
271           SetPixelRed(image,GetPixelRed(image,q)+ClampToQuantum(f),q);
272         else
273           SetPixelRed(image,QuantumRange,q);
274         f/=2.0;
275         if (f < GetPixelGreen(image,q))
276           {
277             SetPixelBlue(image,GetPixelBlue(image,q)-ClampToQuantum(f),q);
278             SetPixelGreen(image,GetPixelBlue(image,q),q);
279           }
280         else
281           {
282             SetPixelGreen(image,0,q);
283             SetPixelBlue(image,0,q);
284           }
285       }
286     if (*p < 0)
287       {
288         f=(*p/MaxVal)*(Quantum) (QuantumRange-GetPixelBlue(image,q));
289         if ((f+GetPixelBlue(image,q)) < QuantumRange)
290           SetPixelBlue(image,GetPixelBlue(image,q)+ClampToQuantum(f),q);
291         else
292           SetPixelBlue(image,QuantumRange,q);
293         f/=2.0;
294         if (f < GetPixelGreen(image,q))
295           {
296             SetPixelRed(image,GetPixelRed(image,q)-ClampToQuantum(f),q);
297             SetPixelGreen(image,GetPixelRed(image,q),q);
298           }
299         else
300           {
301             SetPixelGreen(image,0,q);
302             SetPixelRed(image,0,q);
303           }
304       }
305     p++;
306     q++;
307   }
308   if (!SyncAuthenticPixels(image,exception))
309     return;
310   return;
311 }
312
313
314 /************** READERS ******************/
315
316 /* This function reads one block of floats*/
317 static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
318 {
319   while (len >= 4)
320   {
321     *data++ = ReadBlobFloat(image);
322     len -= sizeof(float);
323   }
324   if (len > 0)
325     (void) SeekBlob(image, len, SEEK_CUR);
326 }
327
328 static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
329 {
330   while (len >= 4)
331   {
332     *data++ = ReadBlobFloat(image);
333     len -= sizeof(float);
334   }
335   if (len > 0)
336     (void) SeekBlob(image, len, SEEK_CUR);
337 }
338
339 /* This function reads one block of doubles*/
340 static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
341 {
342   while (len >= 8)
343   {
344     *data++ = ReadBlobDouble(image);
345     len -= sizeof(double);
346   }
347   if (len > 0)
348     (void) SeekBlob(image, len, SEEK_CUR);
349 }
350
351 static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
352 {
353   while (len >= 8)
354   {
355     *data++ = ReadBlobDouble(image);
356     len -= sizeof(double);
357   }
358   if (len > 0)
359     (void) SeekBlob(image, len, SEEK_CUR);
360 }
361
362 /* Calculate minimum and maximum from a given block of data */
363 static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
364 {
365 MagickOffsetType filepos;
366 int i, x;
367 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
368 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
369 double *dblrow;
370 float *fltrow;
371
372   if (endian_indicator == LSBEndian)
373   {
374     ReadBlobDoublesXXX = ReadBlobDoublesLSB;
375     ReadBlobFloatsXXX = ReadBlobFloatsLSB;
376   }
377   else    /* MI */
378   {
379     ReadBlobDoublesXXX = ReadBlobDoublesMSB;
380     ReadBlobFloatsXXX = ReadBlobFloatsMSB;
381   }
382
383   filepos = TellBlob(image);     /* Please note that file seeking occurs only in the case of doubles */
384   for (i = 0; i < SizeY; i++)
385   {
386     if (CellType==miDOUBLE)
387     {
388       ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
389       dblrow = (double *)BImgBuff;
390       if (i == 0)
391       {
392         *Min = *Max = *dblrow;
393       }
394       for (x = 0; x < SizeX; x++)
395       {
396         if (*Min > *dblrow)
397           *Min = *dblrow;
398         if (*Max < *dblrow)
399           *Max = *dblrow;
400         dblrow++;
401       }
402     }
403     if (CellType==miSINGLE)
404     {
405       ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
406       fltrow = (float *)BImgBuff;
407       if (i == 0)
408       {
409         *Min = *Max = *fltrow;
410       }
411     for (x = 0; x < (ssize_t) SizeX; x++)
412       {
413         if (*Min > *fltrow)
414           *Min = *fltrow;
415         if (*Max < *fltrow)
416           *Max = *fltrow;
417         fltrow++;
418       }
419     }
420   }
421   (void) SeekBlob(image, filepos, SEEK_SET);
422 }
423
424
425 static void FixSignedValues(const Image *image,Quantum *q, int y)
426 {
427   while(y-->0)
428   {
429      /* Please note that negative values will overflow
430         Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
431            <-1;-128> + 127+1 = <0; 127> */
432     SetPixelRed(image,GetPixelRed(image,q)+QuantumRange/2+1,q);
433     SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q);
434     SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q);
435     q++;
436   }
437 }
438
439
440 /** Fix whole row of logical/binary data. It means pack it. */
441 static void FixLogical(unsigned char *Buff,int ldblk)
442 {
443 unsigned char mask=128;
444 unsigned char *BuffL = Buff;
445 unsigned char val = 0;
446
447   while(ldblk-->0)
448   {
449     if(*Buff++ != 0)
450       val |= mask;
451
452     mask >>= 1;
453     if(mask==0)
454     {
455       *BuffL++ = val;
456       val = 0;
457       mask = 128;
458     }
459
460   }
461   *BuffL = val;
462 }
463
464 #if defined(MAGICKCORE_ZLIB_DELEGATE)
465 static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
466   unsigned int size)
467 {
468   (void) context;
469   return((voidpf) AcquireQuantumMemory(items,size));
470 }
471
472 static void RelinquishZIPMemory(voidpf context,voidpf memory)
473 {
474   (void) context;
475   memory=RelinquishMagickMemory(memory);
476 }
477 #endif
478
479 #if defined(MAGICKCORE_ZLIB_DELEGATE)
480 /** This procedure decompreses an image block for a new MATLAB format. */
481 static Image *decompress_block(Image *orig, unsigned int *Size, ImageInfo *clone_info, ExceptionInfo *exception)
482 {
483
484 Image *image2;
485 void *cache_block, *decompress_block;
486 z_stream zip_info;
487 FILE *mat_file;
488 size_t magick_size;
489 size_t extent;
490 int file;
491
492 int status;
493 int zip_status;
494 ssize_t TotalSize = 0;
495
496   if(clone_info==NULL) return NULL;
497   if(clone_info->file)    /* Close file opened from previous transaction. */
498   {
499     fclose(clone_info->file);
500     clone_info->file = NULL;
501     (void) remove_utf8(clone_info->filename);
502   }
503
504   cache_block = AcquireQuantumMemory((size_t)(*Size < MagickMinBufferExtent) ? *Size: MagickMinBufferExtent,sizeof(unsigned char *));
505   if(cache_block==NULL) return NULL;
506   decompress_block = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
507   if(decompress_block==NULL)
508   {
509     RelinquishMagickMemory(cache_block);
510     return NULL;
511   }
512
513   mat_file=0;
514   file = AcquireUniqueFileResource(clone_info->filename);
515   if (file != -1)
516     mat_file = fdopen(file,"w");
517   if(!mat_file)
518   {
519     RelinquishMagickMemory(cache_block);
520     RelinquishMagickMemory(decompress_block);
521     (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Cannot create file stream for decompressed image");
522     return NULL;
523   }
524
525   zip_info.zalloc=AcquireZIPMemory;
526   zip_info.zfree=RelinquishZIPMemory;
527   zip_info.opaque = (voidpf) NULL;
528   zip_status = inflateInit(&zip_info);
529   if (zip_status != Z_OK)
530     {
531       RelinquishMagickMemory(cache_block);
532       RelinquishMagickMemory(decompress_block);
533       (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
534         "UnableToUncompressImage","`%s'",clone_info->filename);
535       (void) fclose(mat_file);
536       RelinquishUniqueFileResource(clone_info->filename);
537       return NULL;
538     }
539   /* zip_info.next_out = 8*4;*/
540
541   zip_info.avail_in = 0;
542   zip_info.total_out = 0;
543   while(*Size>0 && !EOFBlob(orig))
544   {
545     magick_size = ReadBlob(orig, (*Size < MagickMinBufferExtent) ? *Size : MagickMinBufferExtent, (unsigned char *) cache_block);
546     if (magick_size == 0)
547       break;
548     zip_info.next_in = (Bytef *) cache_block;
549     zip_info.avail_in = (uInt) magick_size;
550
551     while(zip_info.avail_in>0)
552     {
553       zip_info.avail_out = 4096;
554       zip_info.next_out = (Bytef *) decompress_block;
555       zip_status = inflate(&zip_info,Z_NO_FLUSH);
556       if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
557         break;
558       extent=fwrite(decompress_block, 4096-zip_info.avail_out, 1, mat_file);
559       (void) extent;
560       TotalSize += 4096-zip_info.avail_out;
561
562       if(zip_status == Z_STREAM_END) goto DblBreak;
563     }
564     if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
565       break;
566
567     *Size -= (unsigned int) magick_size;
568   }
569 DblBreak:
570
571   inflateEnd(&zip_info);
572   (void)fclose(mat_file);
573   RelinquishMagickMemory(cache_block);
574   RelinquishMagickMemory(decompress_block);
575   *Size = TotalSize;
576
577   if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
578   if( (image2 = AcquireImage(clone_info,exception))==NULL ) goto EraseFile;
579   status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
580   if (status == MagickFalse)
581   {
582     DeleteImageFromList(&image2);
583 EraseFile:
584     fclose(clone_info->file);
585     clone_info->file = NULL;
586 UnlinkFile:
587     RelinquishUniqueFileResource(clone_info->filename);
588     return NULL;
589   }
590
591   return image2;
592 }
593 #endif
594
595 static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,
596   ExceptionInfo *exception)
597 {
598   typedef struct {
599     unsigned char Type[4];
600     unsigned int nRows;
601     unsigned int nCols;
602     unsigned int imagf;
603     unsigned int nameLen;
604   } MAT4_HDR;
605
606   long
607     ldblk;
608
609   EndianType
610     endian;
611
612   Image
613     *rotated_image;
614
615   MagickBooleanType
616     status;
617
618   MAT4_HDR
619     HDR;
620
621   QuantumInfo
622     *quantum_info;
623
624   QuantumFormatType
625     format_type;
626
627   register ssize_t
628     i;
629
630   ssize_t
631     count,
632     y;
633
634   unsigned char
635     *pixels;
636
637   unsigned int
638     depth;
639
640   quantum_info=(QuantumInfo *) NULL;
641   (void) SeekBlob(image,0,SEEK_SET);
642   status=MagickTrue;
643   while (EOFBlob(image) == MagickFalse)
644   {
645     /*
646      Object parser loop.
647     */
648     ldblk=ReadBlobLSBLong(image);
649     if(EOFBlob(image)) break;
650     if ((ldblk > 9999) || (ldblk < 0))
651       break;
652     HDR.Type[3]=ldblk % 10; ldblk /= 10;  /* T digit */
653     HDR.Type[2]=ldblk % 10; ldblk /= 10;  /* P digit */
654     HDR.Type[1]=ldblk % 10; ldblk /= 10;  /* O digit */
655     HDR.Type[0]=ldblk;        /* M digit */
656     if (HDR.Type[3] != 0)
657       break;  /* Data format */
658     if (HDR.Type[2] != 0)
659       break;  /* Always 0 */
660     if (HDR.Type[0] == 0)
661       {
662         HDR.nRows=ReadBlobLSBLong(image);
663         HDR.nCols=ReadBlobLSBLong(image);
664         HDR.imagf=ReadBlobLSBLong(image);
665         HDR.nameLen=ReadBlobLSBLong(image);
666         endian=LSBEndian;
667       }
668     else
669       {
670         HDR.nRows=ReadBlobMSBLong(image);
671         HDR.nCols=ReadBlobMSBLong(image);
672         HDR.imagf=ReadBlobMSBLong(image);
673         HDR.nameLen=ReadBlobMSBLong(image);
674         endian=MSBEndian;
675       }
676     if ((HDR.imagf != 0) && (HDR.imagf != 1))
677       break;
678     if (HDR.nameLen > 0xFFFF)
679       return(DestroyImageList(image));
680     for (i=0; i < (ssize_t) HDR.nameLen; i++)
681     {
682       int
683         byte;
684
685       /*
686         Skip matrix name.
687       */
688       byte=ReadBlobByte(image);
689       if (byte == EOF)
690         {
691           ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
692             image->filename);
693           break;
694         }
695     }
696     image->columns=(size_t) HDR.nRows;
697     image->rows=(size_t) HDR.nCols;
698     if ((image->columns == 0) || (image->rows == 0))
699       return(DestroyImageList(image));
700     if (image_info->ping != MagickFalse)
701       {
702         Swap(image->columns,image->rows);
703         if(HDR.imagf==1) ldblk *= 2;
704         SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR);
705         if ((image->columns == 0) || (image->rows == 0))
706           return(image->previous == (Image *) NULL ? DestroyImageList(image)
707             : image);
708         goto skip_reading_current;
709       }
710     status=SetImageExtent(image,image->columns,image->rows,exception);
711     if (status == MagickFalse)
712       return(DestroyImageList(image));
713     (void) SetImageBackgroundColor(image,exception);
714     (void) SetImageColorspace(image,GRAYColorspace,exception);
715     quantum_info=AcquireQuantumInfo(image_info,image);
716     if (quantum_info == (QuantumInfo *) NULL)
717       return(DestroyImageList(image));
718     switch(HDR.Type[1])
719     {
720       case 0:
721         format_type=FloatingPointQuantumFormat;
722         depth=64;
723         break;
724       case 1:
725         format_type=FloatingPointQuantumFormat;
726         depth=32;
727         break;
728       case 2:
729         format_type=UnsignedQuantumFormat;
730         depth=16;
731         break;
732       case 3:
733         format_type=SignedQuantumFormat;
734         depth=16;
735         break;
736       case 4:
737         format_type=UnsignedQuantumFormat;
738         depth=8;
739         break;
740       default:
741         format_type=UnsignedQuantumFormat;
742         depth=8;
743         break;
744     }
745     image->depth=depth;
746     if (HDR.Type[0] != 0)
747       SetQuantumEndian(image,quantum_info,MSBEndian);
748     status=SetQuantumFormat(image,quantum_info,format_type);
749     status=SetQuantumDepth(image,quantum_info,depth);
750     status=SetQuantumEndian(image,quantum_info,endian);
751     SetQuantumScale(quantum_info,1.0);
752     pixels=(unsigned char *) GetQuantumPixels(quantum_info);
753     for (y=0; y < (ssize_t) image->rows; y++)
754     {
755       register Quantum
756         *magick_restrict q;
757
758       count=ReadBlob(image,depth/8*image->columns,(char *) pixels);
759       if (count == -1)
760         break;
761       q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,
762         exception);
763       if (q == (Quantum *) NULL)
764         break;
765       (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
766         GrayQuantum,pixels,exception);
767       if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))
768         FixSignedValues(image,q,(int) image->columns);
769       if (SyncAuthenticPixels(image,exception) == MagickFalse)
770         break;
771       if (image->previous == (Image *) NULL)
772         {
773           status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
774             image->rows);
775           if (status == MagickFalse)
776             break;
777         }
778     }
779     if (HDR.imagf == 1)
780       for (y=0; y < (ssize_t) image->rows; y++)
781       {
782         /*
783           Read complex pixels.
784         */
785         count=ReadBlob(image,depth/8*image->columns,(char *) pixels);
786         if (count == -1)
787           break;
788         if (HDR.Type[1] == 0)
789           InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception);
790         else
791           InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception);
792       }
793     if (quantum_info != (QuantumInfo *) NULL)
794       quantum_info=DestroyQuantumInfo(quantum_info);
795     if (EOFBlob(image) != MagickFalse)
796       {
797         ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
798           image->filename);
799         break;
800       }
801     rotated_image=RotateImage(image,90.0,exception);
802     if (rotated_image != (Image *) NULL)
803       {
804         rotated_image->page.x=0;
805         rotated_image->page.y=0;
806         rotated_image->colors = image->colors;
807         DestroyBlob(rotated_image);
808         rotated_image->blob=ReferenceBlob(image->blob);
809         AppendImageToList(&image,rotated_image);
810         DeleteImageFromList(&image);
811       }
812     /*
813       Proceed to next image.
814     */
815     if (image_info->number_scenes != 0)
816       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
817         break;
818     /*
819       Allocate next image structure.
820     */
821 skip_reading_current:
822     if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
823       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
824         break;
825     AcquireNextImage(image_info,image,exception);
826     if (GetNextImageInList(image) == (Image *) NULL)
827       {
828         status=MagickFalse;
829         break;
830       }
831     image=SyncNextImageInList(image);
832     status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
833       GetBlobSize(image));
834     if (status == MagickFalse)
835       break;
836   }
837   (void) CloseBlob(image);
838   if (status == MagickFalse)
839     return(DestroyImageList(image));
840   return(GetFirstImageInList(image));
841 }
842 \f
843 /*
844 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
845 %                                                                             %
846 %                                                                             %
847 %                                                                             %
848 %   R e a d M A T L A B i m a g e                                             %
849 %                                                                             %
850 %                                                                             %
851 %                                                                             %
852 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
853 %
854 %  ReadMATImage() reads an MAT X image file and returns it.  It
855 %  allocates the memory necessary for the new Image structure and returns a
856 %  pointer to the new image.
857 %
858 %  The format of the ReadMATImage method is:
859 %
860 %      Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
861 %
862 %  A description of each parameter follows:
863 %
864 %    o image:  Method ReadMATImage returns a pointer to the image after
865 %      reading. A null image is returned if there is a memory shortage or if
866 %      the image cannot be read.
867 %
868 %    o image_info: Specifies a pointer to a ImageInfo structure.
869 %
870 %    o exception: return any errors or warnings in this structure.
871 %
872 */
873 static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
874 {
875   Image *image, *image2=NULL,
876    *rotated_image;
877   register Quantum *q;
878
879   unsigned int status;
880   MATHeader MATLAB_HDR;
881   size_t size;
882   size_t CellType;
883   QuantumInfo *quantum_info;
884   ImageInfo *clone_info;
885   int i;
886   ssize_t ldblk;
887   unsigned char *BImgBuff = NULL;
888   double MinVal, MaxVal;
889   unsigned z, z2;
890   unsigned Frames;
891   int logging;
892   int sample_size;
893   MagickOffsetType filepos=0x80;
894
895   unsigned int (*ReadBlobXXXLong)(Image *image);
896   unsigned short (*ReadBlobXXXShort)(Image *image);
897   void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
898   void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
899
900
901   assert(image_info != (const ImageInfo *) NULL);
902   assert(image_info->signature == MagickCoreSignature);
903   assert(exception != (ExceptionInfo *) NULL);
904   assert(exception->signature == MagickCoreSignature);
905   logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
906
907   /*
908      Open image file.
909    */
910   image = AcquireImage(image_info,exception);
911   image2 = (Image *) NULL;
912
913   status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
914   if (status == MagickFalse)
915     {
916       image=DestroyImageList(image);
917       return((Image *) NULL);
918     }
919   /*
920      Read MATLAB image.
921    */
922   quantum_info=(QuantumInfo *) NULL;
923   clone_info=(ImageInfo *) NULL;
924   if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
925     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
926   if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
927     {
928       image=ReadMATImageV4(image_info,image,exception);
929       if (image == NULL)
930         {
931           if ((image != image2) && (image2 != (Image *) NULL))
932             image2=DestroyImage(image2);
933           if (clone_info != (ImageInfo *) NULL)
934             clone_info=DestroyImageInfo(clone_info);
935           return((Image *) NULL);
936         }
937       goto END_OF_READING;
938     }
939   MATLAB_HDR.Version = ReadBlobLSBShort(image);
940   if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
941     ThrowReaderException(CorruptImageError,"ImproperImageHeader");
942
943   if (logging)
944     (void) LogMagickEvent(CoderEvent,GetMagickModule(),"  Endian %c%c",
945       MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
946   if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
947   {
948     ReadBlobXXXLong = ReadBlobLSBLong;
949     ReadBlobXXXShort = ReadBlobLSBShort;
950     ReadBlobDoublesXXX = ReadBlobDoublesLSB;
951     ReadBlobFloatsXXX = ReadBlobFloatsLSB;
952     image->endian = LSBEndian;
953   }
954   else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
955   {
956     ReadBlobXXXLong = ReadBlobMSBLong;
957     ReadBlobXXXShort = ReadBlobMSBShort;
958     ReadBlobDoublesXXX = ReadBlobDoublesMSB;
959     ReadBlobFloatsXXX = ReadBlobFloatsMSB;
960     image->endian = MSBEndian;
961   }
962   else
963     {
964 MATLAB_KO:
965       if ((image != image2) && (image2 != (Image *) NULL))
966         image2=DestroyImage(image2);
967       if (clone_info != (ImageInfo *) NULL)
968         clone_info=DestroyImageInfo(clone_info);
969       ThrowReaderException(CorruptImageError,"ImproperImageHeader");
970     }
971
972   filepos = TellBlob(image);
973   while(filepos < (MagickOffsetType) GetBlobSize(image) && !EOFBlob(image)) /* object parser loop */
974   {
975     Frames = 1;
976     if(filepos > (MagickOffsetType) GetBlobSize(image) || filepos < 0)
977       break;
978     if(SeekBlob(image,filepos,SEEK_SET) != filepos) break;
979     /* printf("pos=%X\n",TellBlob(image)); */
980
981     MATLAB_HDR.DataType = ReadBlobXXXLong(image);
982     if(EOFBlob(image)) break;
983     MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
984     if(EOFBlob(image)) break;
985     if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) >= GetBlobSize(image))
986       goto MATLAB_KO;
987     filepos += (MagickOffsetType) MATLAB_HDR.ObjectSize + 4 + 4;
988
989     if (clone_info != (ImageInfo *) NULL)
990       clone_info=DestroyImageInfo(clone_info);
991     clone_info=CloneImageInfo(image_info);
992     if ((image != image2) && (image2 != (Image *) NULL))
993       image2=DestroyImage(image2);
994     image2 = image;
995 #if defined(MAGICKCORE_ZLIB_DELEGATE)
996     if(MATLAB_HDR.DataType == miCOMPRESSED)
997     {
998       image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception);
999       if(image2==NULL) continue;
1000       MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
1001     }
1002 #endif
1003
1004     if (MATLAB_HDR.DataType != miMATRIX)
1005       {
1006         clone_info=DestroyImageInfo(clone_info);
1007 #if defined(MAGICKCORE_ZLIB_DELEGATE)
1008         if (image2 != image)
1009           DeleteImageFromList(&image2);
1010 #endif
1011         continue;  /* skip another objects. */
1012       }
1013
1014     MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
1015     MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
1016
1017     MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
1018     MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
1019     MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
1020
1021     MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
1022     if(image!=image2)
1023       MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);  /* ??? don't understand why ?? */
1024     MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
1025     MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
1026     MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
1027     MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
1028
1029
1030     switch(MATLAB_HDR.DimFlag)
1031     {
1032       case  8: z2=z=1; break;      /* 2D matrix*/
1033       case 12: z2=z = ReadBlobXXXLong(image2);  /* 3D matrix RGB*/
1034            (void) ReadBlobXXXLong(image2);
1035          if(z!=3)
1036            {
1037              if (clone_info != (ImageInfo *) NULL)
1038                clone_info=DestroyImageInfo(clone_info);
1039              if ((image != image2) && (image2 != (Image *) NULL))
1040                image2=DestroyImage(image2);
1041              ThrowReaderException(CoderError,
1042                "MultidimensionalMatricesAreNotSupported");
1043            }
1044          break;
1045       case 16: z2=z = ReadBlobXXXLong(image2);  /* 4D matrix animation */
1046          if(z!=3 && z!=1)
1047            {
1048              if (clone_info != (ImageInfo *) NULL)
1049                clone_info=DestroyImageInfo(clone_info);
1050              if ((image != image2) && (image2 != (Image *) NULL))
1051                image2=DestroyImage(image2);
1052              ThrowReaderException(CoderError,
1053                "MultidimensionalMatricesAreNotSupported");
1054            }
1055           Frames = ReadBlobXXXLong(image2);
1056           if (Frames == 0)
1057             {
1058               if (clone_info != (ImageInfo *) NULL)
1059                 clone_info=DestroyImageInfo(clone_info);
1060               if ((image != image2) && (image2 != (Image *) NULL))
1061                 image2=DestroyImage(image2);
1062               ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1063             }
1064           if (AcquireMagickResource(ListLengthResource,Frames) == MagickFalse)
1065             {
1066               if (clone_info != (ImageInfo *) NULL)
1067                 clone_info=DestroyImageInfo(clone_info);
1068               if ((image != image2) && (image2 != (Image *) NULL))
1069                 image2=DestroyImage(image2);
1070               ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit");
1071             }
1072          break;
1073       default:
1074         if (clone_info != (ImageInfo *) NULL)
1075           clone_info=DestroyImageInfo(clone_info);
1076         if ((image != image2) && (image2 != (Image *) NULL))
1077           image2=DestroyImage(image2);
1078         ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
1079     }
1080
1081     MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
1082     MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
1083
1084     if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
1085           "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
1086     if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
1087         MATLAB_HDR.StructureClass != mxSINGLE_CLASS &&    /* float + complex float */
1088         MATLAB_HDR.StructureClass != mxDOUBLE_CLASS &&    /* double + complex double */
1089         MATLAB_HDR.StructureClass != mxINT8_CLASS &&
1090         MATLAB_HDR.StructureClass != mxUINT8_CLASS &&    /* uint8 + uint8 3D */
1091         MATLAB_HDR.StructureClass != mxINT16_CLASS &&
1092         MATLAB_HDR.StructureClass != mxUINT16_CLASS &&    /* uint16 + uint16 3D */
1093         MATLAB_HDR.StructureClass != mxINT32_CLASS &&
1094         MATLAB_HDR.StructureClass != mxUINT32_CLASS &&    /* uint32 + uint32 3D */
1095         MATLAB_HDR.StructureClass != mxINT64_CLASS &&
1096         MATLAB_HDR.StructureClass != mxUINT64_CLASS)    /* uint64 + uint64 3D */
1097       {
1098         if ((image2 != (Image*) NULL) && (image2 != image))
1099           {
1100             CloseBlob(image2);
1101             DeleteImageFromList(&image2);
1102           }
1103         if (clone_info != (ImageInfo *) NULL)
1104           clone_info=DestroyImageInfo(clone_info);
1105         ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
1106       }
1107
1108     switch (MATLAB_HDR.NameFlag)
1109     {
1110       case 0:
1111         size = ReadBlobXXXLong(image2);  /* Object name string size */
1112         size = 4 * (((size_t) size + 3 + 1) / 4);
1113         (void) SeekBlob(image2, size, SEEK_CUR);
1114         break;
1115       case 1:
1116       case 2:
1117       case 3:
1118       case 4:
1119         (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
1120         break;
1121       default:
1122         goto MATLAB_KO;
1123     }
1124
1125     CellType = ReadBlobXXXLong(image2);    /* Additional object type */
1126     if (logging)
1127       (void) LogMagickEvent(CoderEvent,GetMagickModule(),
1128         "MATLAB_HDR.CellType: %.20g",(double) CellType);
1129
1130     /* data size */
1131     if (ReadBlob(image2, 4, (unsigned char *) &size) != 4)
1132       goto MATLAB_KO;
1133
1134     NEXT_FRAME:
1135     switch (CellType)
1136     {
1137       case miINT8:
1138       case miUINT8:
1139         sample_size = 8;
1140         if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
1141           image->depth = 1;
1142         else
1143           image->depth = 8;         /* Byte type cell */
1144         ldblk = (ssize_t) MATLAB_HDR.SizeX;
1145         break;
1146       case miINT16:
1147       case miUINT16:
1148         sample_size = 16;
1149         image->depth = 16;        /* Word type cell */
1150         ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
1151         break;
1152       case miINT32:
1153       case miUINT32:
1154         sample_size = 32;
1155         image->depth = 32;        /* Dword type cell */
1156         ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
1157         break;
1158       case miINT64:
1159       case miUINT64:
1160         sample_size = 64;
1161         image->depth = 64;        /* Qword type cell */
1162         ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
1163         break;
1164       case miSINGLE:
1165         sample_size = 32;
1166         image->depth = 32;        /* double type cell */
1167         (void) SetImageOption(clone_info,"quantum:format","floating-point");
1168         if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
1169           {              /* complex float type cell */
1170           }
1171         ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
1172         break;
1173       case miDOUBLE:
1174         sample_size = 64;
1175         image->depth = 64;        /* double type cell */
1176         (void) SetImageOption(clone_info,"quantum:format","floating-point");
1177 DisableMSCWarning(4127)
1178         if (sizeof(double) != 8)
1179 RestoreMSCWarning
1180           {
1181             if (clone_info != (ImageInfo *) NULL)
1182               clone_info=DestroyImageInfo(clone_info);
1183             if ((image != image2) && (image2 != (Image *) NULL))
1184               image2=DestroyImage(image2);
1185             ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
1186           }
1187         if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
1188           {                         /* complex double type cell */
1189           }
1190         ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
1191         break;
1192       default:
1193         if ((image != image2) && (image2 != (Image *) NULL))
1194           image2=DestroyImage(image2);
1195         if (clone_info)
1196           clone_info=DestroyImageInfo(clone_info);
1197         ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
1198     }
1199     (void) sample_size;
1200     image->columns = MATLAB_HDR.SizeX;
1201     image->rows = MATLAB_HDR.SizeY;
1202     image->colors = GetQuantumRange(image->depth);
1203     if (image->columns == 0 || image->rows == 0)
1204       goto MATLAB_KO;
1205     if((unsigned int)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
1206       goto MATLAB_KO;
1207     /* Image is gray when no complex flag is set and 2D Matrix */
1208     if ((MATLAB_HDR.DimFlag == 8) &&
1209         ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
1210       {
1211         image->type=GrayscaleType;
1212         SetImageColorspace(image,GRAYColorspace,exception);
1213       }
1214
1215
1216     /*
1217       If ping is true, then only set image size and colors without
1218       reading any image data.
1219     */
1220     if (image_info->ping)
1221     {
1222       size_t temp = image->columns;
1223       image->columns = image->rows;
1224       image->rows = temp;
1225       goto done_reading; /* !!!!!! BAD  !!!! */
1226     }
1227     status=SetImageExtent(image,image->columns,image->rows,exception);
1228     if (status == MagickFalse)
1229       {
1230         if (clone_info != (ImageInfo *) NULL)
1231           clone_info=DestroyImageInfo(clone_info);
1232         if ((image != image2) && (image2 != (Image *) NULL))
1233           image2=DestroyImage(image2);
1234         return(DestroyImageList(image));
1235       }
1236     (void) SetImageBackgroundColor(image,exception);
1237     quantum_info=AcquireQuantumInfo(clone_info,image);
1238     if (quantum_info == (QuantumInfo *) NULL)
1239       {
1240         if (clone_info != (ImageInfo *) NULL)
1241           clone_info=DestroyImageInfo(clone_info);
1242         if ((image != image2) && (image2 != (Image *) NULL))
1243           image2=DestroyImage(image2);
1244         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1245       }
1246
1247   /* ----- Load raster data ----- */
1248     BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double));    /* Ldblk was set in the check phase */
1249     if (BImgBuff == NULL)
1250       {
1251         if (clone_info != (ImageInfo *) NULL)
1252           clone_info=DestroyImageInfo(clone_info);
1253         if ((image != image2) && (image2 != (Image *) NULL))
1254           image2=DestroyImage(image2);
1255         if (quantum_info != (QuantumInfo *) NULL)
1256           quantum_info=DestroyQuantumInfo(quantum_info);
1257         ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
1258       }
1259     (void) memset(BImgBuff,0,ldblk*sizeof(double));
1260
1261     MinVal = 0;
1262     MaxVal = 0;
1263     if (CellType==miDOUBLE || CellType==miSINGLE)        /* Find Min and Max Values for floats */
1264       {
1265         CalcMinMax(image2,image_info->endian,MATLAB_HDR.SizeX,MATLAB_HDR.SizeY,
1266           CellType,ldblk,BImgBuff,&quantum_info->minimum,
1267           &quantum_info->maximum);
1268       }
1269
1270     /* Main loop for reading all scanlines */
1271     if(z==1) z=0; /* read grey scanlines */
1272     /* else read color scanlines */
1273     do
1274     {
1275       for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
1276       {
1277         q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
1278         if (q == (Quantum *) NULL)
1279           {
1280             if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
1281               "  MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
1282             goto done_reading;    /* Skip image rotation, when cannot set image pixels    */
1283           }
1284         if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
1285           {
1286             if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
1287               "  MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
1288            if ((image != image2) && (image2 != (Image *) NULL))
1289               image2=DestroyImage(image2);
1290             if (clone_info != (ImageInfo *) NULL)
1291               clone_info=DestroyImageInfo(clone_info);
1292             if (quantum_info != (QuantumInfo *) NULL)
1293               quantum_info=DestroyQuantumInfo(quantum_info);
1294             BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
1295             ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
1296           }
1297         if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
1298         {
1299           FixLogical((unsigned char *)BImgBuff,ldblk);
1300           if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
1301             {
1302 ImportQuantumPixelsFailed:
1303               if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
1304                 "  MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
1305               break;
1306             }
1307         }
1308         else
1309         {
1310           if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
1311             goto ImportQuantumPixelsFailed;
1312
1313
1314           if (z<=1 &&       /* fix only during a last pass z==0 || z==1 */
1315              (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
1316             FixSignedValues(image,q,MATLAB_HDR.SizeX);
1317         }
1318
1319         if (!SyncAuthenticPixels(image,exception))
1320           {
1321             if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
1322               "  MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
1323             goto ExitLoop;
1324           }
1325       }
1326     } while(z-- >= 2);
1327 ExitLoop:
1328     if (i != (long) MATLAB_HDR.SizeY)
1329       goto END_OF_READING;
1330
1331     /* Read complex part of numbers here */
1332     if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
1333     {        /* Find Min and Max Values for complex parts of floats */
1334       CellType = ReadBlobXXXLong(image2);    /* Additional object type */
1335       i = ReadBlobXXXLong(image2);           /* size of a complex part - toss away*/
1336
1337       if (CellType==miDOUBLE || CellType==miSINGLE)
1338       {
1339         CalcMinMax(image2,  image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
1340       }
1341
1342       if (CellType==miDOUBLE)
1343         for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
1344         {
1345           ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
1346           if (EOFBlob(image) != MagickFalse)
1347             break;
1348           InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
1349             exception);
1350         }
1351
1352       if (CellType==miSINGLE)
1353         for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
1354         {
1355           ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
1356           if (EOFBlob(image) != MagickFalse)
1357             break;
1358           InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
1359             exception);
1360         }
1361     }
1362
1363       /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
1364     if ((MATLAB_HDR.DimFlag == 8) &&
1365         ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
1366       image->type=GrayscaleType;
1367     if (image->depth == 1)
1368       image->type=BilevelType;
1369
1370     if(image2==image)
1371         image2 = NULL;    /* Remove shadow copy to an image before rotation. */
1372
1373       /*  Rotate image. */
1374     rotated_image = RotateImage(image, 90.0, exception);
1375     if (rotated_image != (Image *) NULL)
1376     {
1377         /* Remove page offsets added by RotateImage */
1378       rotated_image->page.x=0;
1379       rotated_image->page.y=0;
1380       rotated_image->colors = image->colors;
1381       DestroyBlob(rotated_image);
1382       rotated_image->blob=ReferenceBlob(image->blob);
1383       AppendImageToList(&image,rotated_image);
1384       DeleteImageFromList(&image);
1385     }
1386
1387 done_reading:
1388
1389     if(image2!=NULL)
1390       if(image2!=image)
1391       {
1392         DeleteImageFromList(&image2);
1393         if(clone_info)
1394         {
1395           if(clone_info->file)
1396           {
1397             fclose(clone_info->file);
1398             clone_info->file = NULL;
1399             (void) remove_utf8(clone_info->filename);
1400           }
1401         }
1402       }
1403     if (EOFBlob(image) != MagickFalse)
1404       break;
1405
1406       /* Allocate next image structure. */
1407     if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
1408       if (image->scene >= (image_info->scene+image_info->number_scenes-1))
1409         break;
1410     AcquireNextImage(image_info,image,exception);
1411     if (image->next == (Image *) NULL) break;
1412     image=SyncNextImageInList(image);
1413     image->columns=image->rows=0;
1414     image->colors=0;
1415
1416       /* row scan buffer is no longer needed */
1417     RelinquishMagickMemory(BImgBuff);
1418     BImgBuff = NULL;
1419     if (quantum_info != (QuantumInfo *) NULL)
1420       quantum_info=DestroyQuantumInfo(quantum_info);
1421
1422     if(--Frames>0)
1423     {
1424       z = z2;
1425       if(image2==NULL) image2 = image;
1426       if(!EOFBlob(image) && TellBlob(image)<filepos)
1427         goto NEXT_FRAME;
1428     }
1429     if ((image2!=NULL) && (image2!=image))   /* Does shadow temporary decompressed image exist? */
1430       {
1431 /*  CloseBlob(image2); */
1432         DeleteImageFromList(&image2);
1433         if(clone_info)
1434         {
1435           if(clone_info->file)
1436           {
1437             fclose(clone_info->file);
1438             clone_info->file = NULL;
1439             (void) remove_utf8(clone_info->filename);
1440           }
1441         }
1442       }
1443
1444     if (clone_info)
1445       clone_info=DestroyImageInfo(clone_info);
1446   }
1447
1448 END_OF_READING:
1449   RelinquishMagickMemory(BImgBuff);
1450   if (quantum_info != (QuantumInfo *) NULL)
1451     quantum_info=DestroyQuantumInfo(quantum_info);
1452   CloseBlob(image);
1453
1454
1455   {
1456     Image *p;
1457     ssize_t scene=0;
1458
1459     /*
1460       Rewind list, removing any empty images while rewinding.
1461     */
1462     p=image;
1463     image=NULL;
1464     while (p != (Image *) NULL)
1465       {
1466         Image *tmp=p;
1467         if ((p->rows == 0) || (p->columns == 0)) {
1468           p=p->previous;
1469           if (tmp == image2)
1470             image2=(Image *) NULL;
1471           DeleteImageFromList(&tmp);
1472         } else {
1473           image=p;
1474           p=p->previous;
1475         }
1476       }
1477
1478     /*
1479       Fix scene numbers
1480     */
1481     for (p=image; p != (Image *) NULL; p=p->next)
1482       p->scene=scene++;
1483   }
1484
1485   if(clone_info != NULL)  /* cleanup garbage file from compression */
1486   {
1487     if(clone_info->file)
1488     {
1489       fclose(clone_info->file);
1490       clone_info->file = NULL;
1491       (void) remove_utf8(clone_info->filename);
1492     }
1493     DestroyImageInfo(clone_info);
1494     clone_info = NULL;
1495   }
1496   if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
1497   if ((image != image2) && (image2 != (Image *) NULL))
1498     image2=DestroyImage(image2);
1499   if (image == (Image *) NULL)
1500     ThrowReaderException(CorruptImageError,"ImproperImageHeader")
1501   return(image);
1502 }
1503 \f
1504 /*
1505 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1506 %                                                                             %
1507 %                                                                             %
1508 %                                                                             %
1509 %   R e g i s t e r M A T I m a g e                                           %
1510 %                                                                             %
1511 %                                                                             %
1512 %                                                                             %
1513 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1514 %
1515 %  Method RegisterMATImage adds attributes for the MAT image format to
1516 %  the list of supported formats.  The attributes include the image format
1517 %  tag, a method to read and/or write the format, whether the format
1518 %  supports the saving of more than one frame to the same file or blob,
1519 %  whether the format supports native in-memory I/O, and a brief
1520 %  description of the format.
1521 %
1522 %  The format of the RegisterMATImage method is:
1523 %
1524 %      size_t RegisterMATImage(void)
1525 %
1526 */
1527 ModuleExport size_t RegisterMATImage(void)
1528 {
1529   MagickInfo
1530     *entry;
1531
1532   entry=AcquireMagickInfo("MAT","MAT","MATLAB level 5 image format");
1533   entry->decoder=(DecodeImageHandler *) ReadMATImage;
1534   entry->encoder=(EncodeImageHandler *) WriteMATImage;
1535   entry->flags^=CoderBlobSupportFlag;
1536   entry->flags|=CoderDecoderSeekableStreamFlag;
1537   (void) RegisterMagickInfo(entry);
1538   return(MagickImageCoderSignature);
1539 }
1540 \f
1541 /*
1542 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1543 %                                                                             %
1544 %                                                                             %
1545 %                                                                             %
1546 %   U n r e g i s t e r M A T I m a g e                                       %
1547 %                                                                             %
1548 %                                                                             %
1549 %                                                                             %
1550 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1551 %
1552 %  Method UnregisterMATImage removes format registrations made by the
1553 %  MAT module from the list of supported formats.
1554 %
1555 %  The format of the UnregisterMATImage method is:
1556 %
1557 %      UnregisterMATImage(void)
1558 %
1559 */
1560 ModuleExport void UnregisterMATImage(void)
1561 {
1562   (void) UnregisterMagickInfo("MAT");
1563 }
1564 \f
1565 /*
1566 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1567 %                                                                             %
1568 %                                                                             %
1569 %                                                                             %
1570 %   W r i t e M A T L A B I m a g e                                           %
1571 %                                                                             %
1572 %                                                                             %
1573 %                                                                             %
1574 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1575 %
1576 %  Function WriteMATImage writes an Matlab matrix to a file.
1577 %
1578 %  The format of the WriteMATImage method is:
1579 %
1580 %      MagickBooleanType WriteMATImage(const ImageInfo *image_info,
1581 %        Image *image,ExceptionInfo *exception)
1582 %
1583 %  A description of each parameter follows.
1584 %
1585 %    o image_info: Specifies a pointer to a ImageInfo structure.
1586 %
1587 %    o image:  A pointer to an Image structure.
1588 %
1589 %    o exception: return any errors or warnings in this structure.
1590 %
1591 */
1592 static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image,
1593   ExceptionInfo *exception)
1594 {
1595   char
1596     MATLAB_HDR[0x80];
1597
1598   MagickBooleanType
1599     status;
1600
1601   MagickOffsetType
1602     scene;
1603
1604   size_t
1605     imageListLength;
1606
1607   struct tm
1608     utc_time;
1609
1610   time_t
1611     current_time;
1612
1613   /*
1614     Open output image file.
1615   */
1616   assert(image_info != (const ImageInfo *) NULL);
1617   assert(image_info->signature == MagickCoreSignature);
1618   assert(image != (Image *) NULL);
1619   assert(image->signature == MagickCoreSignature);
1620   (void) LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
1621   assert(exception != (ExceptionInfo *) NULL);
1622   assert(exception->signature == MagickCoreSignature);
1623   status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
1624   if (status == MagickFalse)
1625     return(MagickFalse);
1626   image->depth=8;
1627
1628   current_time=GetMagickTime();
1629   GetMagickUTCtime(&current_time,&utc_time);
1630   (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
1631   FormatLocaleString(MATLAB_HDR,sizeof(MATLAB_HDR),
1632     "MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
1633     OsDesc,DayOfWTab[utc_time.tm_wday],MonthsTab[utc_time.tm_mon],
1634     utc_time.tm_mday,utc_time.tm_hour,utc_time.tm_min,
1635     utc_time.tm_sec,utc_time.tm_year+1900);
1636   MATLAB_HDR[0x7C]=0;
1637   MATLAB_HDR[0x7D]=1;
1638   MATLAB_HDR[0x7E]='I';
1639   MATLAB_HDR[0x7F]='M';
1640   (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
1641   scene=0;
1642   imageListLength=GetImageListLength(image);
1643   do
1644   {
1645     char
1646       padding;
1647
1648     MagickBooleanType
1649       is_gray;
1650
1651     QuantumInfo
1652       *quantum_info;
1653
1654     size_t
1655       data_size;
1656
1657     unsigned char
1658       *pixels;
1659
1660     unsigned int
1661       z;
1662
1663     (void) TransformImageColorspace(image,sRGBColorspace,exception);
1664     is_gray=SetImageGray(image,exception);
1665     z=(is_gray != MagickFalse) ? 0 : 3;
1666
1667     /*
1668       Store MAT header.
1669     */
1670     data_size = image->rows * image->columns;
1671     if (is_gray == MagickFalse)
1672       data_size*=3;
1673     padding=((unsigned char)(data_size-1) & 0x7) ^ 0x7;
1674
1675     (void) WriteBlobLSBLong(image,miMATRIX);
1676     (void) WriteBlobLSBLong(image,(unsigned int) data_size+padding+
1677       ((is_gray != MagickFalse) ? 48 : 56));
1678     (void) WriteBlobLSBLong(image,0x6); /* 0x88 */
1679     (void) WriteBlobLSBLong(image,0x8); /* 0x8C */
1680     (void) WriteBlobLSBLong(image,0x6); /* 0x90 */
1681     (void) WriteBlobLSBLong(image,0);
1682     (void) WriteBlobLSBLong(image,0x5); /* 0x98 */
1683     (void) WriteBlobLSBLong(image,(is_gray != MagickFalse) ? 0x8 : 0xC); /* 0x9C - DimFlag */
1684     (void) WriteBlobLSBLong(image,(unsigned int) image->rows);    /* x: 0xA0 */
1685     (void) WriteBlobLSBLong(image,(unsigned int) image->columns); /* y: 0xA4 */
1686     if (is_gray == MagickFalse)
1687       {
1688         (void) WriteBlobLSBLong(image,3); /* z: 0xA8 */
1689         (void) WriteBlobLSBLong(image,0);
1690       }
1691     (void) WriteBlobLSBShort(image,1);  /* 0xB0 */
1692     (void) WriteBlobLSBShort(image,1);  /* 0xB2 */
1693     (void) WriteBlobLSBLong(image,'M'); /* 0xB4 */
1694     (void) WriteBlobLSBLong(image,0x2); /* 0xB8 */
1695     (void) WriteBlobLSBLong(image,(unsigned int) data_size); /* 0xBC */
1696
1697     /*
1698       Store image data.
1699     */
1700     quantum_info=AcquireQuantumInfo(image_info,image);
1701     if (quantum_info == (QuantumInfo *) NULL)
1702       ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1703     pixels=(unsigned char *) GetQuantumPixels(quantum_info);
1704     do
1705     {
1706       const Quantum
1707         *p;
1708
1709       ssize_t
1710         y;
1711
1712       for (y=0; y < (ssize_t) image->columns; y++)
1713       {
1714         size_t
1715           length;
1716
1717         p=GetVirtualPixels(image,y,0,1,image->rows,exception);
1718         if (p == (const Quantum *) NULL)
1719           break;
1720         length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
1721           z2qtype[z],pixels,exception);
1722         if (length != image->columns)
1723           break;
1724         if (WriteBlob(image,image->rows,pixels) != (ssize_t) image->rows)
1725           break;
1726       }
1727       if (y < (ssize_t) image->columns)
1728         break;
1729       if (SyncAuthenticPixels(image,exception) == MagickFalse)
1730         break;
1731     } while (z-- >= 2);
1732     while (padding-- > 0)
1733       (void) WriteBlobByte(image,0);
1734     quantum_info=DestroyQuantumInfo(quantum_info);
1735     if (GetNextImageInList(image) == (Image *) NULL)
1736       break;
1737     image=SyncNextImageInList(image);
1738     status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
1739     if (status == MagickFalse)
1740       break;
1741   } while (image_info->adjoin != MagickFalse);
1742   (void) CloseBlob(image);
1743   return(status);
1744 }