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