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