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