]> Creatis software - gdcm.git/blob - src/gdcm.h
* python/testSuite.py unittest test suite added (uses Data)
[gdcm.git] / src / gdcm.h
1 // gdcmlib Intro:  
2 // * gdcmlib is a library dedicated to reading and writing dicom files.
3 // * LGPL for the license
4 // * lightweigth as opposed to CTN or DCMTK wich come bundled which try
5 //   to implement the full DICOM standard (networking...). gdcmlib concentrates
6 //   on reading and 
7 // * Formats: this lib should be able to read ACR-NEMA v1 and v2, Dicom v3 (as
8 //   stated in part10). [cf dcmtk/dcmdata/docs/datadict.txt]
9 // * Targeted plateforms: Un*xes and Win32/VC++6.0
10 //
11 //
12 // TODO
13 // The declarations commented out and starting with "TODO Swig" needed
14 // to be temporarily removed for swig to proceed correctly (in fact
15 // problems appears at loading of _gdcm.[so/dll]). So, simply uncomment
16 // the declaration once you provided the definition of the method...
17
18 #include <string>
19 #include <iostream>
20 #include <stddef.h>   // For size_t
21 #include <stdio.h>    // FIXME For FILE on GCC only
22 #include <map>        // The requirement for the hash table (or map) that
23                       // we shall use:
24                       // 1/ First, next, last (iterators)
25                       // 2/ should be sortable (i.e. sorted by TagKey). This
26                       //    condition shall be droped since the Win32/VC++
27                       //    implementation doesn't look a sorted one. Pffff....
28                       // 3/ Make sure we can setup some default size value,
29                       //    which should be around 4500 entries which is the
30                       //    average dictionary size (said JPR)
31 #ifdef __GNUC__
32 #include <stdint.h>
33 #define guint16 uint16_t
34 #define guint32 uint32_t
35 #define g_malloc malloc
36 #define g_free   free
37 #endif
38 #ifdef _MSC_VER
39 #include <glib.h>
40 #endif
41
42 #ifdef _MSC_VER
43         using namespace std;  // string type lives in the std namespace on VC++
44 #endif
45 #ifdef _MSC_VER
46 #define GDCM_EXPORT __declspec( dllexport )
47 #else
48 #define GDCM_EXPORT
49 #endif
50
51 // Tag based hash tables.
52 // We shall use as keys the strings (as the C++ type) obtained by
53 // concatenating the group value and the element value (both of type
54 // unsigned 16 bit integers in Dicom) expressed in hexadecimal.
55 // Example: consider the tag given as (group, element) = (0x0010, 0x0010).
56 // Then the corresponding TagKey shall be the string 0010|0010 (where
57 // the | (pipe symbol) acts as a separator). Refer to 
58 // gdcmDictEntry::TranslateToKey for this conversion function.
59 typedef string TagKey;
60
61 class GDCM_EXPORT gdcmDictEntry {
62 private:
63         guint16 group;    // e.g. 0x0010
64         guint16 element;  // e.g. 0x0010
65         string  vr;       // Value Representation i.e. some clue about the nature
66                           // of the data represented e.g. "FD" short for
67                           // "Floating Point Double"
68         // CLEAN ME: find the official dicom name for this field !
69         string  fourth;   // Fourth field containing some semantics.
70         string  name;     // e.g. "Patient_Name"
71         TagKey  key;      // This is redundant zith (group, element) but we add
72                           // on efficiency purposes.
73         // DCMTK has many fields for handling a DictEntry (see below). What are the
74         // relevant ones for gdcmlib ?
75         //      struct DBI_SimpleEntry {
76         //         Uint16 group;
77         //         Uint16 element;
78         //         Uint16 upperGroup;
79         //         Uint16 upperElement;
80         //         DcmEVR evr;
81         //         const char* tagName;
82         //         int vmMin;
83         //         int vmMax;
84         //         const char* standardVersion;
85         //         DcmDictRangeRestriction groupRestriction;
86         //         DcmDictRangeRestriction elementRestriction;
87         //       };
88 public:
89         //CLEANME gdcmDictEntry();
90         gdcmDictEntry(guint16 group, guint16 element,
91                       string vr     = "Unknown",
92                                           string fourth = "Unknown",
93                                           string name   = "Unknown");
94         static TagKey TranslateToKey(guint16 group, guint16 element);
95         guint16 GetGroup(void)  { return group;};
96         guint16 GetElement(void){return element;};
97         string  GetVR(void)     {return vr; };
98         void    SetVR(string);
99         bool    IsVrUnknown(void);
100         string  GetFourth(void) {return fourth;};
101         string  GetName(void)   {return name;};
102         string  GetKey(void)    {return key;};
103 };
104   
105 typedef map<TagKey, gdcmDictEntry*> TagHT;
106
107 // A single DICOM dictionary i.e. a container for a collection of dictionary
108 // entries. There should be a single public dictionary (THE dictionary of
109 // the actual DICOM v3) but as many shadow dictionaries as imagers 
110 // combined with all software versions...
111 class GDCM_EXPORT gdcmDict {
112         string name;
113         string filename;
114         TagHT entries;
115 public:
116         gdcmDict(const char* FileName);   // Read Dict from disk
117         // TODO Swig int AppendEntry(gdcmDictEntry* NewEntry);
118         gdcmDictEntry * GetTag(guint32 group, guint32 element);
119         void Print(ostream&);
120 };
121
122 // Container for managing a set of loaded dictionaries. Sharing dictionaries
123 // should avoid :
124 // * reloading an allready loaded dictionary.
125 // * having many in memory representations of the same dictionary.
126 typedef string DictKey;
127 typedef map<DictKey, gdcmDict*> DictSetHT;
128 class GDCM_EXPORT gdcmDictSet {
129 private:
130         string DictPath;      // Directory path to dictionaries
131         DictSetHT dicts;
132         int AppendDict(gdcmDict* NewDict);
133         int LoadDictFromFile(string filename, DictKey);
134         void SetDictPath(void);
135 public:
136         gdcmDictSet(void);    // loads THE DICOM v3 dictionary
137         // TODO Swig int LoadDictFromFile(string filename);
138 ///// QUESTION: the following function might not be thread safe !? Maybe
139 /////           we need some mutex here, to avoid concurent creation of
140 /////           the same dictionary !?!?!
141         // TODO Swig int LoadDictFromName(string filename);
142         // TODO Swig int LoadAllDictFromDirectory(string DirectoryName);
143         // TODO Swig string* GetAllDictNames();
144         int LoadDicomV3Dict(void);
145         void Print(ostream&);
146         gdcmDict* GetDict(DictKey DictName);
147         gdcmDict* GetDefaultPublicDict(void);
148 };
149
150 // The dicom header of a Dicom file contains a set of such ELement VALUES
151 // (when successfuly parsed against a given Dicom dictionary)
152 class GDCM_EXPORT ElValue {
153 private:
154         gdcmDictEntry *entry;
155         guint32 LgrElem;
156         bool ImplicitVr;       // Even when reading explicit vr files, some
157                                // elements happen to be implicit. Flag them here
158                                // since we can't use the entry->vr without breaking
159                                // the underlying dictionary.
160         // Might prove of some interest (see _ID_DCM_ELEM)
161         // int Swap;
162 public:
163         string  value;     // used to be char * valeurElem
164         size_t Offset;     // Offset from the begining of file for direct user access
165         ElValue(gdcmDictEntry*);
166         void   SetVR(string);
167         string GetVR(void);
168         bool   IsVrUnknown(void) { return entry->IsVrUnknown(); };
169         void SetLength(guint32 l){LgrElem = l; };
170         void SetValue(string val){ value = val; };
171         void SetOffset(size_t of){ Offset = of; };
172         void SetImplicitVr(void) { ImplicitVr = true; };
173         bool  IsImplicitVr(void) { return ImplicitVr; };
174         string  GetValue(void)   { return value; };
175         guint32 GetLength(void)  { return LgrElem; };
176         size_t  GetOffset(void)  { return Offset; };
177         guint16 GetGroup(void)   { return entry->GetGroup(); };
178         guint16 GetElement(void) { return entry->GetElement(); };
179         string  GetKey(void)     { return entry->GetKey(); };
180         string  GetName(void)    { return entry->GetName();};
181 };
182
183 typedef map<TagKey, ElValue*> TagElValueHT;
184 typedef map<string, ElValue*> TagElValueNameHT;
185 // Container for a set of succefully parsed ElValues.
186 class GDCM_EXPORT ElValSet {
187         // We need both accesses with a TagKey and the Dicentry.Name
188         TagElValueHT tagHt;
189         TagElValueNameHT NameHt;
190 public:
191         void Add(ElValue*);
192         void Print(ostream &);
193         void PrintByName(ostream &);
194         ElValue* GetElement(guint32 group, guint32 element);
195         string GetElValue(guint32 group, guint32 element);
196         string GetElValue(string);
197         TagElValueHT & GetTagHt(void);
198 };
199
200 // The various entries of the explicit value representation (VR) shall
201 // be managed within a dictionary. 
202 typedef string VRKey;
203 typedef string VRAtr;
204 typedef map<TagKey, VRAtr> VRHT;    // Value Representation Hash Table
205
206 // The typical usage of objects of this class is to classify a set of
207 // dicom files according to header information e.g. to create a file hierachy
208 // reflecting the Patient/Study/Serie informations, or extracting a given
209 // SerieId. Accesing the content (image[s] or volume[s]) is beyond the
210 // functionality of this class (see dmcFile below).
211 // Notes:
212 // * the gdcmHeader::Set*Tag* family members cannot be defined as protected
213 //   (Swig limitations for as Has_a dependency between gdcmFile and gdcmHeader)
214 class GDCM_EXPORT gdcmHeader {  
215 //FIXME sw should be qn EndianType !!!
216         //enum EndianType {
217                 //LittleEndian, 
218                 //BadLittleEndian,
219                 //BigEndian, 
220                 //BadBigEndian};
221 private:
222         // All instances share the same value representation dictionary
223         static VRHT *dicom_vr;
224         static gdcmDictSet* Dicts;  // Global dictionary container
225         gdcmDict* RefPubDict;       // Public Dictionary
226         gdcmDict* RefShaDict;       // Shadow Dictionary (optional)
227         ElValSet PubElVals;     // Element Values parsed with Public Dictionary
228         ElValSet ShaElVals;     // Element Values parsed with Shadow Dictionary
229         // In order to inspect/navigate through the file
230         string filename;
231         FILE * fp;
232         // The tag Image Location ((0028,0200) containing the adress of
233         // the pixels) is not allways present. When we store this information
234         // FIXME
235         // outside of the elements:
236         guint16 grPixel;
237         guint16 numPixel;
238         int sw;
239
240         guint16 ReadInt16(void);
241         guint32 ReadInt32(void);
242         guint16 SwapShort(guint16);
243         guint32 SwapLong(guint32);
244         void Initialise(void);
245         void CheckSwap(void);
246         void FindLength(ElValue *);
247         void FindVR(ElValue *);
248         void LoadElementValue(ElValue *);
249         void SkipElementValue(ElValue *);
250         void InitVRDict(void);
251         bool IsAnInteger(guint16, guint16, string, guint32);
252         ElValue * ReadNextElement(void);
253         gdcmDictEntry * IsInDicts(guint32, guint32);
254         size_t GetPixelOffset(void);
255 protected:
256         enum FileType {
257                 Unknown = 0,
258                 TrueDicom,
259                 ExplicitVR,
260                 ImplicitVR,
261                 ACR,
262                 ACR_LIBIDO};
263         FileType filetype;
264 ///// QUESTION: Maybe Print is a better name than write !?
265         int write(ostream&);   
266 ///// QUESTION: Maybe anonymize should be a friend function !?!?
267 /////           See below for an example of how anonymize might be implemented.
268         int anonymize(ostream&);
269 public:
270         void LoadElements(void);
271         virtual void ParseHeader(void);
272         gdcmHeader(const char* filename);
273         virtual ~gdcmHeader();
274
275         // TODO Swig int SetPubDict(string filename);
276         // When some proprietary shadow groups are disclosed, whe can set
277         // up an additional specific dictionary to access extra information.
278         // TODO Swig int SetShaDict(string filename);
279
280         // Retrieve all potentially available tag [tag = (group, element)] names
281         // from the standard (or public) dictionary (hence static). Typical usage:
282         // enable the user of a GUI based interface to select his favorite fields
283         // for sorting or selection.
284         // TODO Swig string* GetPubTagNames();
285         // Get the element values themselves:
286         string GetPubElValByName(string TagName);
287         string GetPubElValByNumber(guint16 group, guint16 element);
288         // Get the element value representation: (VR) might be needed by caller
289         // to convert the string typed content to caller's native type (think
290         // of C/C++ vs Python).
291         // TODO Swig string GetPubElValRepByName(string TagName);
292         // TODO Swig string GetPubElValRepByNumber(guint16 group, guint16 element);
293         TagElValueHT & GetPubElVal(void) { return PubElVals.GetTagHt(); };
294         void   PrintPubElVal(ostream & os = cout);
295         void   PrintPubDict(ostream &);
296           
297         // Same thing with the shadow :
298         // TODO Swig string* GetShaTagNames(); 
299         // TODO Swig string GetShaElValByName(string TagName);
300         // TODO Swig string GetShaElValByNumber(guint16 group, guint16 element);
301         // TODO Swig string GetShaElValRepByName(string TagName);
302         // TODO Swig string GetShaElValRepByNumber(guint16 group, guint16 element);
303
304         // Wrappers of the above (both public and shadow) to avoid bugging the
305         // caller with knowing if ElVal is from the public or shadow dictionary.
306         // TODO Swig string GetElValByName(string TagName);
307         // TODO Swig string GetElValByNumber(guint16 group, guint16 element);
308         // TODO Swig string GetElValRepByName(string TagName);
309         // TODO Swig string GetElValRepByNumber(guint16 group, guint16 element);
310
311         // TODO Swig int SetPubElValByName(string content, string TagName);
312         // TODO Swig int SetPubElValByNumber(string content, guint16 group, guint16 element);
313         // TODO Swig int SetShaElValByName(string content, string ShadowTagName);
314         // TODO Swig int SetShaElValByNumber(string content, guint16 group, guint16 element);
315
316         // TODO Swig int GetSwapCode();
317 };
318
319 // In addition to Dicom header exploration, this class is designed
320 // for accessing the image/volume content. One can also use it to
321 // write Dicom files.
322 ////// QUESTION: this looks still like an open question wether the
323 //////           relationship between a gdcmFile and gdcmHeader is of
324 //////           type IS_A or HAS_A !
325 class GDCM_EXPORT gdcmFile: gdcmHeader
326 {
327 private:
328         void* Data;
329         int Parsed;                             // weather allready parsed
330         string OrigFileName;    // To avoid file overwrite
331 public:
332         // Constructor dedicated to writing a new DICOMV3 part10 compliant
333         // file (see SetFileName, SetDcmTag and Write)
334         // TODO Swig gdcmFile();
335         // Opens (in read only and when possible) an existing file and checks
336         // for DICOM compliance. Returns NULL on failure.
337         // Note: the in-memory representation of all available tags found in
338         //    the DICOM header is post-poned to first header information access.
339         //    This avoid a double parsing of public part of the header when
340         //    one sets an a posteriori shadow dictionary (efficiency can be
341         //    seen a a side effect).
342         gdcmFile(string & filename);
343         // For promotion (performs a deepcopy of pointed header object)
344         // TODO Swig gdcmFile(gdcmHeader* header);
345         // TODO Swig ~gdcmFile();
346
347         // On writing purposes. When instance was created through
348         // gdcmFile(string filename) then the filename argument MUST be different
349         // from the constructor's one (no overwriting aloud).
350         // TODO Swig int SetFileName(string filename);
351
352         // Allocates necessary memory, copies the data (image[s]/volume[s]) to
353         // newly allocated zone and return a pointer to it:
354         // TODO Swig void * GetImageData();
355         // Returns size (in bytes) of required memory to contain data
356         // represented in this file.
357         // TODO Swig size_t GetImageDataSize();
358         // Copies (at most MaxSize bytes) of data to caller's memory space.
359         // Returns an error code on failure (if MaxSize is not big enough)
360         // TODO Swig int PutImageDataHere(void* destination, size_t MaxSize );
361         // Allocates ExpectedSize bytes of memory at this->Data and copies the
362         // pointed data to it.
363         // TODO Swig int SetImageData(void * Data, size_t ExpectedSize);
364         // Push to disk.
365         // TODO Swig int Write();
366 };
367
368 //class gdcmSerie : gdcmFile;
369 //class gdcmMultiFrame : gdcmFile;
370
371 //
372 //Examples:
373 // * gdcmFile WriteDicom;
374 //   WriteDicom.SetFileName("MyDicomFile.dcm");
375 //      string * AllTags = gdcmHeader.GetDcmTagNames();
376 //   WriteDicom.SetDcmTag(AllTags[5], "253");
377 //   WriteDicom.SetDcmTag("Patient Name", "bozo");
378 //   WriteDicom.SetDcmTag("Patient Name", "bozo");
379 //      WriteDicom.SetImageData(Image);
380 //   WriteDicom.Write();
381 //
382 //
383 //   Anonymize(ostream& output) {
384 //   a = gdcmFile("toto1");
385 //   a.SetPubValueByName("Patient Name", "");
386 //   a.SetPubValueByName("Date", "");
387 //   a.SetPubValueByName("Study Date", "");
388 //   a.write(output);
389 //   }