]> Creatis software - gdcm.git/blob - src/gdcm.h
ajout quelques fonctions gdcmFile
[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
56 #ifdef __GNUC__
57 #include <stdint.h>
58 #define guint16 uint16_t
59 #define guint32 uint32_t
60 #endif
61
62 #ifdef _MSC_VER 
63 typedef  unsigned short guint16;
64 typedef  unsigned int   guint32;
65 #endif
66
67 #ifdef _MSC_VER
68 #define GDCM_EXPORT __declspec( dllexport )
69 #else
70 #define GDCM_EXPORT
71 #endif
72
73
74 //
75 // ---------------------------------------------------- gdcmDictEntry
76 //
77 //      c'est une ligne du Dictionnaire Dicom
78 //
79
80
81 ////////////////////////////////////////////////////////////////////////////
82 // Tag based hash tables.
83 // We shall use as keys the strings (as the C++ type) obtained by
84 // concatenating the group value and the element value (both of type
85 // unsigned 16 bit integers in Dicom) expressed in hexadecimal.
86 // Example: consider the tag given as (group, element) = (0x0010, 0x0010).
87 // Then the corresponding TagKey shall be the string 0010|0010 (where
88 // the | (pipe symbol) acts as a separator). Refer to 
89 // gdcmDictEntry::TranslateToKey for this conversion function.
90
91 typedef string TagKey;
92
93 class GDCM_EXPORT gdcmDictEntry {
94 private:
95         guint16 group;    // e.g. 0x0010
96         guint16 element;  // e.g. 0x0103
97         string  vr;       // Value Representation i.e. some clue about the nature
98                           // of the data represented e.g. "FD" short for
99                           // "Floating Point Double"
100         // CLEANME: find the official dicom name for this field !
101         string  fourth;   // Fourth field containing some semantics.
102         string  name;     // e.g. "Patient_Name"
103         TagKey  key;      // Redundant with (group, element) but we add it
104                           // on efficiency purposes.
105         // DCMTK has many fields for handling a DictEntry (see below). What are the
106         // relevant ones for gdcmlib ?
107         //      struct DBI_SimpleEntry {
108         //         Uint16 upperGroup;
109         //         Uint16 upperElement;
110         //         DcmEVR evr;
111         //         const char* tagName;
112         //         int vmMin;
113         //         int vmMax;
114         //         const char* standardVersion;
115         //         DcmDictRangeRestriction groupRestriction;
116         //         DcmDictRangeRestriction elementRestriction;
117         //       };
118 public:
119         
120         // fabrique une ligne de Dictionnaire Dicom à partir des parametres en entrée
121
122         gdcmDictEntry(guint16 group, guint16 element,
123                       string vr     = "Unknown",
124                       string fourth = "Unknown",
125                       string name   = "Unknown");
126                                           
127         // fabrique une 'clé' par concaténation du numGroupe et du numElement
128
129         static TagKey TranslateToKey(guint16 group, guint16 element);
130         
131         guint16 GetGroup(void)  { return group;};
132         guint16 GetElement(void){return element;};
133         string  GetVR(void)     {return vr; };
134         void    SetVR(string);
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) --> ligne du Dictionnaire Dicom
155
156 typedef map<TagKey, gdcmDictEntry*> TagHT;
157
158 class GDCM_EXPORT gdcmDict {
159         string name;
160         string filename;
161         TagHT entries;
162 public:
163         // rempli le Dictionnaire Dicom à partir d'un fichier texte
164         gdcmDict(const char* FileName);   // Read Dict from disk
165         
166         // QUESTION :
167         // Ca doit ajouter une nouvelle entrée 'a la fin', ou 'a sa place' ?
168         //
169         // TODO Swig int AppendEntry(gdcmDictEntry* NewEntry);
170         
171         // renvoie une ligne de Dictionnaire Dicom à partir de (numGroup, numElement)
172         gdcmDictEntry * GetTag(guint32 group, guint32 element);
173         void Print(ostream&);
174         TagHT & GetEntries(void) { return entries; }
175 };
176
177
178 //
179 // ---------------------------------------------------- gdcmDictSet
180 //
181 //      Ensemble de Dictionnaires Dicom (le public + 'des' privés)
182 //      Au cas ou l'on traiterait un jour les 'dictionnaires privés'
183 //       - pratiquement un par constructeur, par machine, et par version du logiciel -
184 //
185 //
186
187 ////////////////////////////////////////////////////////////////////////////
188 // Container for managing a set of loaded dictionaries. Sharing dictionaries
189 // should avoid :
190 // * reloading an allready loaded dictionary,
191 // * having many in memory representations of the same dictionary.
192
193 typedef string DictKey;
194 typedef map<DictKey, gdcmDict*> DictSetHT;
195
196 class GDCM_EXPORT gdcmDictSet {
197 private:
198         string DictPath;      // Directory path to dictionaries
199         DictSetHT dicts;
200         int AppendDict(gdcmDict* NewDict);
201         int LoadDictFromFile(string filename, DictKey);
202         void SetDictPath(void);
203 public:
204         gdcmDictSet(void);    // loads THE DICOM v3 dictionary
205         // TODO Swig int LoadDictFromFile(string filename);
206    // QUESTION: the following function might not be thread safe !? Maybe
207    //           we need some mutex here, to avoid concurent creation of
208    //           the same dictionary !?!?!
209         // TODO Swig int LoadDictFromName(string filename);
210         // TODO Swig int LoadAllDictFromDirectory(string DirectoryName);
211         // TODO Swig string* GetAllDictNames();
212         //
213         // Question : ne faudra-t-il pas mettre LE dictionnaire DICOM dans un Directory
214         // et les eventuels 'dictionnaires prives' dans un autre?
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         ElValue(gdcmDictEntry*);
255         void SetDictEntry(gdcmDictEntry *NewEntry) { entry = NewEntry; };
256
257         bool   IsVrUnknown(void) { return entry->IsVrUnknown(); };
258         void SetLength(guint32 l){ LgrElem = l; };
259         void SetValue(string val){ value = val; };
260         void SetOffset(size_t of){ Offset = of; };
261         void SetImplicitVr(void) { ImplicitVr = true; };
262         bool  IsImplicitVr(void) { return ImplicitVr; };
263         void    SetVR(string);
264         string  GetVR(void);
265         string  GetValue(void)   { return value; };
266         guint32 GetLength(void)  { return LgrElem; };
267         size_t  GetOffset(void)  { return Offset; };
268         guint16 GetGroup(void)   { return entry->GetGroup(); };
269         guint16 GetElement(void) { return entry->GetElement(); };
270         string  GetKey(void)     { return entry->GetKey(); };
271         string  GetName(void)    { return entry->GetName();};
272 };
273
274
275 //
276 // ---------------------------------------------------- ElValSet
277 //
278 //      ... un ensemble d'Elements Dicom 
279 //      ... le résultat de l'analyse d'une entete d'image, par exemple
280
281 ////////////////////////////////////////////////////////////////////////////
282 // Container for a set of successfully parsed ElValues.
283 typedef map<TagKey, ElValue*> TagElValueHT;
284 typedef map<string, ElValue*> TagElValueNameHT;
285
286 class GDCM_EXPORT ElValSet {
287                 // We need both accesses with a TagKey and the Dictentry.Name
288         TagElValueHT tagHt;
289         TagElValueNameHT NameHt;
290 public:
291         void Add(ElValue*);
292         void Print(ostream &);
293         void PrintByName(ostream &);
294         ElValue* GetElementByNumber(guint32 group, guint32 element);
295         ElValue* GetElementByName  (string);
296         string   GetElValueByNumber(guint32 group, guint32 element);
297         string   GetElValueByName  (string);
298         TagElValueHT & GetTagHt(void);
299 };
300
301
302 //
303 // ---------------------------------------------------- gdcmHeader
304 //
305 //      C'est le Dicom Header d'une image donnée
306 //      (tous les elements Dicom qui la composent
307 //      + des info 'de service')
308 //
309
310 ////////////////////////////////////////////////////////////////////////////
311 // The typical usage of instances of class gdcmHeader is to classify a set of
312 // dicom files according to header information e.g. to create a file hierarchy
313 // reflecting the Patient/Study/Serie informations, or extracting a given
314 // SerieId. Accesing the content (image[s] or volume[s]) is beyond the
315 // functionality of this class and belong to gdmcFile (see below).
316 // Notes:
317 // * the various entries of the explicit value representation (VR) shall
318 //   be managed within a dictionary which is shared by all gdcmHeader instances
319 // * the gdcmHeader::Set*Tag* family members cannot be defined as protected
320 //   (Swig limitations for as Has_a dependency between gdcmFile and gdcmHeader)
321  
322
323 typedef string VRKey;   // Ne devrait-elle pas etre utilisee dans la definition de VRHT ?
324 typedef string VRAtr;
325 typedef map<TagKey, VRAtr> VRHT;    // Value Representation Hash Table
326                 // Cette Table de Hachage ne devrait servir qu'a determiner
327                 // si deux caractères correspondent à une VR existante ?        
328
329 class GDCM_EXPORT gdcmHeader {
330         void SkipBytes(guint32);
331 private:
332         static VRHT *dicom_vr;
333         // Dictionaries of data elements:
334         
335         // Question :
336         // Pourquoi mettre un pointeur statique vers le container des dictionnaires
337         // (qui est une H-table de pointeurs vers des dictionnaires)
338         // en plus des pointeurs vers chacun des dictionnaires ?
339         // Ces derniers n'auraient-ils pas suffit ?
340         //
341         static gdcmDictSet* Dicts;  // global dictionary container
342         gdcmDict* RefPubDict;       // public dictionary
343         gdcmDict* RefShaDict;       // shadow dictionary (optional)
344         // Parsed element values:
345         ElValSet PubElVals;         // parsed with Public Dictionary
346         ElValSet ShaElVals;         // parsed with Shadow Dictionary
347         string filename;            // refering underlying file
348         FILE * fp;
349         // The tag Image Location ((0028,0200) containing the address of
350         // the pixels) is not allways present. Then we store this information
351         
352         // FIXME
353         
354         // Question :
355         // Qu'y a-t-il a corriger ?
356         //
357         // outside of the elements:
358         guint16 grPixel;
359         guint16 numPixel;
360         // Ne faudrait-il pas une indication sur la presence ou non
361         // du 'groupe des pixels' dans l'entete?
362         // (voir pb du DICOMDIR)
363         
364         // Swap code (little, big, bad-big, bad-little endian): this code is not fixed
365         // during parsing.FIXME sw should be an enum e.g.
366         //enum EndianType {
367                 //LittleEndian, 
368                 //BadLittleEndian,
369                 //BigEndian, 
370                 //BadBigEndian};
371         int sw;
372
373         // Only the elements whose size is below this bound will be loaded.
374         // By default, this upper bound is limited to 1024 (which looks reasonable
375         // when one considers the definition of the various VR contents).
376         guint32 MaxSizeLoadElementValue;
377
378         guint16 ReadInt16(void);
379         guint32 ReadInt32(void);
380         guint16 SwapShort(guint16);
381         guint32 SwapLong(guint32);
382         void Initialise(void);
383         void CheckSwap(void);
384         void FindLength(ElValue *);
385         guint32 FindLengthOB(void);
386         void FindVR(ElValue *);
387         void LoadElementValue(ElValue *);
388         void LoadElementValueSafe(ElValue *);
389         void SkipElementValue(ElValue *);
390         void InitVRDict(void);
391         void SwitchSwapToBigEndian(void);
392         void FixFoundLength(ElValue*, guint32);
393         bool IsAnInteger(ElValue *);
394         
395         bool IsImplicitVRLittleEndianTransferSyntax(void);
396         bool IsExplicitVRLittleEndianTransferSyntax(void);
397         bool IsDeflatedExplicitVRLittleEndianTransferSyntax(void);
398         bool IsExplicitVRBigEndianTransferSyntax(void);
399         bool IsJPEGBaseLineProcess1TransferSyntax(void);
400         bool IsJPEGExtendedProcess2_4TransferSyntax(void);      
401         bool IsJPEGExtendedProcess3_5TransferSyntax(void);
402         bool IsJPEGSpectralSelectionProcess6_8TransferSyntax(void);     
403 //
404 // Euhhhhhhh
405 // Il y en a encore DIX-SEPT, comme ça.
406 // Il faudrait trouver qq chose + rusé ...
407 //      
408                 
409         void SetMaxSizeLoadElementValue(long);
410         ElValue       * ReadNextElement(void);
411         gdcmDictEntry * IsInDicts(guint32, guint32);
412 protected:
413         enum FileType {
414                 Unknown = 0,
415                 TrueDicom,
416                 ExplicitVR,
417                 ImplicitVR,
418                 ACR,
419                 ACR_LIBIDO};  // CLEANME
420         FileType filetype;
421         int write(ostream&);   
422         int anonymize(ostream&);  // FIXME : anonymize should be a friend ?
423 public:
424         void LoadElements(void);
425         virtual void ParseHeader(void);
426         gdcmHeader(const char* filename);
427         virtual ~gdcmHeader();
428         
429         size_t GetPixelOffset(void);
430         void   GetPixels(size_t, void *);
431         int    GetSwapCode(void) { return sw; }
432
433         // TODO Swig int SetPubDict(string filename);
434         // When some proprietary shadow groups are disclosed, we can set up
435         // an additional specific dictionary to access extra information.
436         // TODO Swig int SetShaDict(string filename);
437
438         // Retrieve all potentially available tag [tag = (group, element)] names
439         // from the standard (or public) dictionary. Typical usage: enable the
440         // user of a GUI based interface to select his favorite fields for sorting
441         // or selecting.
442         list<string> * GetPubTagNames(void);
443         map<string, list<string> > * GetPubTagNamesByCategory(void);
444         // Get the element values themselves:
445         
446         string GetPubElValByName(string TagName);
447         string GetPubElValByNumber(guint16 group, guint16 element);
448
449         // Getting the element value representation (VR) might be needed by caller
450         // to convert the string typed content to caller's native type 
451         // (think of C/C++ vs Python).
452
453         string GetPubElValRepByName(string TagName);
454         string GetPubElValRepByNumber(guint16 group, guint16 element);
455
456         TagElValueHT & GetPubElVal(void) { return PubElVals.GetTagHt(); };
457         void   PrintPubElVal(ostream & os = cout);
458         void   PrintPubDict(ostream &);
459           
460         // Same thing with the shadow :
461         // TODO Swig string* GetShaTagNames(); 
462         string GetShaElValByName(string TagName);
463         string GetShaElValByNumber(guint16 group, guint16 element);
464         string GetShaElValRepByName(string TagName);
465         string GetShaElValRepByNumber(guint16 group, guint16 element);
466
467         // Wrappers of the above (public is privileged over shadow) to avoid
468         // bugging the caller with knowing if ElVal is from the public or shadow
469         // dictionary.
470         string GetElValByName(string TagName);
471         string GetElValByNumber(guint16 group, guint16 element);
472         string GetElValRepByName(string TagName);
473         string GetElValRepByNumber(guint16 group, guint16 element);
474
475         // TODO Swig int SetPubElValByName(string content, string TagName);
476         // TODO Swig int SetPubElValByNumber(string content, guint16 group, guint16 element);
477         // TODO Swig int SetShaElValByName(string content, string ShadowTagName);
478         // TODO Swig int SetShaElValByNumber(string content, guint16 group, guint16 element);
479
480         // TODO Swig int GetSwapCode();
481 };
482
483 //
484 // ---------------------------------------------------- gdcmFile
485 //
486 //      un fichier EST_UNE entete, ou A_UNE entete ?
487 //
488 //
489
490
491 ////////////////////////////////////////////////////////////////////////////
492 // In addition to Dicom header exploration, this class is designed
493 // for accessing the image/volume content. One can also use it to
494 // write Dicom files.
495 ////// QUESTION: this looks still like an open question wether the
496 //////           relationship between a gdcmFile and gdcmHeader is of
497 //////           type IS_A or HAS_A !
498
499 class GDCM_EXPORT gdcmFile: public gdcmHeader
500 {
501 private:
502         // QUESTION :
503         // Data pointe sur quoi?
504         // sur les Pixels lus?
505         // --> j'ajoute un champ public : Pixels
506         
507         void* Data;
508         int Parsed;          // weather allready parsed
509         string OrigFileName; // To avoid file overwrite
510 public:
511         // je ne suis pas sur d'avoir compris *où* il serait légitime de ranger ca.
512         // on pourra tjs le deplacer, et mettre des accesseurs
513         void * Pixels;
514         size_t lgrTotale;
515         
516         // Constructor dedicated to writing a new DICOMV3 part10 compliant
517         // file (see SetFileName, SetDcmTag and Write)
518         // TODO Swig gdcmFile();
519         // Opens (in read only and when possible) an existing file and checks
520         // for DICOM compliance. Returns NULL on failure.
521         // Note: the in-memory representation of all available tags found in
522         //    the DICOM header is post-poned to first header information access.
523         //    This avoid a double parsing of public part of the header when
524         //    one sets an a posteriori shadow dictionary (efficiency can be
525         //    seen as a side effect).
526         
527         gdcmFile(string & filename);
528         
529         // For promotion (performs a deepcopy of pointed header object)
530         // TODO Swig gdcmFile(gdcmHeader* header);
531         // TODO Swig ~gdcmFile();
532
533         // On writing purposes. When instance was created through
534         // gdcmFile(string filename) then the filename argument MUST be different
535         // from the constructor's one (no overwriting allowed).
536         // TODO Swig int SetFileName(string filename);
537
538         // Allocates necessary memory, copies the data (image[s]/volume[s]) to
539         // newly allocated zone and return a pointer to it:
540         
541          void * GetImageData();
542         
543         // Returns size (in bytes) of required memory to contain data
544         // represented in this file.
545         
546         size_t GetImageDataSize();
547         
548         // Copies (at most MaxSize bytes) of data to caller's memory space.
549         // Returns an error code on failure (if MaxSize is not big enough)
550         
551         int PutImageDataHere(void* destination, size_t MaxSize );
552         
553         // Allocates ExpectedSize bytes of memory at this->Data and copies the
554         // pointed data to it.
555         // TODO Swig int SetImageData(void * Data, size_t ExpectedSize);
556         // Push to disk.
557         // A NE PAS OUBLIER : que fait-on en cas de Transfert Syntax (dans l'entete)
558         // incohérente avec l'ordre des octets en mémoire  
559         // TODO Swig int Write();
560         
561         // Ecrit sur disque les pixels d'UNE image
562         // Aucun test n'est fait sur l'"Endiannerie" du processeur.
563         // C'est à l'utilisateur d'appeler son Reader correctement
564                 
565         int WriteRawData (string nomFichier);
566 };
567
568 //
569 // ---------------------------------------------------- gdcmSerie
570 //
571 //      une serie EST_UN fichier ????
572 //
573 //
574
575 //class gdcmSerie : gdcmFile;
576
577 //
578 // ---------------------------------------------------- gdcmMultiFrame
579 //
580 //      un fichierMultiFrame EST_UN fichier 
581 //
582 //
583
584 //class gdcmMultiFrame : gdcmFile;
585
586