blob: 63ab2947a117390f63f88e55bf1f5eb6b2f20227 [file] [log] [blame]
cristy3ed852e2009-09-05 21:47:34 +00001/*
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 "magick/studio.h"
51#include "magick/blob.h"
52#include "magick/blob-private.h"
53#include "magick/cache.h"
54#include "magick/color-private.h"
cristye20ffe52010-04-24 23:51:41 +000055#include "magick/colormap.h"
cristy3ed852e2009-09-05 21:47:34 +000056#include "magick/exception.h"
57#include "magick/exception-private.h"
58#include "magick/image.h"
59#include "magick/image-private.h"
60#include "magick/list.h"
61#include "magick/magick.h"
62#include "magick/memory_.h"
63#include "magick/monitor.h"
64#include "magick/monitor-private.h"
65#include "magick/quantum-private.h"
66#include "magick/option.h"
67#include "magick/resource_.h"
68#include "magick/shear.h"
69#include "magick/static.h"
70#include "magick/string_.h"
71#include "magick/module.h"
72#include "magick/transform.h"
73#if defined(MAGICKCORE_ZLIB_DELEGATE)
74 #include "zlib.h"
75#endif
76
77/*
78 Forward declaration.
79*/
80static MagickBooleanType
81 WriteMATImage(const ImageInfo *,Image *);
82
83
84/* Auto coloring method, sorry this creates some artefact inside data
85MinReal+j*MaxComplex = red MaxReal+j*MaxComplex = black
86MinReal+j*0 = white MaxReal+j*0 = black
87MinReal+j*MinComplex = blue MaxReal+j*MinComplex = black
88*/
89
90typedef struct
91{
92 char identific[124];
93 unsigned short Version;
94 char EndianIndicator[2];
cristyf6fe0a12010-05-30 00:44:47 +000095 unsigned long DataType;
96 unsigned long ObjectSize;
97 unsigned long unknown1;
98 unsigned long unknown2;
cristy3ed852e2009-09-05 21:47:34 +000099
100 unsigned short unknown5;
101 unsigned char StructureFlag;
102 unsigned char StructureClass;
cristyf6fe0a12010-05-30 00:44:47 +0000103 unsigned long unknown3;
104 unsigned long unknown4;
105 unsigned long DimFlag;
cristy3ed852e2009-09-05 21:47:34 +0000106
cristyf6fe0a12010-05-30 00:44:47 +0000107 unsigned long SizeX;
108 unsigned long SizeY;
cristy3ed852e2009-09-05 21:47:34 +0000109 unsigned short Flag1;
110 unsigned short NameFlag;
111}
112MATHeader;
113
114static const char *MonthsTab[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
115static const char *DayOfWTab[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
116static const char *OsDesc=
117#ifdef __WIN32__
118 "PCWIN";
119#else
120 #ifdef __APPLE__
121 "MAC";
122 #else
123 "LNX86";
124 #endif
125#endif
126
127typedef enum
128 {
cristyc5de6992009-10-06 19:19:48 +0000129 miINT8 = 1, /* 8 bit signed */
130 miUINT8, /* 8 bit unsigned */
131 miINT16, /* 16 bit signed */
132 miUINT16, /* 16 bit unsigned */
133 miINT32, /* 32 bit signed */
134 miUINT32, /* 32 bit unsigned */
135 miSINGLE, /* IEEE 754 single precision float */
cristy3ed852e2009-09-05 21:47:34 +0000136 miRESERVE1,
cristyc5de6992009-10-06 19:19:48 +0000137 miDOUBLE, /* IEEE 754 double precision float */
cristy3ed852e2009-09-05 21:47:34 +0000138 miRESERVE2,
139 miRESERVE3,
cristyc5de6992009-10-06 19:19:48 +0000140 miINT64, /* 64 bit signed */
141 miUINT64, /* 64 bit unsigned */
142 miMATRIX, /* MATLAB array */
143 miCOMPRESSED, /* Compressed Data */
144 miUTF8, /* Unicode UTF-8 Encoded Character Data */
145 miUTF16, /* Unicode UTF-16 Encoded Character Data */
146 miUTF32 /* Unicode UTF-32 Encoded Character Data */
cristy3ed852e2009-09-05 21:47:34 +0000147 } mat5_data_type;
148
149typedef enum
150 {
cristyc5de6992009-10-06 19:19:48 +0000151 mxCELL_CLASS=1, /* cell array */
152 mxSTRUCT_CLASS, /* structure */
153 mxOBJECT_CLASS, /* object */
154 mxCHAR_CLASS, /* character array */
155 mxSPARSE_CLASS, /* sparse array */
156 mxDOUBLE_CLASS, /* double precision array */
157 mxSINGLE_CLASS, /* single precision floating point */
158 mxINT8_CLASS, /* 8 bit signed integer */
159 mxUINT8_CLASS, /* 8 bit unsigned integer */
160 mxINT16_CLASS, /* 16 bit signed integer */
161 mxUINT16_CLASS, /* 16 bit unsigned integer */
162 mxINT32_CLASS, /* 32 bit signed integer */
163 mxUINT32_CLASS, /* 32 bit unsigned integer */
164 mxINT64_CLASS, /* 64 bit signed integer */
165 mxUINT64_CLASS, /* 64 bit unsigned integer */
cristy3ed852e2009-09-05 21:47:34 +0000166 mxFUNCTION_CLASS /* Function handle */
167 } arrayclasstype;
168
169#define FLAG_COMPLEX 0x8
170#define FLAG_GLOBAL 0x4
171#define FLAG_LOGICAL 0x2
172
173static const QuantumType z2qtype[4] = {GrayQuantum, BlueQuantum, GreenQuantum, RedQuantum};
174
175
176static void InsertComplexDoubleRow(double *p, int y, Image * image, double MinVal,
177 double MaxVal)
178{
179 ExceptionInfo
180 *exception;
181
182 double f;
183 int x;
184 register PixelPacket *q;
185
186 if (MinVal == 0)
187 MinVal = -1;
188 if (MaxVal == 0)
189 MaxVal = 1;
190
191 exception=(&image->exception);
192 q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
193 if (q == (PixelPacket *) NULL)
194 return;
cristybb503372010-05-27 20:51:26 +0000195 for (x = 0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +0000196 {
197 if (*p > 0)
198 {
199 f = (*p / MaxVal) * (QuantumRange - q->red);
200 if (f + q->red > QuantumRange)
201 q->red = QuantumRange;
202 else
203 q->red += (int) f;
204 if ((int) f / 2.0 > q->green)
205 q->green = q->blue = 0;
206 else
207 q->green = q->blue -= (int) (f / 2.0);
208 }
209 if (*p < 0)
210 {
211 f = (*p / MaxVal) * (QuantumRange - q->blue);
212 if (f + q->blue > QuantumRange)
213 q->blue = QuantumRange;
214 else
215 q->blue += (int) f;
216 if ((int) f / 2.0 > q->green)
217 q->green = q->red = 0;
218 else
219 q->green = q->red -= (int) (f / 2.0);
220 }
221 p++;
222 q++;
223 }
224 if (!SyncAuthenticPixels(image,exception))
225 return;
cristy3ed852e2009-09-05 21:47:34 +0000226 return;
227}
228
229
230static void InsertComplexFloatRow(float *p, int y, Image * image, double MinVal,
231 double MaxVal)
232{
233 ExceptionInfo
234 *exception;
235
236 double f;
237 int x;
238 register PixelPacket *q;
239
240 if (MinVal == 0)
241 MinVal = -1;
242 if (MaxVal == 0)
243 MaxVal = 1;
244
245 exception=(&image->exception);
246 q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
247 if (q == (PixelPacket *) NULL)
248 return;
cristybb503372010-05-27 20:51:26 +0000249 for (x = 0; x < (ssize_t) image->columns; x++)
cristy3ed852e2009-09-05 21:47:34 +0000250 {
251 if (*p > 0)
252 {
253 f = (*p / MaxVal) * (QuantumRange - q->red);
254 if (f + q->red > QuantumRange)
255 q->red = QuantumRange;
256 else
257 q->red += (int) f;
258 if ((int) f / 2.0 > q->green)
259 q->green = q->blue = 0;
260 else
261 q->green = q->blue -= (int) (f / 2.0);
262 }
263 if (*p < 0)
264 {
265 f = (*p / MaxVal) * (QuantumRange - q->blue);
266 if (f + q->blue > QuantumRange)
267 q->blue = QuantumRange;
268 else
269 q->blue += (int) f;
270 if ((int) f / 2.0 > q->green)
271 q->green = q->red = 0;
272 else
273 q->green = q->red -= (int) (f / 2.0);
274 }
275 p++;
276 q++;
277 }
278 if (!SyncAuthenticPixels(image,exception))
279 return;
cristy3ed852e2009-09-05 21:47:34 +0000280 return;
281}
282
283
284/************** READERS ******************/
285
286/* This function reads one block of floats*/
287static void ReadBlobFloatsLSB(Image * image, size_t len, float *data)
288{
289 while (len >= 4)
290 {
291 *data++ = ReadBlobFloat(image);
292 len -= sizeof(float);
293 }
294 if (len > 0)
295 (void) SeekBlob(image, len, SEEK_CUR);
296}
297
298static void ReadBlobFloatsMSB(Image * image, size_t len, float *data)
299{
300 while (len >= 4)
301 {
302 *data++ = ReadBlobFloat(image);
303 len -= sizeof(float);
304 }
305 if (len > 0)
306 (void) SeekBlob(image, len, SEEK_CUR);
307}
308
309/* This function reads one block of doubles*/
310static void ReadBlobDoublesLSB(Image * image, size_t len, double *data)
311{
312 while (len >= 8)
313 {
314 *data++ = ReadBlobDouble(image);
315 len -= sizeof(double);
316 }
317 if (len > 0)
318 (void) SeekBlob(image, len, SEEK_CUR);
319}
320
321static void ReadBlobDoublesMSB(Image * image, size_t len, double *data)
322{
323 while (len >= 8)
324 {
325 *data++ = ReadBlobDouble(image);
326 len -= sizeof(double);
327 }
328 if (len > 0)
329 (void) SeekBlob(image, len, SEEK_CUR);
330}
331
332/* Calculate minimum and maximum from a given block of data */
cristybb503372010-05-27 20:51:26 +0000333static void CalcMinMax(Image *image, int endian_indicator, int SizeX, int SizeY, size_t CellType, unsigned ldblk, void *BImgBuff, double *Min, double *Max)
cristy3ed852e2009-09-05 21:47:34 +0000334{
335MagickOffsetType filepos;
336int i, x;
337void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
338void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
339double *dblrow;
340float *fltrow;
341
342 if (endian_indicator == LSBEndian)
343 {
344 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
345 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
346 }
cristyc5de6992009-10-06 19:19:48 +0000347 else /* MI */
cristy3ed852e2009-09-05 21:47:34 +0000348 {
349 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
350 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
351 }
352
cristyc5de6992009-10-06 19:19:48 +0000353 filepos = TellBlob(image); /* Please note that file seeking occurs only in the case of doubles */
cristy3ed852e2009-09-05 21:47:34 +0000354 for (i = 0; i < SizeY; i++)
355 {
356 if (CellType==miDOUBLE)
357 {
358 ReadBlobDoublesXXX(image, ldblk, (double *)BImgBuff);
359 dblrow = (double *)BImgBuff;
360 if (i == 0)
361 {
362 *Min = *Max = *dblrow;
363 }
364 for (x = 0; x < SizeX; x++)
365 {
366 if (*Min > *dblrow)
367 *Min = *dblrow;
368 if (*Max < *dblrow)
369 *Max = *dblrow;
370 dblrow++;
371 }
372 }
373 if (CellType==miSINGLE)
374 {
375 ReadBlobFloatsXXX(image, ldblk, (float *)BImgBuff);
376 fltrow = (float *)BImgBuff;
377 if (i == 0)
378 {
379 *Min = *Max = *fltrow;
380 }
cristybb503372010-05-27 20:51:26 +0000381 for (x = 0; x < (ssize_t) SizeX; x++)
cristy3ed852e2009-09-05 21:47:34 +0000382 {
383 if (*Min > *fltrow)
384 *Min = *fltrow;
385 if (*Max < *fltrow)
386 *Max = *fltrow;
387 fltrow++;
388 }
389 }
390 }
391 (void) SeekBlob(image, filepos, SEEK_SET);
392}
393
394
395static void FixSignedValues(PixelPacket *q, int y)
396{
397 while(y-->0)
398 {
399 /* Please note that negative values will overflow
400 Q=8; QuantumRange=255: <0;127> + 127+1 = <128; 255>
cristyc5de6992009-10-06 19:19:48 +0000401 <-1;-128> + 127+1 = <0; 127> */
cristy3ed852e2009-09-05 21:47:34 +0000402 q->red += QuantumRange/2 + 1;
403 q->green += QuantumRange/ + 1;
404 q->blue += QuantumRange/ + 1;
405 q++;
406 }
407}
408
409
410/** Fix whole row of logical/binary data. It means pack it. */
411static void FixLogical(unsigned char *Buff,int ldblk)
412{
413unsigned char mask=128;
414unsigned char *BuffL = Buff;
415unsigned char val = 0;
416
417 while(ldblk-->0)
418 {
419 if(*Buff++ != 0)
420 val |= mask;
421
422 mask >>= 1;
423 if(mask==0)
424 {
425 *BuffL++ = val;
426 val = 0;
427 mask = 128;
428 }
429
430 }
431 *BuffL = val;
432}
433
434#if defined(MAGICKCORE_ZLIB_DELEGATE)
435static voidpf AcquireZIPMemory(voidpf context,unsigned int items,
436 unsigned int size)
437{
438 (void) context;
439 return((voidpf) AcquireQuantumMemory(items,size));
440}
441
442static void RelinquishZIPMemory(voidpf context,voidpf memory)
443{
444 (void) context;
445 memory=RelinquishMagickMemory(memory);
446}
447#endif
448
449/** This procedure decompreses an image block for a new MATLAB format. */
450static Image *DecompressBlock(Image *orig, MagickOffsetType Size, ImageInfo *clone_info, ExceptionInfo *exception)
451{
452#if defined(MAGICKCORE_ZLIB_DELEGATE)
453
454Image *image2;
455void *CacheBlock, *DecompressBlock;
456z_stream zip_info;
457FILE *mat_file;
458size_t magick_size;
cristy95236b52009-12-30 21:56:45 +0000459size_t extent;
cristy3ed852e2009-09-05 21:47:34 +0000460
461int status;
462
463 if(clone_info==NULL) return NULL;
cristyc5de6992009-10-06 19:19:48 +0000464 if(clone_info->file) /* Close file opened from previous transaction. */
cristy3ed852e2009-09-05 21:47:34 +0000465 {
466 fclose(clone_info->file);
467 clone_info->file = NULL;
468 (void) unlink(clone_info->filename);
469 }
470
471 CacheBlock = AcquireQuantumMemory((size_t)((Size<16384)?Size:16384),sizeof(unsigned char *));
472 if(CacheBlock==NULL) return NULL;
473 DecompressBlock = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
474 if(DecompressBlock==NULL)
475 {
476 RelinquishMagickMemory(CacheBlock);
477 return NULL;
478 }
479
480 mat_file = fdopen(AcquireUniqueFileResource(clone_info->filename),"w");
481 if(!mat_file)
482 {
483 RelinquishMagickMemory(CacheBlock);
484 RelinquishMagickMemory(DecompressBlock);
485 (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Gannot create file stream for PS image");
486 return NULL;
487 }
488
489 zip_info.zalloc=AcquireZIPMemory;
490 zip_info.zfree=RelinquishZIPMemory;
491 zip_info.opaque = (voidpf) NULL;
492 inflateInit(&zip_info);
493 /* zip_info.next_out = 8*4;*/
494
495 zip_info.avail_in = 0;
496 zip_info.total_out = 0;
497 while(Size>0 && !EOFBlob(orig))
498 {
499 magick_size = ReadBlob(orig, (Size<16384)?Size:16384, (unsigned char *) CacheBlock);
500 zip_info.next_in = (Bytef *) CacheBlock;
501 zip_info.avail_in = (uInt) magick_size;
502
503 while(zip_info.avail_in>0)
504 {
505 zip_info.avail_out = 4096;
506 zip_info.next_out = (Bytef *) DecompressBlock;
507 status = inflate(&zip_info,Z_NO_FLUSH);
cristy95236b52009-12-30 21:56:45 +0000508 extent=fwrite(DecompressBlock, 4096-zip_info.avail_out, 1, mat_file);
cristy3ed852e2009-09-05 21:47:34 +0000509
510 if(status == Z_STREAM_END) goto DblBreak;
511 }
512
513 Size -= magick_size;
514 }
515DblBreak:
516
517 (void)fclose(mat_file);
518 RelinquishMagickMemory(CacheBlock);
519 RelinquishMagickMemory(DecompressBlock);
520
521 if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
522 if( (image2 = AcquireImage(clone_info))==NULL ) goto EraseFile;
523 status = OpenBlob(clone_info,image2,ReadBinaryBlobMode,exception);
524 if (status == MagickFalse)
525 {
526 DeleteImageFromList(&image2);
527EraseFile:
528 fclose(clone_info->file);
529 clone_info->file = NULL;
530UnlinkFile:
531 (void) unlink(clone_info->filename);
532 return NULL;
533 }
534
535 return image2;
536#else
537 (void) orig;
538 (void) Size;
539 (void) clone_info;
540 (void) exception;
541 return NULL;
542#endif
543}
544
545/*
546%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
547% %
548% %
549% %
550% R e a d M A T L A B i m a g e %
551% %
552% %
553% %
554%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
555%
556% ReadMATImage() reads an MAT X image file and returns it. It
557% allocates the memory necessary for the new Image structure and returns a
558% pointer to the new image.
559%
560% The format of the ReadMATImage method is:
561%
562% Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
563%
564% A description of each parameter follows:
565%
566% o image: Method ReadMATImage returns a pointer to the image after
567% reading. A null image is returned if there is a memory shortage or if
568% the image cannot be read.
569%
570% o image_info: Specifies a pointer to a ImageInfo structure.
571%
572% o exception: return any errors or warnings in this structure.
573%
574*/
575
576static inline size_t MagickMin(const size_t x,const size_t y)
577{
578 if (x < y)
579 return(x);
580 return(y);
581}
582
583static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
584{
585 Image *image, *image2=NULL,
586 *rotated_image;
587 PixelPacket *q;
588
589 unsigned int status;
590 MATHeader MATLAB_HDR;
cristybb503372010-05-27 20:51:26 +0000591 size_t size;
592 size_t CellType;
cristy3ed852e2009-09-05 21:47:34 +0000593 QuantumInfo *quantum_info;
594 ImageInfo *clone_info;
595 int i;
cristybb503372010-05-27 20:51:26 +0000596 ssize_t ldblk;
cristy3ed852e2009-09-05 21:47:34 +0000597 unsigned char *BImgBuff = NULL;
598 double MinVal, MaxVal;
cristybb503372010-05-27 20:51:26 +0000599 size_t Unknown6;
cristy3ed852e2009-09-05 21:47:34 +0000600 unsigned z;
601 int logging;
602 int sample_size;
603 MagickOffsetType filepos=0x80;
604 BlobInfo *blob;
cristyeaedf062010-05-29 22:36:02 +0000605 size_t one;
cristy3ed852e2009-09-05 21:47:34 +0000606
607 unsigned int (*ReadBlobXXXLong)(Image *image);
608 unsigned short (*ReadBlobXXXShort)(Image *image);
609 void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
610 void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
611
612
613 assert(image_info != (const ImageInfo *) NULL);
614 assert(image_info->signature == MagickSignature);
615 assert(exception != (ExceptionInfo *) NULL);
616 assert(exception->signature == MagickSignature);
617 logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
618
619 /*
620 Open image file.
621 */
622 image = AcquireImage(image_info);
623
624 status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
625 if (status == MagickFalse)
626 {
627 image=DestroyImageList(image);
628 return((Image *) NULL);
629 }
630 /*
631 Read MATLAB image.
632 */
633 clone_info=CloneImageInfo(image_info);
634 if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
635 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
636 MATLAB_HDR.Version = ReadBlobLSBShort(image);
637 if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
638 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
639
640 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
641 MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
642 if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
643 {
644 ReadBlobXXXLong = ReadBlobLSBLong;
645 ReadBlobXXXShort = ReadBlobLSBShort;
646 ReadBlobDoublesXXX = ReadBlobDoublesLSB;
647 ReadBlobFloatsXXX = ReadBlobFloatsLSB;
648 image->endian = LSBEndian;
649 }
650 else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
651 {
652 ReadBlobXXXLong = ReadBlobMSBLong;
653 ReadBlobXXXShort = ReadBlobMSBShort;
654 ReadBlobDoublesXXX = ReadBlobDoublesMSB;
655 ReadBlobFloatsXXX = ReadBlobFloatsMSB;
656 image->endian = MSBEndian;
657 }
658 else
659 goto MATLAB_KO; /* unsupported endian */
660
661 if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
662MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
663
664 filepos = TellBlob(image);
665 while(!EOFBlob(image)) /* object parser loop */
666 {
667 (void) SeekBlob(image,filepos,SEEK_SET);
668 /* printf("pos=%X\n",TellBlob(image)); */
669
670 MATLAB_HDR.DataType = ReadBlobXXXLong(image);
671 if(EOFBlob(image)) break;
672 MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
673 if(EOFBlob(image)) break;
674 filepos += MATLAB_HDR.ObjectSize + 4 + 4;
675
676 image2 = image;
677#if defined(MAGICKCORE_ZLIB_DELEGATE)
678 if(MATLAB_HDR.DataType == miCOMPRESSED)
679 {
680 image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
681 if(image2==NULL) continue;
682 MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
683 }
684#endif
685
686 if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
687
688 MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
689 MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
690
691 MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
692 MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
693 MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
694
695 MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
696 if(image!=image2)
cristyc5de6992009-10-06 19:19:48 +0000697 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
cristy3ed852e2009-09-05 21:47:34 +0000698 MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
699 MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
700 MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
701 MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
702
703
704 switch(MATLAB_HDR.DimFlag)
705 {
cristyc5de6992009-10-06 19:19:48 +0000706 case 8: z=1; break; /* 2D matrix*/
707 case 12: z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
708 Unknown6 = ReadBlobXXXLong(image2);
709 if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
710 break;
cristy3ed852e2009-09-05 21:47:34 +0000711 default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
712 }
713
714 MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
715 MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
716
717 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
718 "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
719 if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
cristyc5de6992009-10-06 19:19:48 +0000720 MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
721 MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
cristy3ed852e2009-09-05 21:47:34 +0000722 MATLAB_HDR.StructureClass != mxINT8_CLASS &&
cristyc5de6992009-10-06 19:19:48 +0000723 MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
cristy3ed852e2009-09-05 21:47:34 +0000724 MATLAB_HDR.StructureClass != mxINT16_CLASS &&
cristyc5de6992009-10-06 19:19:48 +0000725 MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
cristy3ed852e2009-09-05 21:47:34 +0000726 MATLAB_HDR.StructureClass != mxINT32_CLASS &&
cristyc5de6992009-10-06 19:19:48 +0000727 MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
cristy3ed852e2009-09-05 21:47:34 +0000728 MATLAB_HDR.StructureClass != mxINT64_CLASS &&
cristyc5de6992009-10-06 19:19:48 +0000729 MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
cristy3ed852e2009-09-05 21:47:34 +0000730 ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
731
732 switch (MATLAB_HDR.NameFlag)
733 {
734 case 0:
cristyc5de6992009-10-06 19:19:48 +0000735 size = ReadBlobXXXLong(image2); /* Object name string size */
cristybb503372010-05-27 20:51:26 +0000736 size = 4 * (ssize_t) ((size + 3 + 1) / 4);
cristy3ed852e2009-09-05 21:47:34 +0000737 (void) SeekBlob(image2, size, SEEK_CUR);
738 break;
739 case 1:
740 case 2:
741 case 3:
742 case 4:
743 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
744 break;
745 default:
746 goto MATLAB_KO;
747 }
748
749 CellType = ReadBlobXXXLong(image2); /* Additional object type */
cristyf2faecf2010-05-28 19:19:36 +0000750 if (logging)
751 (void) LogMagickEvent(CoderEvent,GetMagickModule(),
cristye8c25f92010-06-03 00:53:06 +0000752 "MATLAB_HDR.CellType: %.20g",(double) CellType);
cristy3ed852e2009-09-05 21:47:34 +0000753
754 (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
755
756 /* Image is gray when no complex flag is set and 2D Matrix */
757 if ((MATLAB_HDR.DimFlag == 8) &&
758 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
759 image->type=GrayscaleType;
760
761 switch (CellType)
762 {
763 case miINT8:
764 case miUINT8:
765 sample_size = 8;
766 if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
767 image->depth = 1;
768 else
769 image->depth = 8; /* Byte type cell */
cristybb503372010-05-27 20:51:26 +0000770 ldblk = (ssize_t) MATLAB_HDR.SizeX;
cristy3ed852e2009-09-05 21:47:34 +0000771 break;
772 case miINT16:
773 case miUINT16:
774 sample_size = 16;
775 image->depth = 16; /* Word type cell */
cristybb503372010-05-27 20:51:26 +0000776 ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
cristy3ed852e2009-09-05 21:47:34 +0000777 break;
778 case miINT32:
779 case miUINT32:
780 sample_size = 32;
781 image->depth = 32; /* Dword type cell */
cristybb503372010-05-27 20:51:26 +0000782 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
cristy3ed852e2009-09-05 21:47:34 +0000783 break;
784 case miINT64:
785 case miUINT64:
786 sample_size = 64;
787 image->depth = 64; /* Qword type cell */
cristybb503372010-05-27 20:51:26 +0000788 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
cristy3ed852e2009-09-05 21:47:34 +0000789 break;
790 case miSINGLE:
791 sample_size = 32;
792 image->depth = 32; /* double type cell */
793 (void) SetImageOption(clone_info,"quantum:format","floating-point");
794 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
cristyc5de6992009-10-06 19:19:48 +0000795 { /* complex float type cell */
796 }
cristybb503372010-05-27 20:51:26 +0000797 ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
cristy3ed852e2009-09-05 21:47:34 +0000798 break;
799 case miDOUBLE:
800 sample_size = 64;
801 image->depth = 64; /* double type cell */
802 (void) SetImageOption(clone_info,"quantum:format","floating-point");
803 if (sizeof(double) != 8)
804 ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
805 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
cristyc5de6992009-10-06 19:19:48 +0000806 { /* complex double type cell */
807 }
cristybb503372010-05-27 20:51:26 +0000808 ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
cristy3ed852e2009-09-05 21:47:34 +0000809 break;
810 default:
811 ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
812 }
813 image->columns = MATLAB_HDR.SizeX;
814 image->rows = MATLAB_HDR.SizeY;
815 quantum_info=AcquireQuantumInfo(clone_info,image);
816 if (quantum_info == (QuantumInfo *) NULL)
817 ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
cristyeaedf062010-05-29 22:36:02 +0000818 one=1;
819 image->colors = one << image->depth;
cristy3ed852e2009-09-05 21:47:34 +0000820 if (image->columns == 0 || image->rows == 0)
821 goto MATLAB_KO;
822
823 /* ----- Create gray palette ----- */
824
825 if (CellType==miUINT8 && z!=3)
826 {
827 if(image->colors>256) image->colors = 256;
828
829 if (!AcquireImageColormap(image, image->colors))
830 {
831 NoMemory:ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");}
832 }
833
834 /*
835 If ping is true, then only set image size and colors without
836 reading any image data.
837 */
838 if (image_info->ping)
839 {
cristybb503372010-05-27 20:51:26 +0000840 size_t temp = image->columns;
cristy3ed852e2009-09-05 21:47:34 +0000841 image->columns = image->rows;
842 image->rows = temp;
843 goto done_reading; /* !!!!!! BAD !!!! */
844 }
845
846 /* ----- Load raster data ----- */
847 BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(unsigned char *)); /* Ldblk was set in the check phase */
848 if (BImgBuff == NULL)
849 goto NoMemory;
850
851 MinVal = 0;
852 MaxVal = 0;
853 if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
854 {
855 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
856 }
857
858 /* Main loop for reading all scanlines */
859 if(z==1) z=0; /* read grey scanlines */
cristyc5de6992009-10-06 19:19:48 +0000860 /* else read color scanlines */
cristy3ed852e2009-09-05 21:47:34 +0000861 do
862 {
cristybb503372010-05-27 20:51:26 +0000863 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
cristy3ed852e2009-09-05 21:47:34 +0000864 {
865 q=QueueAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
866 if (q == (PixelPacket *)NULL)
cristyc5de6992009-10-06 19:19:48 +0000867 {
868 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
cristy3ed852e2009-09-05 21:47:34 +0000869 " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
cristyc5de6992009-10-06 19:19:48 +0000870 goto done_reading; /* Skip image rotation, when cannot set image pixels */
871 }
cristy3ed852e2009-09-05 21:47:34 +0000872 if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
cristyc5de6992009-10-06 19:19:48 +0000873 {
874 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
cristy3ed852e2009-09-05 21:47:34 +0000875 " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
cristyc5de6992009-10-06 19:19:48 +0000876 goto ExitLoop;
877 }
cristy3ed852e2009-09-05 21:47:34 +0000878 if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
879 {
880 FixLogical((unsigned char *)BImgBuff,ldblk);
881 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
cristyc5de6992009-10-06 19:19:48 +0000882 {
cristy3ed852e2009-09-05 21:47:34 +0000883ImportQuantumPixelsFailed:
cristyc5de6992009-10-06 19:19:48 +0000884 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
cristy3ed852e2009-09-05 21:47:34 +0000885 " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
cristyc5de6992009-10-06 19:19:48 +0000886 break;
887 }
cristy3ed852e2009-09-05 21:47:34 +0000888 }
889 else
890 {
891 if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
cristyc5de6992009-10-06 19:19:48 +0000892 goto ImportQuantumPixelsFailed;
cristy3ed852e2009-09-05 21:47:34 +0000893
894
cristyc5de6992009-10-06 19:19:48 +0000895 if (z<=1 && /* fix only during a last pass z==0 || z==1 */
896 (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
897 FixSignedValues(q,MATLAB_HDR.SizeX);
cristy3ed852e2009-09-05 21:47:34 +0000898 }
899
900 if (!SyncAuthenticPixels(image,exception))
cristyc5de6992009-10-06 19:19:48 +0000901 {
902 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
cristy3ed852e2009-09-05 21:47:34 +0000903 " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
cristyc5de6992009-10-06 19:19:48 +0000904 goto ExitLoop;
905 }
cristy3ed852e2009-09-05 21:47:34 +0000906 }
907 } while(z-- >= 2);
908ExitLoop:
909
910
911 /* Read complex part of numbers here */
912 if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
913 { /* Find Min and Max Values for complex parts of floats */
914 CellType = ReadBlobXXXLong(image2); /* Additional object type */
915 i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
916
917 if (CellType==miDOUBLE || CellType==miSINGLE)
918 {
919 CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
920 }
921
922 if (CellType==miDOUBLE)
cristybb503372010-05-27 20:51:26 +0000923 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
cristyc5de6992009-10-06 19:19:48 +0000924 {
cristy3ed852e2009-09-05 21:47:34 +0000925 ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
926 InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
cristyc5de6992009-10-06 19:19:48 +0000927 }
cristy3ed852e2009-09-05 21:47:34 +0000928
929 if (CellType==miSINGLE)
cristybb503372010-05-27 20:51:26 +0000930 for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
cristyc5de6992009-10-06 19:19:48 +0000931 {
cristy3ed852e2009-09-05 21:47:34 +0000932 ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
933 InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
cristyc5de6992009-10-06 19:19:48 +0000934 }
cristy3ed852e2009-09-05 21:47:34 +0000935 }
936
937 /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
938 if ((MATLAB_HDR.DimFlag == 8) &&
939 ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
940 image->type=GrayscaleType;
941 if (image->depth == 1)
942 image->type=BilevelType;
943
944 if(image2==image)
945 image2 = NULL; /* Remove shadow copy to an image before rotation. */
946
947 /* Rotate image. */
948 rotated_image = RotateImage(image, 90.0, exception);
949 if (rotated_image != (Image *) NULL)
950 {
951 /* Remove page offsets added by RotateImage */
952 rotated_image->page.x=0;
953 rotated_image->page.y=0;
954
955 blob = rotated_image->blob;
956 rotated_image->blob = image->blob;
957 rotated_image->colors = image->colors;
958 image->blob = blob;
959 AppendImageToList(&image,rotated_image);
960 DeleteImageFromList(&image);
961 }
962
963done_reading:
964
965 if(image2!=NULL)
966 if(image2!=image)
967 {
968 DeleteImageFromList(&image2);
cristyc5de6992009-10-06 19:19:48 +0000969 if(clone_info)
970 {
cristy3ed852e2009-09-05 21:47:34 +0000971 if(clone_info->file)
cristyc5de6992009-10-06 19:19:48 +0000972 {
cristy3ed852e2009-09-05 21:47:34 +0000973 fclose(clone_info->file);
974 clone_info->file = NULL;
975 (void) unlink(clone_info->filename);
cristyc5de6992009-10-06 19:19:48 +0000976 }
cristy3ed852e2009-09-05 21:47:34 +0000977 }
978 }
979
980 /* Allocate next image structure. */
981 AcquireNextImage(image_info,image);
982 if (image->next == (Image *) NULL) break;
983 image=SyncNextImageInList(image);
984 image->columns=image->rows=0;
985 image->colors=0;
986
cristybb503372010-05-27 20:51:26 +0000987 /* row scan buffer is no ssize_ter needed */
cristy3ed852e2009-09-05 21:47:34 +0000988 RelinquishMagickMemory(BImgBuff);
989 BImgBuff = NULL;
990 }
991 clone_info=DestroyImageInfo(clone_info);
992
993 RelinquishMagickMemory(BImgBuff);
994 CloseBlob(image);
995
996
997 {
998 Image *p;
cristybb503372010-05-27 20:51:26 +0000999 ssize_t scene=0;
cristy3ed852e2009-09-05 21:47:34 +00001000
1001 /*
1002 Rewind list, removing any empty images while rewinding.
1003 */
1004 p=image;
1005 image=NULL;
1006 while (p != (Image *)NULL)
1007 {
1008 Image *tmp=p;
1009 if ((p->rows == 0) || (p->columns == 0)) {
1010 p=p->previous;
1011 DeleteImageFromList(&tmp);
1012 } else {
1013 image=p;
1014 p=p->previous;
1015 }
1016 }
1017
1018 /*
1019 Fix scene numbers
1020 */
1021 for (p=image; p != (Image *) NULL; p=p->next)
1022 p->scene=scene++;
1023 }
1024
cristyc5de6992009-10-06 19:19:48 +00001025 if(clone_info != NULL) /* cleanup garbage file from compression */
cristy3ed852e2009-09-05 21:47:34 +00001026 {
1027 if(clone_info->file)
1028 {
1029 fclose(clone_info->file);
1030 clone_info->file = NULL;
1031 (void) unlink(clone_info->filename);
1032 }
1033 DestroyImageInfo(clone_info);
1034 clone_info = NULL;
1035 }
1036 if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
1037 if(image==NULL)
1038 ThrowReaderException(CorruptImageError,"ImproperImageHeader");
1039 return (image);
1040}
1041
1042/*
1043%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1044% %
1045% %
1046% %
1047% R e g i s t e r M A T I m a g e %
1048% %
1049% %
1050% %
1051%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1052%
1053% Method RegisterMATImage adds attributes for the MAT image format to
1054% the list of supported formats. The attributes include the image format
1055% tag, a method to read and/or write the format, whether the format
1056% supports the saving of more than one frame to the same file or blob,
1057% whether the format supports native in-memory I/O, and a brief
1058% description of the format.
1059%
1060% The format of the RegisterMATImage method is:
1061%
cristybb503372010-05-27 20:51:26 +00001062% size_t RegisterMATImage(void)
cristy3ed852e2009-09-05 21:47:34 +00001063%
1064*/
cristybb503372010-05-27 20:51:26 +00001065ModuleExport size_t RegisterMATImage(void)
cristy3ed852e2009-09-05 21:47:34 +00001066{
1067 MagickInfo
1068 *entry;
1069
1070 entry=SetMagickInfo("MAT");
1071 entry->decoder=(DecodeImageHandler *) ReadMATImage;
1072 entry->encoder=(EncodeImageHandler *) WriteMATImage;
1073 entry->blob_support=MagickFalse;
1074 entry->seekable_stream=MagickTrue;
1075 entry->description=AcquireString("MATLAB image format");
1076 entry->module=AcquireString("MAT");
1077 (void) RegisterMagickInfo(entry);
1078 return(MagickImageCoderSignature);
1079}
1080
1081/*
1082%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1083% %
1084% %
1085% %
1086% U n r e g i s t e r M A T I m a g e %
1087% %
1088% %
1089% %
1090%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1091%
1092% Method UnregisterMATImage removes format registrations made by the
1093% MAT module from the list of supported formats.
1094%
1095% The format of the UnregisterMATImage method is:
1096%
1097% UnregisterMATImage(void)
1098%
1099*/
1100ModuleExport void UnregisterMATImage(void)
1101{
1102 (void) UnregisterMagickInfo("MAT");
1103}
1104
1105/*
1106%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1107% %
1108% %
1109% %
1110% W r i t e M A T L A B I m a g e %
1111% %
1112% %
1113% %
1114%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1115%
1116% Function WriteMATImage writes an Matlab matrix to a file.
1117%
1118% The format of the WriteMATImage method is:
1119%
1120% unsigned int WriteMATImage(const ImageInfo *image_info,Image *image)
1121%
1122% A description of each parameter follows.
1123%
1124% o status: Function WriteMATImage return True if the image is written.
1125% False is returned is there is a memory shortage or if the image file
1126% fails to write.
1127%
1128% o image_info: Specifies a pointer to a ImageInfo structure.
1129%
1130% o image: A pointer to an Image structure.
1131%
1132*/
1133static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image)
1134{
1135 ExceptionInfo
1136 *exception;
1137
cristybb503372010-05-27 20:51:26 +00001138 ssize_t y;
cristy3ed852e2009-09-05 21:47:34 +00001139 unsigned z;
1140 const PixelPacket *p;
1141
1142 unsigned int status;
1143 int logging;
cristybb503372010-05-27 20:51:26 +00001144 size_t DataSize;
cristy3ed852e2009-09-05 21:47:34 +00001145 char padding;
1146 char MATLAB_HDR[0x80];
1147 time_t current_time;
1148 struct tm local_time;
1149 unsigned char *pixels;
1150 int is_gray;
1151
1152 MagickOffsetType
1153 scene;
1154
1155 QuantumInfo
1156 *quantum_info;
1157
1158 /*
1159 Open output image file.
1160 */
1161 assert(image_info != (const ImageInfo *) NULL);
1162 assert(image_info->signature == MagickSignature);
1163 assert(image != (Image *) NULL);
1164 assert(image->signature == MagickSignature);
1165 logging=LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
1166 status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
1167 if (status == MagickFalse)
1168 return(MagickFalse);
1169 image->depth=8;
1170
1171 current_time=time((time_t *) NULL);
1172#if defined(MAGICKCORE_HAVE_LOCALTIME_R)
1173 (void) localtime_r(&current_time,&local_time);
1174#else
1175 (void) memcpy(&local_time,localtime(&current_time),sizeof(local_time));
1176#endif
1177 (void) memset(MATLAB_HDR,' ',MagickMin(sizeof(MATLAB_HDR),124));
1178 FormatMagickString(MATLAB_HDR,MaxTextExtent,"MATLAB 5.0 MAT-file, Platform: %s, Created on: %s %s %2d %2d:%2d:%2d %d",
1179 OsDesc,DayOfWTab[local_time.tm_wday],MonthsTab[local_time.tm_mon],
1180 local_time.tm_mday,local_time.tm_hour,local_time.tm_min,
1181 local_time.tm_sec,local_time.tm_year+1900);
1182 MATLAB_HDR[0x7C]=0;
1183 MATLAB_HDR[0x7D]=1;
1184 MATLAB_HDR[0x7E]='I';
1185 MATLAB_HDR[0x7F]='M';
1186 (void) WriteBlob(image,sizeof(MATLAB_HDR),(unsigned char *) MATLAB_HDR);
1187 scene=0;
1188 do
1189 {
1190 if (image->colorspace != RGBColorspace)
1191 (void) TransformImageColorspace(image,RGBColorspace);
1192
1193 is_gray = IsGrayImage(image,&image->exception);
1194 z = is_gray ? 0 : 3;
1195
1196 /*
1197 Store MAT header.
1198 */
1199 DataSize = image->rows /*Y*/ * image->columns /*X*/;
1200 if(!is_gray) DataSize *= 3 /*Z*/;
1201 padding=((unsigned char)(DataSize-1) & 0x7) ^ 0x7;
1202
1203 (void) WriteBlobLSBLong(image, miMATRIX);
cristyf6fe0a12010-05-30 00:44:47 +00001204 (void) WriteBlobLSBLong(image, (unsigned int) DataSize+padding+(is_gray ? 48 : 56));
cristy3ed852e2009-09-05 21:47:34 +00001205 (void) WriteBlobLSBLong(image, 0x6); /* 0x88 */
1206 (void) WriteBlobLSBLong(image, 0x8); /* 0x8C */
1207 (void) WriteBlobLSBLong(image, 0x6); /* 0x90 */
1208 (void) WriteBlobLSBLong(image, 0);
1209 (void) WriteBlobLSBLong(image, 0x5); /* 0x98 */
1210 (void) WriteBlobLSBLong(image, is_gray ? 0x8 : 0xC); /* 0x9C - DimFlag */
cristyf6fe0a12010-05-30 00:44:47 +00001211 (void) WriteBlobLSBLong(image, (unsigned int) image->rows); /* x: 0xA0 */
1212 (void) WriteBlobLSBLong(image, (unsigned int) image->columns); /* y: 0xA4 */
cristy3ed852e2009-09-05 21:47:34 +00001213 if(!is_gray)
1214 {
1215 (void) WriteBlobLSBLong(image, 3); /* z: 0xA8 */
1216 (void) WriteBlobLSBLong(image, 0);
1217 }
1218 (void) WriteBlobLSBShort(image, 1); /* 0xB0 */
1219 (void) WriteBlobLSBShort(image, 1); /* 0xB2 */
1220 (void) WriteBlobLSBLong(image, 'M'); /* 0xB4 */
1221 (void) WriteBlobLSBLong(image, 0x2); /* 0xB8 */
cristyf6fe0a12010-05-30 00:44:47 +00001222 (void) WriteBlobLSBLong(image, (unsigned int) DataSize); /* 0xBC */
cristy3ed852e2009-09-05 21:47:34 +00001223
1224 /*
1225 Store image data.
1226 */
1227 exception=(&image->exception);
1228 quantum_info=AcquireQuantumInfo(image_info,image);
1229 if (quantum_info == (QuantumInfo *) NULL)
1230 ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
1231 pixels=GetQuantumPixels(quantum_info);
1232 do
1233 {
cristybb503372010-05-27 20:51:26 +00001234 for (y=0; y < (ssize_t)image->columns; y++)
cristy3ed852e2009-09-05 21:47:34 +00001235 {
1236 p=GetVirtualPixels(image,y,0,1,image->rows,&image->exception);
1237 if (p == (const PixelPacket *) NULL)
1238 break;
1239 (void) ExportQuantumPixels(image,(const CacheView *) NULL,quantum_info,
1240 z2qtype[z],pixels,exception);
1241 (void) WriteBlob(image,image->rows,pixels);
1242 }
1243 if (!SyncAuthenticPixels(image,exception))
1244 break;
1245 } while(z-- >= 2);
1246 while(padding-->0) (void) WriteBlobByte(image,0);
1247 quantum_info=DestroyQuantumInfo(quantum_info);
1248 if (GetNextImageInList(image) == (Image *) NULL)
1249 break;
1250 image=SyncNextImageInList(image);
1251 status=SetImageProgress(image,SaveImagesTag,scene++,
1252 GetImageListLength(image));
1253 if (status == MagickFalse)
1254 break;
1255 } while (image_info->adjoin != MagickFalse);
1256 (void) CloseBlob(image);
1257 return(MagickTrue);
1258}