]> Creatis software - gdcm.git/blob - src/gdcm.h
* src/gdcm.h and gdcmHeader.cxx are now "Big Endian transfer syntax"
[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 Dicentry.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         static gdcmDictSet* Dicts;  // Global dictionary container
227         gdcmDict* RefPubDict;       // Public Dictionary
228         gdcmDict* RefShaDict;       // Shadow Dictionary (optional)
229         ElValSet PubElVals;     // Element Values parsed with Public Dictionary
230         ElValSet ShaElVals;     // Element Values parsed with Shadow Dictionary
231         // In order to inspect/navigate through the file
232         string filename;
233         FILE * fp;
234         // The tag Image Location ((0028,0200) containing the adress of
235         // the pixels) is not allways present. When we store this information
236         // FIXME
237         // outside of the elements:
238         guint16 grPixel;
239         guint16 numPixel;
240         int sw;
241
242         guint16 ReadInt16(void);
243         guint32 ReadInt32(void);
244         guint16 SwapShort(guint16);
245         guint32 SwapLong(guint32);
246         void Initialise(void);
247         void CheckSwap(void);
248         void FindLength(ElValue *);
249         void FindVR(ElValue *);
250         void LoadElementValue(ElValue *);
251         void LoadElementValueSafe(ElValue *);
252         void SkipElementValue(ElValue *);
253         void InitVRDict(void);
254         void SwitchSwapToBigEndian(void);
255         void FixFoundLength(ElValue*, guint32);
256         bool IsAnInteger(ElValue *);
257         bool IsBigEndianTransferSyntax(void);
258         ElValue * ReadNextElement(void);
259         gdcmDictEntry * IsInDicts(guint32, guint32);
260         size_t GetPixelOffset(void);
261 protected:
262         enum FileType {
263                 Unknown = 0,
264                 TrueDicom,
265                 ExplicitVR,
266                 ImplicitVR,
267                 ACR,
268                 ACR_LIBIDO};
269         FileType filetype;
270 ///// QUESTION: Maybe Print is a better name than write !?
271         int write(ostream&);   
272 ///// QUESTION: Maybe anonymize should be a friend function !?!?
273 /////           See below for an example of how anonymize might be implemented.
274         int anonymize(ostream&);
275 public:
276         void LoadElements(void);
277         virtual void ParseHeader(void);
278         gdcmHeader(const char* filename);
279         virtual ~gdcmHeader();
280
281         // TODO Swig int SetPubDict(string filename);
282         // When some proprietary shadow groups are disclosed, whe can set
283         // up an additional specific dictionary to access extra information.
284         // TODO Swig int SetShaDict(string filename);
285
286         // Retrieve all potentially available tag [tag = (group, element)] names
287         // from the standard (or public) dictionary (hence static). Typical usage:
288         // enable the user of a GUI based interface to select his favorite fields
289         // for sorting or selection.
290         // TODO Swig string* GetPubTagNames();
291         // Get the element values themselves:
292         string GetPubElValByName(string TagName);
293         string GetPubElValByNumber(guint16 group, guint16 element);
294         // Get the element value representation: (VR) might be needed by caller
295         // to convert the string typed content to caller's native type (think
296         // of C/C++ vs Python).
297         // TODO Swig string GetPubElValRepByName(string TagName);
298         // TODO Swig string GetPubElValRepByNumber(guint16 group, guint16 element);
299         TagElValueHT & GetPubElVal(void) { return PubElVals.GetTagHt(); };
300         void   PrintPubElVal(ostream & os = cout);
301         void   PrintPubDict(ostream &);
302           
303         // Same thing with the shadow :
304         // TODO Swig string* GetShaTagNames(); 
305         // TODO Swig string GetShaElValByName(string TagName);
306         // TODO Swig string GetShaElValByNumber(guint16 group, guint16 element);
307         // TODO Swig string GetShaElValRepByName(string TagName);
308         // TODO Swig string GetShaElValRepByNumber(guint16 group, guint16 element);
309
310         // Wrappers of the above (both public and shadow) to avoid bugging the
311         // caller with knowing if ElVal is from the public or shadow dictionary.
312         // TODO Swig string GetElValByName(string TagName);
313         // TODO Swig string GetElValByNumber(guint16 group, guint16 element);
314         // TODO Swig string GetElValRepByName(string TagName);
315         // TODO Swig string GetElValRepByNumber(guint16 group, guint16 element);
316
317         // TODO Swig int SetPubElValByName(string content, string TagName);
318         // TODO Swig int SetPubElValByNumber(string content, guint16 group, guint16 element);
319         // TODO Swig int SetShaElValByName(string content, string ShadowTagName);
320         // TODO Swig int SetShaElValByNumber(string content, guint16 group, guint16 element);
321
322         // TODO Swig int GetSwapCode();
323 };
324
325 // In addition to Dicom header exploration, this class is designed
326 // for accessing the image/volume content. One can also use it to
327 // write Dicom files.
328 ////// QUESTION: this looks still like an open question wether the
329 //////           relationship between a gdcmFile and gdcmHeader is of
330 //////           type IS_A or HAS_A !
331 class GDCM_EXPORT gdcmFile: gdcmHeader
332 {
333 private:
334         void* Data;
335         int Parsed;                             // weather allready parsed
336         string OrigFileName;    // To avoid file overwrite
337 public:
338         // Constructor dedicated to writing a new DICOMV3 part10 compliant
339         // file (see SetFileName, SetDcmTag and Write)
340         // TODO Swig gdcmFile();
341         // Opens (in read only and when possible) an existing file and checks
342         // for DICOM compliance. Returns NULL on failure.
343         // Note: the in-memory representation of all available tags found in
344         //    the DICOM header is post-poned to first header information access.
345         //    This avoid a double parsing of public part of the header when
346         //    one sets an a posteriori shadow dictionary (efficiency can be
347         //    seen a a side effect).
348         gdcmFile(string & filename);
349         // For promotion (performs a deepcopy of pointed header object)
350         // TODO Swig gdcmFile(gdcmHeader* header);
351         // TODO Swig ~gdcmFile();
352
353         // On writing purposes. When instance was created through
354         // gdcmFile(string filename) then the filename argument MUST be different
355         // from the constructor's one (no overwriting aloud).
356         // TODO Swig int SetFileName(string filename);
357
358         // Allocates necessary memory, copies the data (image[s]/volume[s]) to
359         // newly allocated zone and return a pointer to it:
360         // TODO Swig void * GetImageData();
361         // Returns size (in bytes) of required memory to contain data
362         // represented in this file.
363         // TODO Swig size_t GetImageDataSize();
364         // Copies (at most MaxSize bytes) of data to caller's memory space.
365         // Returns an error code on failure (if MaxSize is not big enough)
366         // TODO Swig int PutImageDataHere(void* destination, size_t MaxSize );
367         // Allocates ExpectedSize bytes of memory at this->Data and copies the
368         // pointed data to it.
369         // TODO Swig int SetImageData(void * Data, size_t ExpectedSize);
370         // Push to disk.
371         // TODO Swig int Write();
372 };
373
374 //class gdcmSerie : gdcmFile;
375 //class gdcmMultiFrame : gdcmFile;
376
377 //
378 //Examples:
379 // * gdcmFile WriteDicom;
380 //   WriteDicom.SetFileName("MyDicomFile.dcm");
381 //      string * AllTags = gdcmHeader.GetDcmTagNames();
382 //   WriteDicom.SetDcmTag(AllTags[5], "253");
383 //   WriteDicom.SetDcmTag("Patient Name", "bozo");
384 //   WriteDicom.SetDcmTag("Patient Name", "bozo");
385 //      WriteDicom.SetImageData(Image);
386 //   WriteDicom.Write();
387 //
388 //
389 //   Anonymize(ostream& output) {
390 //   a = gdcmFile("toto1");
391 //   a.SetPubValueByName("Patient Name", "");
392 //   a.SetPubValueByName("Date", "");
393 //   a.SetPubValueByName("Study Date", "");
394 //   a.write(output);
395 //   }