]> Creatis software - gdcm.git/blob - src/gdcmlib.h
* Truckload of changes. Parsing of header is barely functional
[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 LgrLueElem; // Longueur Lue
129         // Might prove of some interest (see _ID_DCM_ELEM)
130         // int Swap;
131 public:
132         guint32 LgrElem;   // FIXME probably for bad reasons at parse time !
133         string  value;     // used to be char * valeurElem
134         size_t Offset;     // Offset from the begining of file for direct user access
135         ElValue(gdcmDictEntry*);
136         void   SetVR(string);
137         void SetLgrLue(guint32);
138         void SetValue(string val){ value = val; };
139         string  GetValue(void)   { return value; };
140         guint32 GetLgrElem(void) { return LgrElem; };
141         guint16 GetGroup(void)   { return entry->GetGroup(); };
142         guint16 GetElement(void) { return entry->GetElement(); };
143         string  GetKey(void)     { return entry->GetKey(); };
144         string  GetName(void)    { return entry->GetName();};
145 };
146
147 typedef map<TagKey, ElValue*> TagElValueHT;
148 // Container for a set of succefully parsed ElValues.
149 class ElValSet {
150         // We need both accesses with a TagKey and the Dicentry.Name
151         TagElValueHT tagHt;
152         map<string, ElValue*> NameHt;
153 public:
154         int Add(ElValue*);
155         int Print(ostream &);
156 };
157
158 // The various entries of the explicit value representation (VR) shall
159 // be managed within a dictionary. 
160 typedef string VRKey;
161 typedef string VRAtr;
162 typedef map<TagKey, VRAtr> VRHT;    // Value Representation Hash Table
163
164 // The typical usage of objects of this class is to classify a set of
165 // dicom files according to header information e.g. to create a file hierachy
166 // reflecting the Patient/Study/Serie informations, or extracting a given
167 // SerieId. Accesing the content (image[s] or volume[s]) is beyond the
168 // functionality of this class (see dmcFile below).
169 // Notes:
170 // * the gdcmHeader::Set*Tag* family members cannot be defined as protected
171 //   (Swig limitations for as Has_a dependency between gdcmFile and gdcmHeader)
172 class gdcmHeader {      
173         //enum EndianType {
174                 //LittleEndian, 
175                 //BadLittleEndian,
176                 //BigEndian, 
177                 //BadBigEndian};
178         enum FileType {
179                 Unknown = 0,
180                 TrueDicom,
181                 ExplicitVR,
182                 ImplicitVR,
183                 ACR,
184                 ACR_LIBIDO};
185 private:
186         // All instances share the same valur representation dictionary
187         static VRHT *dicom_vr;
188         static gdcmDictSet* Dicts;  // Global dictionary container
189         gdcmDict* RefPubDict;       // Public Dictionary
190         gdcmDict* RefShaDict;       // Shadow Dictionary (optional)
191         ElValSet PubElVals;     // Element Values parsed with Public Dictionary
192         ElValSet ShaElVals;     // Element Values parsed with Shadow Dictionary
193         FileType filetype;
194         // In order to inspect/navigate through the file
195         string filename;
196         size_t taille_fich;
197         FILE * fp;
198         size_t offsetCourant;
199         // The tag Image Location ((0028,0200) containing the adress of
200         // the pixels) is not allways present. When we store this information
201         // FIXME
202         // outside of the elements:
203         guint16 grPixel;
204         guint16 numPixel;
205         bool PixelsTrouves;
206         bool grPixelTrouve;
207         size_t PixelPosition;
208         int sw;
209
210         void Initialise(void);
211         void CheckSwap(void);
212         void setAcrLibido(void);
213         long int RecupLgr(ElValue *, int *);
214         guint32 SwapLong(guint32);
215         short int SwapShort(short int);
216         void InitVRDict(void);
217         ElValue * ReadNextElement(void);
218         gdcmDictEntry * IsInDicts(guint32, guint32);
219         void SetAsidePixelData(ElValue*);
220 protected:
221 ///// QUESTION: Maybe Print is a better name than write !?
222         int write(ostream&);   
223 ///// QUESTION: Maybe anonymize should be a friend function !?!?
224 /////           See below for an example of how anonymize might be implemented.
225         int anonymize(ostream&);
226 public:
227         void BuildHeader(void);
228         gdcmHeader(char* filename);
229         ~gdcmHeader();
230
231         int SetPubDict(string filename);
232         // When some proprietary shadow groups are disclosed, whe can set
233         // up an additional specific dictionary to access extra information.
234         int SetShaDict(string filename);
235
236         // Retrieve all potentially available tag [tag = (group, element)] names
237         // from the standard (or public) dictionary (hence static). Typical usage:
238         // enable the user of a GUI based interface to select his favorite fields
239         // for sorting or selection.
240         string* GetPubTagNames();
241         // Get the element values themselves:
242         string GetPubElValByName(string TagName);
243         string GetPubElValByNumber(guint16 group, guint16 element);
244         // Get the element value representation: (VR) might be needed by caller
245         // to convert the string typed content to caller's native type (think
246         // of C/C++ vs Python).
247         string GetPubElValRepByName(string TagName);
248         string GetPubElValRepByNumber(guint16 group, guint16 element);
249         int    PrintPubElVal(ostream &);
250         void   PrintPubDict(ostream &);
251           
252         // Same thing with the shadow :
253         string* GetShaTagNames(); 
254         string GetShaElValByName(string TagName);
255         string GetShaElValByNumber(guint16 group, guint16 element);
256         string GetShaElValRepByName(string TagName);
257         string GetShaElValRepByNumber(guint16 group, guint16 element);
258
259         // Wrappers of the above (both public and shadow) to avoid bugging the
260         // caller with knowing if ElVal is from the public or shadow dictionary.
261         string GetElValByName(string TagName);
262         string GetElValByNumber(guint16 group, guint16 element);
263         string GetElValRepByName(string TagName);
264         string GetElValRepByNumber(guint16 group, guint16 element);
265
266         int SetPubElValByName(string content, string TagName);
267         int SetPubElValByNumber(string content, guint16 group, guint16 element);
268         int SetShaElValByName(string content, string ShadowTagName);
269         int SetShaElValByNumber(string content, guint16 group, guint16 element);
270
271         int GetSwapCode();
272 };
273
274 // In addition to Dicom header exploration, this class is designed
275 // for accessing the image/volume content. One can also use it to
276 // write Dicom files.
277 ////// QUESTION: this looks still like an open question wether the
278 //////           relationship between a gdcmFile and gdcmHeader is of
279 //////           type IS_A or HAS_A !
280 class gdcmFile: gdcmHeader
281 {
282 private:
283         void* Data;
284         int Parsed;                             // weather allready parsed
285         string OrigFileName;    // To avoid file overwrite
286 public:
287         // Constructor dedicated to writing a new DICOMV3 part10 compliant
288         // file (see SetFileName, SetDcmTag and Write)
289         gdcmFile();
290         // Opens (in read only and when possible) an existing file and checks
291         // for DICOM compliance. Returns NULL on failure.
292         // Note: the in-memory representation of all available tags found in
293         //    the DICOM header is post-poned to first header information access.
294         //    This avoid a double parsing of public part of the header when
295         //    one sets an a posteriori shadow dictionary (efficiency can be
296         //    seen a a side effect).
297         gdcmFile(string & filename);
298         // For promotion (performs a deepcopy of pointed header object)
299         gdcmFile(gdcmHeader* header);
300         ~gdcmFile();
301
302         // On writing purposes. When instance was created through
303         // gdcmFile(string filename) then the filename argument MUST be different
304         // from the constructor's one (no overwriting aloud).
305         int SetFileName(string filename);
306
307         // Allocates necessary memory, copies the data (image[s]/volume[s]) to
308         // newly allocated zone and return a pointer to it:
309         void * GetImageData();
310         // Returns size (in bytes) of required memory to contain data
311         // represented in this file.
312         size_t GetImageDataSize();
313         // Copies (at most MaxSize bytes) of data to caller's memory space.
314         // Returns an error code on failure (if MaxSize is not big enough)
315         int PutImageDataHere(void* destination, size_t MaxSize );
316         // Allocates ExpectedSize bytes of memory at this->Data and copies the
317         // pointed data to it.
318         int SetImageData(void * Data, size_t ExpectedSize);
319         // Push to disk.
320         int Write();
321 };
322
323 //class gdcmSerie : gdcmFile;
324 //class gdcmMultiFrame : gdcmFile;
325
326 //
327 //Examples:
328 // * gdcmFile WriteDicom;
329 //   WriteDicom.SetFileName("MyDicomFile.dcm");
330 //      string * AllTags = gdcmHeader.GetDcmTagNames();
331 //   WriteDicom.SetDcmTag(AllTags[5], "253");
332 //   WriteDicom.SetDcmTag("Patient Name", "bozo");
333 //   WriteDicom.SetDcmTag("Patient Name", "bozo");
334 //      WriteDicom.SetImageData(Image);
335 //   WriteDicom.Write();
336 //
337 //
338 //   Anonymize(ostream& output) {
339 //   a = gdcmFile("toto1");
340 //   a.SetPubValueByName("Patient Name", "");
341 //   a.SetPubValueByName("Date", "");
342 //   a.SetPubValueByName("Study Date", "");
343 //   a.write(output);
344 //   }