]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
- gdcmDebug set to 0 in ordrer to avaoid some spurious outputs
[gdcm.git] / src / gdcmFile.cxx
1 // gdcmFile.cxx
2
3 #include "gdcmFile.h"
4 #include "gdcmUtil.h"
5
6
7 // TODO : remove DEBUG
8 #define DEBUG 0
9
10
11 #include "iddcmjpeg.h"
12 using namespace std;
13
14 /////////////////////////////////////////////////////////////////
15 /**
16  * \ingroup   gdcmFile
17  * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
18  *        file (see SetFileName, SetDcmTag and Write)
19  *        Opens (in read only and when possible) an existing file and checks
20  *        for DICOM compliance. Returns NULL on failure.
21  * \Note  the in-memory representation of all available tags found in
22  *        the DICOM header is post-poned to first header information access.
23  *        This avoid a double parsing of public part of the header when
24  *        one sets an a posteriori shadow dictionary (efficiency can be
25  *        seen as a side effect).   
26  *
27  * @param filename file to be opened for parsing
28  *
29  * @return      
30  */
31  
32 gdcmFile::gdcmFile(string & filename) 
33         :gdcmHeader(filename.c_str())   
34 {
35    SetPixelDataSizeFromHeader();
36 }
37
38 gdcmFile::gdcmFile(const char * filename) 
39         :gdcmHeader(filename)   
40 {
41    SetPixelDataSizeFromHeader();
42 }
43
44 /**
45  * \ingroup   gdcmFile
46  * \brief     calcule la longueur (in bytes) A ALLOUER pour recevoir les
47  *              pixels de l'image
48  *              ou DES images dans le cas d'un multiframe
49  *              ATTENTION : il ne s'agit PAS de la longueur du groupe des Pixels        
50  *              (dans le cas d'images compressees, elle n'a pas de sens).
51  *
52  * @return      longueur a allouer 
53  */
54 void gdcmFile::SetPixelDataSizeFromHeader(void) {
55    int nb;
56    string str_nb;
57
58    str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
59    if (str_nb == "gdcm::Unfound" ) {
60       nb = 16;
61    } else {
62       nb = atoi(str_nb.c_str() );
63       if (nb == 12) nb =16;
64    }
65    lgrTotale =  GetXSize() *  GetYSize() *  GetZSize() * (nb/8)* GetSamplesPerPixel();;
66 }
67
68 /////////////////////////////////////////////////////////////////
69 /**
70  * \ingroup   gdcmFile
71  * \brief     Returns the size (in bytes) of required memory to hold
72  *            the pixel data represented in this file.
73  * @return    The size of pixel data in bytes.
74  */
75 size_t gdcmFile::GetImageDataSize(void) {
76    return (lgrTotale);
77 }
78
79
80 /////////////////////////////////////////////////////////////////
81 /**
82  * \ingroup gdcmFile
83  * \brief   Read pixel data from disk (optionaly decompressing) into the
84  *          caller specified memory location.
85  * @param   destination where the pixel data should be stored.
86  *
87  */
88 bool gdcmFile::ReadPixelData(void* destination) {
89    if ( !OpenFile())
90       return false;
91       
92       printf("GetPixelOffset() %d\n",GetPixelOffset() );
93       
94     if ( fseek(fp, GetPixelOffset(), SEEK_SET) == -1 ) {
95       CloseFile();
96       return false;
97    }     
98     
99    if ( !IsDicomV3()                             ||
100         IsImplicitVRLittleEndianTransferSyntax() ||
101         IsExplicitVRLittleEndianTransferSyntax() ||
102         IsExplicitVRBigEndianTransferSyntax()    ||
103         IsDeflatedExplicitVRLittleEndianTransferSyntax() ) { 
104                     
105       size_t ItemRead = fread(destination, lgrTotale, 1, fp);
106       if ( ItemRead != 1 ) {
107          CloseFile();
108          return false;
109       } else {
110          CloseFile();
111          return true;
112       }
113    } 
114      
115   // ------------------------------- Position on begining of Jpeg Pixels
116   
117       int ln;
118       fseek(fp,4,SEEK_CUR);
119       fread(&ln,4,1,fp); 
120       if(GetSwapCode()) 
121          ln=SwapLong(ln);
122       if (DEBUG) 
123          printf ("ln %d\n",ln);
124       fseek(fp,ln,SEEK_CUR);
125       fseek(fp,4,SEEK_CUR);
126       fread(&ln,4,1,fp); 
127       if(GetSwapCode()) 
128          ln=SwapLong(ln);
129       if (DEBUG) 
130          printf ("ln image comprimée %d\n",ln);        
131           
132   // ------------------------------- JPEG LossLess : call to Jpeg Libido
133    
134    if (IsJPEGLossless()) {
135  
136       ClbJpeg* jpg = _IdDcmJpegRead(fp);
137       if(jpg == NULL) {
138          CloseFile();
139          return false;
140       } 
141
142       int nb;
143       string str_nb=gdcmHeader::GetPubElValByNumber(0x0028,0x0100);
144       if (str_nb == "gdcm::Unfound" ) {
145          nb = 16;
146       } else {
147          nb = atoi(str_nb.c_str() );
148          if (nb == 12) nb =16;
149       }
150       int nBytes= nb/8;
151       int * dataJpg = jpg->DataImg;
152       int taille = GetXSize() *  GetYSize() *  GetZSize() * GetSamplesPerPixel();
153           
154       switch (nBytes) {   
155          case 1:
156          {
157             unsigned short *dest = (unsigned short *)destination;
158             for (int i=0; i<taille; i++) {
159                *((unsigned char *)dest+i) = *(dataJpg +i);    
160             }
161          }
162          break;        
163          
164          case 2:
165          {
166             unsigned short *dest = (unsigned short *)destination;
167             for (int i=0; i<taille; i++) {           
168                *((unsigned short *)dest+i) = *(dataJpg +i);    
169             }
170          }
171          break;
172             
173          case 4:
174          {
175             unsigned int *dest=(unsigned int *)destination;
176             for (int i=0;i<taille; i++) {
177                *((unsigned int *)dest+i) = *(dataJpg +i);    
178             }
179           }
180          break;          
181      }
182       
183       _IdDcmJpegFree (jpg);
184       return true;
185    }  
186  
187   // ------------------------------- JPEG Lossy : call to IJG 6b
188   
189   // TODO : faire qq chose d'intelligent pour limiter 
190   // la duplication du code JPEG <bits=8 / bits=12>
191   // TODO : eplucher icelui pour traiter *egalement* bits=16
192   
193       int nBS;        
194       if  ((nBS = GetBitsStored()) != 12) {
195          printf("Sorry, Bits Stored = %d not yet taken into account\n",nBS);
196          return false;
197       }
198       
199       int res = gdcm_read_JPEG_file (destination);
200          if (DEBUG) 
201             printf ("res : %d\n",res);
202       return res;
203 }   
204
205 /**
206  * \ingroup gdcmFile
207  * \brief   Allocates necessary memory, copies the pixel data
208  *          (image[s]/volume[s]) to newly allocated zone.
209  * @return  Pointer to newly allocated pixel data. 
210  */
211 void * gdcmFile::GetImageData (void) {
212    PixelData = (void *) malloc(lgrTotale);
213    GetImageDataIntoVector(PixelData, lgrTotale);
214    return(PixelData);
215 }
216
217 /**
218  * \ingroup gdcmFile
219  * \brief   Copies at most MaxSize bytes of pixel data to caller's
220  *          memory space.
221  * @param   destination Address (in caller's memory space) at which the
222  *          pixel data should be copied
223  * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
224  *          is not sufficient to hold the pixel data the copy is not
225  *          executed (i.e. no partial copy).
226  * @return  On success, the number of bytes actually copied. Zero on
227  *          failure e.g. MaxSize is lower than necessary.
228  */
229
230 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
231
232    int nb, nbu, highBit, signe;
233    string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
234  
235    if ( lgrTotale > MaxSize ) {
236       dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
237                      "than caller's expected MaxSize");
238       return (size_t)0; 
239    }
240         
241         (void)ReadPixelData(destination);
242                         
243         // Nombre de Bits Alloues pour le stockage d'un Pixel
244         str_nb = GetPubElValByNumber(0x0028,0x0100);
245         if (str_nb == "gdcm::Unfound" ) {
246                 nb = 16;
247         } else {
248                 nb = atoi(str_nb.c_str() );
249         }
250         
251         // Nombre de Bits Utilises
252         str_nbu=GetPubElValByNumber(0x0028,0x0101);
253         if (str_nbu == "gdcm::Unfound" ) {
254                 nbu = nb;
255         } else {
256                 nbu = atoi(str_nbu.c_str() );
257         }       
258         
259         // Position du Bit de Poids Fort
260         str_highBit=GetPubElValByNumber(0x0028,0x0102);
261         if (str_highBit == "gdcm::Unfound" ) {
262                 highBit = nb - 1;
263         } else {
264                 highBit = atoi(str_highBit.c_str() );
265         }
266                 
267         // Signe des Pixels 
268         str_signe=GetPubElValByNumber(0x0028,0x0103);
269         if (str_signe == "gdcm::Unfound" ) {
270                 signe = 1;
271         } else {
272                 signe = atoi(str_signe.c_str() );
273         }
274
275    // On remet les Octets dans le bon ordre si besoin est
276    if (nb != 8)
277      SwapZone(destination, GetSwapCode(), lgrTotale, nb);
278  
279    // On remet les Bits des Octets dans le bon ordre si besoin est
280    if (nbu != nb){
281       int l = (int)lgrTotale / (nb/8);
282       if (nb == 16) {
283          guint16 mask = 0xffff;
284          mask = mask >> (nb-nbu);
285          guint16 *deb = (guint16 *)destination;
286          for(int i = 0; i<l; i++) {
287             *deb = (*deb >> (nbu-highBit-1)) & mask;
288             deb ++;
289          }
290       } else if (nb == 32 ) {
291          guint32 mask = 0xffffffff;
292          mask = mask >> (nb-nbu);
293          guint32 *deb = (guint32 *)destination;
294          for(int i = 0; i<l; i++) {
295             *deb = (*deb >> (nbu-highBit-1)) & mask;
296             deb ++;
297          }
298       } else {
299          dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
300          return (size_t)0; 
301       }
302    }
303    
304  // ---
305    string str_PlanarConfiguration = GetPubElValByNumber(0x0028,0x0006);
306    int PlanarConfiguration;
307    if (str_PlanarConfiguration == "gdcm::Unfound" ) {
308       PlanarConfiguration = 0;
309    } else {
310       PlanarConfiguration = atoi(str_PlanarConfiguration.c_str() );
311    }   
312  // ---
313  
314    // TODO : replace by                  
315    // if (GetPlanarConfiguration() == 1) {
316    // after unfreeze
317    
318    if (PlanarConfiguration == 1) { // need to make RGB Pixels
319       int l = lgrTotale/3 ;
320
321       char * a = (char *)destination;
322       char * b = a + l;
323       char * c = b + l;
324       char * newDest = (char*) malloc(lgrTotale);
325       // TODO :
326       // any trick not to have to allocate temporary buffer is welcome ...
327       char *x = newDest;
328       for (int i=0;i<l; i++) {
329          *(x++) = *(a++);
330          *(x++) = *(b++);
331          *(x++) = *(c++);  
332       }
333       a = (char *)destination;
334       x = newDest;
335       for (int i=0;i<lgrTotale; i++) {
336          *(a++) = *(x++);
337       }
338       free(newDest);
339    }
340    return lgrTotale; 
341 }
342
343
344 //
345 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
346 //
347
348 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
349 guint32 s32;
350 guint16 fort,faible;
351 int i;
352
353 if(nb == 16)  
354    switch(swap) {
355       case 0:
356       case 12:
357       case 1234:
358          break;
359                 
360       case 21:
361       case 3412:
362       case 2143:
363       case 4321:
364
365          for(i=0;i<lgr;i++)
366             ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
367                                         | ((((unsigned short int*)im)[i])<<8);
368          break;
369                         
370       default:
371          printf("valeur de SWAP (16 bits) non autorisee : %d\n", swap);
372    } 
373  
374 if( nb == 32 )
375    switch (swap) {
376       case 0:
377       case 1234:
378          break;
379
380       case 4321:
381          for(i=0;i<lgr;i++) {
382             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 4321 */
383             fort  =((unsigned long int*)im)[i]>>16;
384             fort=  (fort>>8)   | (fort<<8);
385             faible=(faible>>8) | (faible<<8);
386             s32=faible;
387             ((unsigned long int*)im)[i]=(s32<<16)|fort;
388          }
389          break;
390
391       case 2143:
392          for(i=0;i<lgr;i++) {
393             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 2143 */
394             fort=((unsigned long int*)im)[i]>>16;
395             fort=  (fort>>8)   | (fort<<8);
396             faible=(faible>>8) | (faible<<8);
397             s32=fort; 
398             ((unsigned long int*)im)[i]=(s32<<16)|faible;
399          }
400          break;
401   
402       case 3412:
403          for(i=0;i<lgr;i++) {
404             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 3412 */
405             fort=((unsigned long int*)im)[i]>>16;                  
406             s32=faible; 
407             ((unsigned long int*)im)[i]=(s32<<16)|fort;
408          }                 
409          break; 
410                                 
411       default:
412          printf("valeur de SWAP (32 bits) non autorisee : %d\n", swap);
413    } 
414 return;
415 }
416
417 /////////////////////////////////////////////////////////////////
418 /**
419  * \ingroup   gdcmFile
420  * \brief TODO JPR
421  * \warning doit-etre etre publique ?  FIXME JPR
422  * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
423  *
424  * @param inData TODO JPR
425  * @param ExpectedSize TODO JPR
426  *
427  * @return TODO JPR     
428  */
429 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
430    SetImageDataSize(ExpectedSize);
431    PixelData = inData;
432    lgrTotale = ExpectedSize;
433    return(1);
434 }
435
436
437 /////////////////////////////////////////////////////////////////
438 /**
439  * \ingroup   gdcmFile
440  * \brief TODO JPR
441  * \
442  * \warning WARNING doit-etre etre publique ? FIXME JPR
443  * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
444  *
445  * @param ImageDataSize TODO JPR
446  *
447  */
448
449 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
450
451    string content1;
452    char car[20];
453         
454    // suppose que le ElValue (0x7fe0, 0x0010) existe ...
455         
456    sprintf(car,"%d",ImageDataSize);
457  
458    gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
459    a->SetLength(ImageDataSize);
460                 
461    ImageDataSize+=8;
462    sprintf(car,"%d",ImageDataSize);
463    content1=car;        
464    SetPubElValByNumber(content1, 0x7fe0, 0x0000);
465 }
466
467
468 /////////////////////////////////////////////////////////////////
469 /**
470  * \ingroup   gdcmFile
471  * \brief Ecrit sur disque les pixels d'UNE image
472  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
473  *        Ca sera à l'utilisateur d'appeler son Reader correctement
474  *        (Equivalent a IdImaWriteRawFile) FIXME JPR
475  *
476  * @param nomFichier TODO JPR
477  *
478  * @return TODO JPR     
479  */
480
481 int gdcmFile::WriteRawData (string nomFichier) {
482
483    FILE * fp1;
484    fp1 = fopen(nomFichier.c_str(),"wb");
485    if (fp1 == NULL) {
486       printf("Echec ouverture (ecriture) Fichier [%s] \n",nomFichier.c_str());
487       return (0);
488    } 
489         
490    fwrite (PixelData,lgrTotale, 1, fp1);
491    fclose (fp1);
492    return(1);
493 }
494
495
496
497 /////////////////////////////////////////////////////////////////
498 /**
499  * \ingroup   gdcmFile
500  * \brief Ecrit sur disque UNE image Dicom
501  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
502  *         Ca fonctionnera correctement (?) sur processeur Intel
503  *         (Equivalent a IdDcmWrite) FIXME JPR 
504  *
505  * @param nomFichier TODO JPR
506  *
507  * @return      TODO JPR
508  */
509
510 int gdcmFile::WriteDcmImplVR (string nomFichier) {
511    return WriteBase(nomFichier, ImplicitVR);
512 }
513
514 /////////////////////////////////////////////////////////////////
515 /**
516  * \ingroup   gdcmFile
517  *
518  * @param  nomFichier TODO JPR
519  *
520  * @return TODO JPR
521  */
522  
523 int gdcmFile::WriteDcmImplVR (const char* nomFichier) {
524    return WriteDcmImplVR (string (nomFichier));
525 }
526         
527 /////////////////////////////////////////////////////////////////
528 /**
529  * \ingroup   gdcmFile
530  *
531  * @param  nomFichier TODO JPR
532  *
533  * @return TODO JPR
534  */
535
536 int gdcmFile::WriteDcmExplVR (string nomFichier) {
537    return WriteBase(nomFichier, ExplicitVR);
538 }
539         
540 /////////////////////////////////////////////////////////////////
541 /**
542  * \ingroup   gdcmFile
543  * \brief  Ecrit au format ACR-NEMA sur disque l'entete et les pixels
544  *        (a l'attention des logiciels cliniques 
545  *        qui ne prennent en entrée QUE des images ACR ...
546  * \warning si un header DICOM est fourni en entree,
547  *        les groupes < 0x0008 et les groupes impairs sont ignores)
548  * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
549  *        Ca fonctionnera correctement (?) sur processeur Intel
550  *        (Equivalent a IdDcmWrite) 
551  *
552  * @param nomFichier TODO JPR
553  *
554  * @return TODO JPR     
555  */
556
557 int gdcmFile::WriteAcr (string nomFichier) {
558    return WriteBase(nomFichier, ACR);
559 }
560
561 /////////////////////////////////////////////////////////////////
562 /**
563  * \ingroup   gdcmFile
564  *
565  * @param  FileName TODO JPR
566  * @param  type TODO JPR
567  *
568  * @return TODO JPR
569  */
570 int gdcmFile::WriteBase (string FileName, FileType type) {
571
572    FILE * fp1;
573    fp1 = fopen(FileName.c_str(),"wb");
574    if (fp1 == NULL) {
575       printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
576       return (0);
577    }
578
579    if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
580       char * filePreamble;
581       // Ecriture Dicom File Preamble
582       filePreamble=(char*)calloc(128,1);
583       fwrite(filePreamble,128,1,fp1);
584       fwrite("DICM",4,1,fp1);
585    }
586
587    gdcmHeader::Write(fp1, type);
588    fwrite(PixelData, lgrTotale, 1, fp1);
589    fclose (fp1);
590    return(1);
591 }