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