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