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