]> Creatis software - gdcm.git/blob - src/gdcm.h
* python/demo/*.py load.py extracted from test.py. Added explore.py
[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 SetDictEntry(gdcmDictEntry *NewEntry) { entry = NewEntry; };
167
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         void    SetVR(string);
175         string  GetVR(void);
176         string  GetValue(void)   { return value; };
177         guint32 GetLength(void)  { return LgrElem; };
178         size_t  GetOffset(void)  { return Offset; };
179         guint16 GetGroup(void)   { return entry->GetGroup(); };
180         guint16 GetElement(void) { return entry->GetElement(); };
181         string  GetKey(void)     { return entry->GetKey(); };
182         string  GetName(void)    { return entry->GetName();};
183 };
184
185 typedef map<TagKey, ElValue*> TagElValueHT;
186 typedef map<string, ElValue*> TagElValueNameHT;
187 // Container for a set of succefully parsed ElValues.
188 class GDCM_EXPORT ElValSet {
189         // We need both accesses with a TagKey and the Dictentry.Name
190         TagElValueHT tagHt;
191         TagElValueNameHT NameHt;
192 public:
193         void Add(ElValue*);
194         void Print(ostream &);
195         void PrintByName(ostream &);
196         ElValue* GetElement(guint32 group, guint32 element);
197         string GetElValue(guint32 group, guint32 element);
198         string GetElValue(string);
199         TagElValueHT & GetTagHt(void);
200 };
201
202 // The various entries of the explicit value representation (VR) shall
203 // be managed within a dictionary. 
204 typedef string VRKey;
205 typedef string VRAtr;
206 typedef map<TagKey, VRAtr> VRHT;    // Value Representation Hash Table
207
208 // The typical usage of objects of this class is to classify a set of
209 // dicom files according to header information e.g. to create a file hierachy
210 // reflecting the Patient/Study/Serie informations, or extracting a given
211 // SerieId. Accesing the content (image[s] or volume[s]) is beyond the
212 // functionality of this class (see dmcFile below).
213 // Notes:
214 // * the gdcmHeader::Set*Tag* family members cannot be defined as protected
215 //   (Swig limitations for as Has_a dependency between gdcmFile and gdcmHeader)
216 class GDCM_EXPORT gdcmHeader {
217 //FIXME sw should be qn EndianType !!!
218         //enum EndianType {
219                 //LittleEndian, 
220                 //BadLittleEndian,
221                 //BigEndian, 
222                 //BadBigEndian};
223 private:
224         // All instances share the same Value Representation dictionary
225         static VRHT *dicom_vr;
226         // Dictionaries of data elements:
227         static gdcmDictSet* Dicts;  // Global dictionary container
228         gdcmDict* RefPubDict;       // Public Dictionary
229         gdcmDict* RefShaDict;       // Shadow Dictionary (optional)
230         // Parsed element values:
231         ElValSet PubElVals;         // parsed with Public Dictionary
232         ElValSet ShaElVals;         // parsed with Shadow Dictionary
233         // In order to inspect/navigate through the file
234         string filename;
235         FILE * fp;
236         // The tag Image Location ((0028,0200) containing the adress of
237         // the pixels) is not allways present. When we store this information
238         // FIXME
239         // outside of the elements:
240         guint16 grPixel;
241         guint16 numPixel;
242         // Swap code (little, big, big-bad endian): this code is not fixed
243         // during parsing.
244         int sw;
245         // Only the elements whose size are below this bound shall be loaded.
246         // By default, this upper bound is limited to 1024 (which looks reasonable
247         // when one considers the definition of the various VR contents).
248         guint32 MaxSizeLoadElementValue;
249
250         guint16 ReadInt16(void);
251         guint32 ReadInt32(void);
252         guint16 SwapShort(guint16);
253         guint32 SwapLong(guint32);
254         void Initialise(void);
255         void CheckSwap(void);
256         void FindLength(ElValue *);
257         void FindVR(ElValue *);
258         void LoadElementValue(ElValue *);
259         void LoadElementValueSafe(ElValue *);
260         void SkipElementValue(ElValue *);
261         void InitVRDict(void);
262         void SwitchSwapToBigEndian(void);
263         void FixFoundLength(ElValue*, guint32);
264         bool IsAnInteger(ElValue *);
265         bool IsBigEndianTransferSyntax(void);
266         void SetMaxSizeLoadElementValue(long);
267         ElValue       * ReadNextElement(void);
268         gdcmDictEntry * IsInDicts(guint32, guint32);
269         size_t GetPixelOffset(void);
270 protected:
271         enum FileType {
272                 Unknown = 0,
273                 TrueDicom,
274                 ExplicitVR,
275                 ImplicitVR,
276                 ACR,
277                 ACR_LIBIDO};
278         FileType filetype;
279 ///// QUESTION: Maybe Print is a better name than write !?
280         int write(ostream&);   
281 ///// QUESTION: Maybe anonymize should be a friend function !?!?
282 /////           See below for an example of how anonymize might be implemented.
283         int anonymize(ostream&);
284 public:
285         void LoadElements(void);
286         virtual void ParseHeader(void);
287         gdcmHeader(const char* filename);
288         virtual ~gdcmHeader();
289
290         // TODO Swig int SetPubDict(string filename);
291         // When some proprietary shadow groups are disclosed, whe can set
292         // up an additional specific dictionary to access extra information.
293         // TODO Swig int SetShaDict(string filename);
294
295         // Retrieve all potentially available tag [tag = (group, element)] names
296         // from the standard (or public) dictionary (hence static). Typical usage:
297         // enable the user of a GUI based interface to select his favorite fields
298         // for sorting or selection.
299         // TODO Swig string* GetPubTagNames();
300         // Get the element values themselves:
301         string GetPubElValByName(string TagName);
302         string GetPubElValByNumber(guint16 group, guint16 element);
303         // Get the element value representation: (VR) might be needed by caller
304         // to convert the string typed content to caller's native type (think
305         // of C/C++ vs Python).
306         // TODO Swig string GetPubElValRepByName(string TagName);
307         // TODO Swig string GetPubElValRepByNumber(guint16 group, guint16 element);
308         TagElValueHT & GetPubElVal(void) { return PubElVals.GetTagHt(); };
309         void   PrintPubElVal(ostream & os = cout);
310         void   PrintPubDict(ostream &);
311           
312         // Same thing with the shadow :
313         // TODO Swig string* GetShaTagNames(); 
314         // TODO Swig string GetShaElValByName(string TagName);
315         // TODO Swig string GetShaElValByNumber(guint16 group, guint16 element);
316         // TODO Swig string GetShaElValRepByName(string TagName);
317         // TODO Swig string GetShaElValRepByNumber(guint16 group, guint16 element);
318
319         // Wrappers of the above (both public and shadow) to avoid bugging the
320         // caller with knowing if ElVal is from the public or shadow dictionary.
321         // TODO Swig string GetElValByName(string TagName);
322         // TODO Swig string GetElValByNumber(guint16 group, guint16 element);
323         // TODO Swig string GetElValRepByName(string TagName);
324         // TODO Swig string GetElValRepByNumber(guint16 group, guint16 element);
325
326         // TODO Swig int SetPubElValByName(string content, string TagName);
327         // TODO Swig int SetPubElValByNumber(string content, guint16 group, guint16 element);
328         // TODO Swig int SetShaElValByName(string content, string ShadowTagName);
329         // TODO Swig int SetShaElValByNumber(string content, guint16 group, guint16 element);
330
331         // TODO Swig int GetSwapCode();
332 };
333
334 // In addition to Dicom header exploration, this class is designed
335 // for accessing the image/volume content. One can also use it to
336 // write Dicom files.
337 ////// QUESTION: this looks still like an open question wether the
338 //////           relationship between a gdcmFile and gdcmHeader is of
339 //////           type IS_A or HAS_A !
340 class GDCM_EXPORT gdcmFile: gdcmHeader
341 {
342 private:
343         void* Data;
344         int Parsed;                             // weather allready parsed
345         string OrigFileName;    // To avoid file overwrite
346 public:
347         // Constructor dedicated to writing a new DICOMV3 part10 compliant
348         // file (see SetFileName, SetDcmTag and Write)
349         // TODO Swig gdcmFile();
350         // Opens (in read only and when possible) an existing file and checks
351         // for DICOM compliance. Returns NULL on failure.
352         // Note: the in-memory representation of all available tags found in
353         //    the DICOM header is post-poned to first header information access.
354         //    This avoid a double parsing of public part of the header when
355         //    one sets an a posteriori shadow dictionary (efficiency can be
356         //    seen a a side effect).
357         gdcmFile(string & filename);
358         // For promotion (performs a deepcopy of pointed header object)
359         // TODO Swig gdcmFile(gdcmHeader* header);
360         // TODO Swig ~gdcmFile();
361
362         // On writing purposes. When instance was created through
363         // gdcmFile(string filename) then the filename argument MUST be different
364         // from the constructor's one (no overwriting aloud).
365         // TODO Swig int SetFileName(string filename);
366
367         // Allocates necessary memory, copies the data (image[s]/volume[s]) to
368         // newly allocated zone and return a pointer to it:
369         // TODO Swig void * GetImageData();
370         // Returns size (in bytes) of required memory to contain data
371         // represented in this file.
372         // TODO Swig size_t GetImageDataSize();
373         // Copies (at most MaxSize bytes) of data to caller's memory space.
374         // Returns an error code on failure (if MaxSize is not big enough)
375         // TODO Swig int PutImageDataHere(void* destination, size_t MaxSize );
376         // Allocates ExpectedSize bytes of memory at this->Data and copies the
377         // pointed data to it.
378         // TODO Swig int SetImageData(void * Data, size_t ExpectedSize);
379         // Push to disk.
380         // TODO Swig int Write();
381 };
382
383 //class gdcmSerie : gdcmFile;
384 //class gdcmMultiFrame : gdcmFile;
385
386 //
387 //Examples:
388 // * gdcmFile WriteDicom;
389 //   WriteDicom.SetFileName("MyDicomFile.dcm");
390 //      string * AllTags = gdcmHeader.GetDcmTagNames();
391 //   WriteDicom.SetDcmTag(AllTags[5], "253");
392 //   WriteDicom.SetDcmTag("Patient Name", "bozo");
393 //   WriteDicom.SetDcmTag("Patient Name", "bozo");
394 //      WriteDicom.SetImageData(Image);
395 //   WriteDicom.Write();
396 //
397 //
398 //   Anonymize(ostream& output) {
399 //   a = gdcmFile("toto1");
400 //   a.SetPubValueByName("Patient Name", "");
401 //   a.SetPubValueByName("Date", "");
402 //   a.SetPubValueByName("Study Date", "");
403 //   a.write(output);
404 //   }