]> Creatis software - gdcm.git/blob - src/gdcm.h
Ajout fonctions
[gdcm.git] / src / gdcm.h
1 // gdcm.h
2
3 // gdcmlib Intro:  
4 // * gdcmlib is a library dedicated to reading and writing dicom files.
5 // * LGPL for the license
6 // * lightweigth as opposed to CTN or DCMTK which come bundled which try
7 //   to implement the full DICOM standard (networking...). gdcmlib concentrates
8 //   on reading and writing
9 // * Formats: this lib should be able to read ACR-NEMA v1 and v2, Dicom v3 (as
10 //   stated in part10). [cf dcmtk/dcmdata/docs/datadict.txt]
11 // * Targeted plateforms: Un*xes and Win32/VC++6.0
12 //
13 //
14 // TODO
15 // The declarations commented out and starting with "TODO Swig" needed
16 // to be temporarily removed for swig to proceed correctly (in fact
17 // problems appears at loading of _gdcm.[so/dll]). So, simply uncomment
18 // the declaration once you provided the definition of the method...
19
20 #include <string>
21 #ifdef _MSC_VER
22 using namespace std;  // string type lives in the std namespace on VC++
23 #endif
24
25 #include <iostream>
26 #include <stddef.h>   // For size_t
27 #include <stdio.h>    // FIXME For FILE on GCC only
28 #include <list>
29 #include <map>
30
31                       // The requirement for the hash table (or map) that
32                       // we shall use:
33                       // 1/ First, next, last (iterators)
34                       // 2/ should be sortable (i.e. sorted by TagKey). This
35                       //    condition shall be droped since the Win32/VC++
36                       //    implementation doesn't look a sorted one. Pffff....
37                       // 3/ Make sure we can setup some default size value,
38                       //    which should be around 4500 entries which is the
39                       //    average dictionary size (said JPR)
40                       //
41                       // En fait, je disais que dans LE Directory Dicom (dans son etat 2002)
42                       // il y a 1600 entrees.
43                       // Une valeur raisonable pour un  majorant du nombre d'entrees
44                       // dans une entete DICOM d'une image semble semble etre 300
45                       // Si on 'decortique' les elements SQ (ce qui ne semble pas etre fait pour le moment)
46                       // on risque en fait de depasser ... un nombre non previsible dans le cas d'une entree SQ
47                       // contenant lui même un tres grand nombre d'entrees ?!?)
48                       // Quant au nombre d'entrees dans un DICOMDIR, c'est encore pire : il n'est limité
49                       // que par la taille d'un CD-ROM (les DVD-ROM ne sont pas encore pris en compte)
50                       // On peut s'attendre a 30 entrees par fichier dicom présent sur le CD-ROM
51                       // REMARQUE : il faudra se pencher sur le pb de la creation du DICOMDIR lorsqu'on voudra 
52                       // exporter des images lisibles par les consoles cliniques 
53                       // et pas seulement importables dans e-film. 
54
55 #ifdef __GNUC__
56 #include <stdint.h>
57 #define guint16 uint16_t
58 #define guint32 uint32_t
59 #endif
60
61 #ifdef _MSC_VER 
62 typedef  unsigned short guint16;
63 typedef  unsigned int   guint32;
64 #endif
65
66 #ifdef _MSC_VER
67 #define GDCM_EXPORT __declspec( dllexport )
68 #else
69 #define GDCM_EXPORT
70 #endif
71
72 //
73 // ---------------------------------------------------- gdcmDictEntry
74 //
75 //      c'est une ligne du Dictionnaire Dicom
76 //
77
78
79 ////////////////////////////////////////////////////////////////////////////
80 // Tag based hash tables.
81 // We shall use as keys the strings (as the C++ type) obtained by
82 // concatenating the group value and the element value (both of type
83 // unsigned 16 bit integers in Dicom) expressed in hexadecimal.
84 // Example: consider the tag given as (group, element) = (0x0010, 0x0010).
85 // Then the corresponding TagKey shall be the string 0010|0010 (where
86 // the | (pipe symbol) acts as a separator). Refer to 
87 // gdcmDictEntry::TranslateToKey for this conversion function.
88
89 typedef string TagKey;
90
91 class GDCM_EXPORT gdcmDictEntry {
92 private:
93         guint16 group;    // e.g. 0x0010
94         guint16 element;  // e.g. 0x0103
95         string  vr;       // Value Representation i.e. some clue about the nature
96                           // of the data represented e.g. "FD" short for
97                           // "Floating Point Double"
98         // CLEANME: find the official dicom name for this field !
99         string  fourth;   // Fourth field containing some semantics.
100         string  name;     // e.g. "Patient_Name"
101         TagKey  key;      // Redundant with (group, element) but we add it
102                           // on efficiency purposes.
103         // DCMTK has many fields for handling a DictEntry (see below). What are the
104         // relevant ones for gdcmlib ?
105         //      struct DBI_SimpleEntry {
106         //         Uint16 upperGroup;
107         //         Uint16 upperElement;
108         //         DcmEVR evr;
109         //         const char* tagName;
110         //         int vmMin;
111         //         int vmMax;
112         //         const char* standardVersion;
113         //         DcmDictRangeRestriction groupRestriction;
114         //         DcmDictRangeRestriction elementRestriction;
115         //       };
116 public:
117         
118         // fabrique une ligne de Dictionnaire Dicom à partir des parametres en entrée
119
120         gdcmDictEntry(guint16 group, 
121                           guint16 element,
122                       string vr     = "Unknown",
123                       string fourth = "Unknown",
124                       string name   = "Unknown");
125                                           
126         // fabrique une 'clé' par concaténation du numGroupe et du numElement
127
128         static TagKey TranslateToKey(guint16 group, guint16 element);
129         
130         guint16 GetGroup(void)  { return group; };
131         guint16 GetElement(void){return element;};
132         string  GetVR(void)     {return vr;     };
133         void    SetVR(string);
134         void    SetKey(string k){ key = k;              }
135         bool    IsVrUnknown(void);
136         string  GetFourth(void) {return fourth;};
137         string  GetName(void)   {return name;  };
138         string  GetKey(void)    {return key;   };
139 };
140   
141 //
142 // ---------------------------------------------------- gdcmDict
143 // 
144 //      c'est le Dictionnaire Dicom
145 //
146  
147 ////////////////////////////////////////////////////////////////////////////
148 // A single DICOM dictionary i.e. a container for a collection of dictionary
149 // entries. There should be a single public dictionary (THE dictionary of
150 // the actual DICOM v3) but as many shadow dictionaries as imagers 
151 // combined with all software versions...
152
153 typedef map<TagKey, gdcmDictEntry*> TagHT;
154         // Table de Hachage : (group,Elem) --> pointeur vers une ligne du Dictionnaire Dicom
155
156 class GDCM_EXPORT gdcmDict {
157         string name;
158         string filename;
159         TagHT entries;
160 public:
161         // rempli le Dictionnaire Dicom à partir d'un fichier texte
162         gdcmDict(const char* FileName);   // Read Dict from disk
163         
164         int AddNewEntry (gdcmDictEntry* NewEntry);
165         int ReplaceEntry(gdcmDictEntry* NewEntry);
166         int RemoveEntry (TagKey k);
167         int RemoveEntry (guint16 group, guint16 element);
168
169         
170         // renvoie une ligne de Dictionnaire Dicom à partir de (numGroup, numElement)
171         gdcmDictEntry * GetTag(guint32 group, guint32 element);
172         void Print(ostream&);
173         TagHT & GetEntries(void) { return entries; }
174 };
175
176
177 //
178 // ---------------------------------------------------- gdcmDictSet
179 //
180 //      Ensemble de Dictionnaires Dicom (le public + 'des' privés)
181 //      Au cas ou l'on traiterait un jour les 'dictionnaires privés'
182 //       - pratiquement un par constructeur, par machine, et par version du logiciel -
183 //
184 //
185
186 ////////////////////////////////////////////////////////////////////////////
187 // Container for managing a set of loaded dictionaries. Sharing dictionaries
188 // should avoid :
189 // * reloading an allready loaded dictionary,
190 // * having many in memory representations of the same dictionary.
191
192 typedef string DictKey;
193 typedef map<DictKey, gdcmDict*> DictSetHT;
194
195 class GDCM_EXPORT gdcmDictSet {
196 private:
197         string DictPath;      // Directory path to dictionaries
198         DictSetHT dicts;
199         int AppendDict(gdcmDict* NewDict);
200         int LoadDictFromFile(string filename, DictKey);
201         void SetDictPath(void);
202 public:
203         gdcmDictSet(void);    // loads THE DICOM v3 dictionary
204         // TODO Swig int LoadDictFromFile(string filename);
205    // QUESTION: the following function might not be thread safe !? Maybe
206    //           we need some mutex here, to avoid concurent creation of
207    //           the same dictionary !?!?!
208         // TODO Swig int LoadDictFromName(string filename);
209         // TODO Swig int LoadAllDictFromDirectory(string DirectoryName);
210         // TODO Swig string* GetAllDictNames();
211         //
212         // Question : ne faudra-t-il pas mettre LE dictionnaire DICOM dans un Directory
213         // et les eventuels 'dictionnaires prives' dans un autre?
214         // (pour eviter a un utilisateur mal dégourdi de tout saccager ?)
215         //
216         int LoadDicomV3Dict(void);
217         void Print(ostream&);
218         gdcmDict* GetDict(DictKey DictName);
219         gdcmDict* GetDefaultPublicDict(void);
220 };
221
222
223 //
224 // ---------------------------------------------------- ElValue
225 //
226 //      C'est un Element Dicom
227 //      (ce qu'on a trouve dans l'entete de l'image
228 //      + ce qu'on est allé chercher dans le Dictionnaire Dicom)
229 //
230
231 // QUESTION:
232 //
233 // Ne faudrait-il pas trouver un autre nom, qui preterait moins à confusion?
234 // ElValue n'EST PAS la 'valeur d'un Element', mais la reunion d'infos
235 // trouvees dans l'Entete du fichier ET dans le Dictionnaire DICOM
236 //
237
238 // The dicom header of a Dicom file contains a set of such ELement VALUES
239 // (when successfuly parsed against a given Dicom dictionary)
240
241 class GDCM_EXPORT ElValue {
242 private:
243         gdcmDictEntry *entry;
244         guint32 LgrElem;
245         bool ImplicitVr;       // Even when reading explicit vr files, some
246                                // elements happen to be implicit. Flag them here
247                                // since we can't use the entry->vr without breaking
248                                // the underlying dictionary.
249         // Might prove of some interest (see _ID_DCM_ELEM)
250         // int Swap;
251 public:
252         string  value;     // used to be char * valeurElem
253         size_t Offset;     // Offset from the begining of file for direct user access
254         
255         ElValue(gdcmDictEntry*);
256         void SetDictEntry(gdcmDictEntry *NewEntry) { entry = NewEntry; };
257         bool   IsVrUnknown(void) { return entry->IsVrUnknown(); };
258         void SetImplicitVr(void) { ImplicitVr = true; };
259         bool  IsImplicitVr(void) { return ImplicitVr; };
260
261         guint16 GetGroup(void)   { return entry->GetGroup();   };       
262         guint16 GetElement(void) { return entry->GetElement(); };
263         string  GetKey(void)     { return entry->GetKey();     };
264         string  GetName(void)    { return entry->GetName();    };
265         
266         string  GetVR(void)              { return entry->GetVR(); };
267         
268         void    SetVR(string v)  { entry->SetVR(v);       }; 
269                 
270         // Question :
271         // Un champ privé, accessible en consultation et en modif (sans restriction)
272         // interet par rapport à un champ public ? 
273         // --> pouvoir en changer la définition sans toucher à l'API
274         
275         void SetLength(guint32 l){ LgrElem = l;         };
276         guint32 GetLength(void)  { return LgrElem;      };
277
278         void SetValue(string val){ value = val;         };
279         string  GetValue(void)   { return value;        };
280
281         void SetOffset(size_t of){ Offset = of;         };
282         size_t  GetOffset(void)  { return Offset;       };      
283
284 };
285
286
287 //
288 // ---------------------------------------------------- ElValSet
289 //
290 //      ... un ensemble d'Elements Dicom 
291 //      ... le résultat de l'analyse d'une entete d'image, par exemple
292
293 ////////////////////////////////////////////////////////////////////////////
294 // Container for a set of successfully parsed ElValues.
295 typedef map<TagKey, ElValue*> TagElValueHT;
296 typedef map<string, ElValue*> TagElValueNameHT;
297
298 class GDCM_EXPORT ElValSet {
299                 // We need both accesses with a TagKey and the Dictentry.Name
300
301         TagElValueHT tagHt;
302         TagElValueNameHT NameHt;
303 public: 
304         void Add(ElValue*);             
305         void Print(ostream &);
306         void PrintByName(ostream &);
307         int  Write(FILE *fp);
308         ElValue* GetElementByNumber(guint32 group, guint32 element);
309         ElValue* GetElementByName  (string);
310         string   GetElValueByNumber(guint32 group, guint32 element);
311         string   GetElValueByName  (string);
312         
313         TagElValueHT & GetTagHt(void);  
314         
315         int SetElValueByNumber(string content, guint32 group, guint32 element);
316         int SetElValueByName(string content, string TagName);
317 };
318
319
320 //
321 // ---------------------------------------------------- gdcmHeader
322 //
323 //      C'est le Dicom Header d'une image donnée
324 //      (tous les elements Dicom qui la composent
325 //      + des info 'de service')
326 //
327
328 ////////////////////////////////////////////////////////////////////////////
329 // The typical usage of instances of class gdcmHeader is to classify a set of
330 // dicom files according to header information e.g. to create a file hierarchy
331 // reflecting the Patient/Study/Serie informations, or extracting a given
332 // SerieId. Accesing the content (image[s] or volume[s]) is beyond the
333 // functionality of this class and belong to gdmcFile (see below).
334 // Notes:
335 // * the various entries of the explicit value representation (VR) shall
336 //   be managed within a dictionary which is shared by all gdcmHeader instances
337 // * the gdcmHeader::Set*Tag* family members cannot be defined as protected
338 //   (Swig limitations for as Has_a dependency between gdcmFile and gdcmHeader)
339  
340
341 typedef string VRKey;
342 typedef string VRAtr;
343 typedef map<VRKey, VRAtr> VRHT;    // Value Representation Hash Table
344
345
346 class GDCM_EXPORT gdcmHeader {
347         void SkipBytes(guint32);
348 private:
349         static VRHT *dicom_vr;
350         // Dictionaries of data elements:
351
352         static gdcmDictSet* Dicts;  // global dictionary container
353         gdcmDict* RefPubDict;       // public dictionary
354         gdcmDict* RefShaDict;       // shadow dictionary (optional)
355         // Parsed element values:
356         ElValSet PubElVals;         // parsed with Public Dictionary
357         ElValSet ShaElVals;         // parsed with Shadow Dictionary
358         string filename;            // refering underlying file
359         FILE * fp;
360         // The tag Image Location (0028,0200) - containing the address of
361         // the pixels - is not allways present. Then we store this information
362         
363         // FIXME
364         
365         // Question :
366         // Qu'y a-t-il a corriger ?
367         //
368         // outside of the elements:
369         
370         guint16 grPixel;
371         guint16 numPixel;
372         // Ne faudrait-il pas une indication sur la presence ou non
373         // du 'groupe des pixels' dans l'entete?
374         // (voir pb du DICOMDIR)
375         
376         // Swap code (little, big, bad-big, bad-little endian): this code is not fixed
377         // during parsing.FIXME sw should be an enum e.g.
378         //enum EndianType {
379                 //LittleEndian, 
380                 //BadLittleEndian,
381                 //BigEndian, 
382                 //BadBigEndian};
383         int sw;
384
385         // Only the elements whose size is below this bound will be loaded.
386         // By default, this upper bound is limited to 1024 (which looks reasonable
387         // when one considers the definition of the various VR contents).
388         guint32 MaxSizeLoadElementValue;
389
390         guint16 ReadInt16(void);
391         guint32 ReadInt32(void);
392         guint16 SwapShort(guint16);
393         guint32 SwapLong(guint32);
394         void Initialise(void);
395         void CheckSwap(void);
396         void FindLength(ElValue *);
397         guint32 FindLengthOB(void);
398         void FindVR(ElValue *);
399         void LoadElementValue(ElValue *);
400         void LoadElementValueSafe(ElValue *);
401         void SkipElementValue(ElValue *);
402         void InitVRDict(void);
403         void SwitchSwapToBigEndian(void);
404         void FixFoundLength(ElValue*, guint32);
405         bool IsAnInteger(ElValue *);
406         
407         bool IsImplicitVRLittleEndianTransferSyntax(void);
408         bool IsExplicitVRLittleEndianTransferSyntax(void);
409         bool IsDeflatedExplicitVRLittleEndianTransferSyntax(void);
410         bool IsExplicitVRBigEndianTransferSyntax(void);
411         bool IsJPEGBaseLineProcess1TransferSyntax(void);
412         bool IsJPEGExtendedProcess2_4TransferSyntax(void);      
413         bool IsJPEGExtendedProcess3_5TransferSyntax(void);
414         bool IsJPEGSpectralSelectionProcess6_8TransferSyntax(void);     
415 //
416 // Euhhhhhhh
417 // Il y en a encore DIX-SEPT, comme ça.
418 // Il faudrait trouver qq chose + rusé ...
419 //      
420                 
421         void SetMaxSizeLoadElementValue(long);
422         ElValue       * ReadNextElement(void);
423         gdcmDictEntry * IsInDicts(guint32, guint32);
424 protected:
425         enum FileType {
426                 Unknown = 0,
427                 TrueDicom,
428                 ExplicitVR,
429                 ImplicitVR,
430                 ACR,
431                 ACR_LIBIDO};  // CLEANME
432         FileType filetype;
433         int write(ostream&);   
434         int anonymize(ostream&);  // FIXME : anonymize should be a friend ?
435 public:
436         void LoadElements(void);
437         virtual void ParseHeader(void);
438         gdcmHeader(const char* filename);
439         virtual ~gdcmHeader();
440         
441         size_t GetPixelOffset(void);
442         void   GetPixels(size_t, void *);
443         int    GetSwapCode(void) { return sw; }
444
445         // TODO Swig int SetPubDict(string filename);
446         // When some proprietary shadow groups are disclosed, we can set up
447         // an additional specific dictionary to access extra information.
448         // TODO Swig int SetShaDict(string filename);
449
450         // Retrieve all potentially available tag [tag = (group, element)] names
451         // from the standard (or public) dictionary. Typical usage : enable the
452         // user of a GUI based interface to select his favorite fields for sorting
453         // or selecting.
454         list<string> * GetPubTagNames(void);
455         map<string, list<string> > * GetPubTagNamesByCategory(void);
456         // Get the element values themselves:
457         
458         string GetPubElValByName(string TagName);
459         string GetPubElValByNumber(guint16 group, guint16 element);
460
461         // Getting the element value representation (VR) might be needed by caller
462         // to convert the string typed content to caller's native type 
463         // (think of C/C++ vs Python).
464
465         string GetPubElValRepByName(string TagName);
466         string GetPubElValRepByNumber(guint16 group, guint16 element);
467
468         TagElValueHT & GetPubElVal(void) { return PubElVals.GetTagHt(); };
469         void   PrintPubElVal(ostream & os = cout);
470         void   PrintPubDict(ostream &);
471           
472         // Same thing with the shadow :
473         // TODO Swig string* GetShaTagNames(); 
474         string GetShaElValByName(string TagName);
475         string GetShaElValByNumber(guint16 group, guint16 element);
476         string GetShaElValRepByName(string TagName);
477         string GetShaElValRepByNumber(guint16 group, guint16 element);
478
479         // Wrappers of the above (public is privileged over shadow) to avoid
480         // bugging the caller with knowing if ElVal is from the public or shadow
481         // dictionary.
482         string GetElValByName(string TagName);
483         string GetElValByNumber(guint16 group, guint16 element);
484         string GetElValRepByName(string TagName);
485         string GetElValRepByNumber(guint16 group, guint16 element);
486
487         int SetPubElValByName(string content, string TagName);
488         int SetPubElValByNumber(string content, guint16 group, guint16 element);
489         int SetShaElValByName(string content, string ShadowTagName);
490         int SetShaElValByNumber(string content, guint16 group, guint16 element);
491
492         ElValSet GetPubElVals() { return(PubElVals); }
493 };
494
495 //
496 // ---------------------------------------------------- gdcmFile
497 //
498 //      un fichier EST_UNE entete, ou A_UNE entete ?
499 // 
500 //      On dit 'EST_UNE' ...
501
502
503 ////////////////////////////////////////////////////////////////////////////
504 // In addition to Dicom header exploration, this class is designed
505 // for accessing the image/volume content. One can also use it to
506 // write Dicom files.
507 ////// QUESTION: this looks still like an open question whether the
508 //////           relationship between a gdcmFile and gdcmHeader is of
509 //////           type IS_A or HAS_A !
510
511 class GDCM_EXPORT gdcmFile: public gdcmHeader
512 {
513 private:
514         // QUESTION :
515         // Data pointe sur quoi?
516         // sur les Pixels lus?
517         // --> j'ajoute un champ public : Pixels
518         // (il faudra que l'utilisateur puisse modifier les pixels ?)
519         
520         void* Data;
521         int Parsed;          // weather allready parsed
522         string OrigFileName; // To avoid file overwrite
523 public:
524         // je ne suis pas sur d'avoir compris *où* il serait légitime de ranger ca.
525         // on pourra tjs le deplacer, et mettre des accesseurs
526         void * Pixels;
527         size_t lgrTotale;
528         
529         // Constructor dedicated to writing a new DICOMV3 part10 compliant
530         // file (see SetFileName, SetDcmTag and Write)
531         // TODO Swig gdcmFile();
532         // Opens (in read only and when possible) an existing file and checks
533         // for DICOM compliance. Returns NULL on failure.
534         // Note: the in-memory representation of all available tags found in
535         //    the DICOM header is post-poned to first header information access.
536         //    This avoid a double parsing of public part of the header when
537         //    one sets an a posteriori shadow dictionary (efficiency can be
538         //    seen as a side effect).
539         
540         gdcmFile(string & filename);
541         
542         // For promotion (performs a deepcopy of pointed header object)
543         // TODO Swig gdcmFile(gdcmHeader* header);
544         // TODO Swig ~gdcmFile();
545
546         // On writing purposes. When instance was created through
547         // gdcmFile(string filename) then the filename argument MUST be different
548         // from the constructor's one (no overwriting allowed).
549         // TODO Swig int SetFileName(string filename);
550
551         // Allocates necessary memory, copies the data (image[s]/volume[s]) to
552         // newly allocated zone and return a pointer to it:
553         
554          void * GetImageData();
555         
556         // Returns size (in bytes) of required memory to contain data
557         // represented in this file.
558         
559         size_t GetImageDataSize();
560         
561         // Copies (at most MaxSize bytes) of data to caller's memory space.
562         // Returns an error code on failure (if MaxSize is not big enough)
563         
564         int PutImageDataHere(void* destination, size_t MaxSize );
565         
566         // Question :
567         //
568         //      GetImageData et PutImageDataHere
569         // Get et Put pour 2 fonctions qui font presque la meme chose :-(
570         //
571         
572         // Allocates ExpectedSize bytes of memory at this->Data and copies the
573         // pointed data to it.
574         
575         // Question :
576         // Pourquoi dupliquer les pixels, alors qu'on les a deja en mémoire,
577         // et que Data (dans le gdcmHeader) est un pointeur ?
578         
579         // TODO Swig int SetImageData(void * Data, size_t ExpectedSize);
580         
581         // Push to disk.
582         // A NE PAS OUBLIER : que fait-on en cas de Transfert Syntax (dans l'entete)
583         // incohérente avec l'ordre des octets en mémoire  
584         // TODO Swig int Write();
585         
586         // Ecrit sur disque les pixels d'UNE image
587         // Aucun test n'est fait sur l'"Endiannerie" du processeur.
588         // Ca sera à l'utilisateur d'appeler son Reader correctement
589                 
590         int WriteRawData (string nomFichier);
591         int WriteDcm (string nomFichier);
592 };
593
594 //
595 // ---------------------------------------------------- gdcmSerie
596 //
597 //      une serie EST_UN fichier ????
598 //
599 //
600
601 //class gdcmSerie : gdcmFile;
602
603 //
604 // ---------------------------------------------------- gdcmMultiFrame
605 //
606 //      un fichierMultiFrame EST_UN fichier 
607 //
608 //
609
610 //class gdcmMultiFrame : gdcmFile;
611
612