4 // * gdcmlib is a library dedicated to reading and writing dicom files.
5 // * LGPL for the license
6 // * lightweigth as opposed to CTN or DCMTK which come bundled which try
7 // to implement the full DICOM standard (networking...). gdcmlib concentrates
8 // on reading and writing
9 // * Formats: this lib should be able to read ACR-NEMA v1 and v2, Dicom v3 (as
10 // stated in part10). [cf dcmtk/dcmdata/docs/datadict.txt]
11 // * Targeted plateforms: Un*xes and Win32/VC++6.0
15 // The declarations commented out and starting with "TODO Swig" needed
16 // to be temporarily removed for swig to proceed correctly (in fact
17 // problems appears at loading of _gdcm.[so/dll]). So, simply uncomment
18 // the declaration once you provided the definition of the method...
27 #include <stddef.h> // For size_t
28 #include <stdio.h> // FIXME For FILE on GCC only
31 #include "gdcmException.h"
34 // The requirement for the hash table (or map) that
36 // 1/ First, next, last (iterators)
37 // 2/ should be sortable (i.e. sorted by TagKey). This
38 // condition shall be droped since the Win32/VC++
39 // implementation doesn't look a sorted one. Pffff....
40 // 3/ Make sure we can setup some default size value,
41 // which should be around 4500 entries which is the
42 // average dictionary size (said JPR)
44 // En fait, je disais que dans LE Directory Dicom (dans son etat 2001)
45 // il y a +/- 1600 entrees.
46 // Une valeur raisonable pour un majorant du nombre d'entrees
47 // dans une entete DICOM d'une image semble semble etre 300
48 // Si on 'decortique' les elements SQ (ce qui ne semble pas etre fait pour le moment)
49 // on risque en fait de depasser ... un nombre non previsible dans le cas d'une entree SQ
50 // contenant lui même un tres grand nombre d'entrees ?!?)
51 // Quant au nombre d'entrees dans un DICOMDIR, c'est encore pire : il n'est limité
52 // que par la taille d'un CD-ROM (les DVD-ROM ne sont pas encore pris en compte)
53 // On peut s'attendre a 30 entrees par fichier dicom présent sur le CD-ROM
54 // REMARQUE : il faudra se pencher sur le pb de la creation du DICOMDIR lorsqu'on voudra
55 // exporter des images lisibles par les consoles cliniques
56 // et pas seulement importables dans e-film.
60 #define guint16 uint16_t
61 #define guint32 uint32_t
65 typedef unsigned short guint16;
66 typedef unsigned int guint32;
70 #define GDCM_EXPORT __declspec( dllexport )
75 ////////////////////////////////////////////////////////////////////////////
76 // Tag based hash tables.
77 // We shall use as keys the strings (as the C++ type) obtained by
78 // concatenating the group value and the element value (both of type
79 // unsigned 16 bit integers in Dicom) expressed in hexadecimal.
80 // Example: consider the tag given as (group, element) = (0x0010, 0x0010).
81 // Then the corresponding TagKey shall be the string 0010|0010 (where
82 // the | (pipe symbol) acts as a separator). Refer to
83 // gdcmDictEntry::TranslateToKey for this conversion function.
85 typedef string TagKey;
86 typedef string TagName;
88 class GDCM_EXPORT gdcmDictEntry {
90 guint16 group; // e.g. 0x0010
91 guint16 element; // e.g. 0x0103
92 string vr; // Value Representation i.e. some clue about the nature
93 // of the data represented e.g. "FD" short for
94 // "Floating Point Double"
95 // CLEANME: find the official dicom name for this field !
96 string fourth; // Fourth field containing some semantics.
97 string name; // e.g. "Patient_Name"
98 TagKey key; // Redundant with (group, element) but we add it
99 // on efficiency purposes.
100 // DCMTK has many fields for handling a DictEntry (see below). What are the
101 // relevant ones for gdcmlib ?
102 // struct DBI_SimpleEntry {
103 // Uint16 upperGroup;
104 // Uint16 upperElement;
106 // const char* tagName;
109 // const char* standardVersion;
110 // DcmDictRangeRestriction groupRestriction;
111 // DcmDictRangeRestriction elementRestriction;
114 gdcmDictEntry(guint16 group,
116 string vr = "Unknown",
117 string fourth = "Unknown",
118 string name = "Unknown");
119 // fabrique une 'clé' par concaténation du numGroupe et du numElement
120 static TagKey TranslateToKey(guint16 group, guint16 element);
122 guint16 GetGroup(void) { return group; };
123 guint16 GetElement(void){return element;};
124 string GetVR(void) {return vr; };
126 void SetKey(string k){ key = k; }
127 bool IsVrUnknown(void);
128 string GetFourth(void) {return fourth;};
129 string GetName(void) {return name; };
130 string GetKey(void) {return key; };
133 ////////////////////////////////////////////////////////////////////////////
134 // A single DICOM dictionary i.e. a container for a collection of dictionary
135 // entries. There should be a single public dictionary (THE dictionary of
136 // the actual DICOM v3) but as many shadow dictionaries as imagers
137 // combined with all software versions...
139 typedef map<TagKey, gdcmDictEntry*> TagKeyHT;
140 typedef map<TagName, gdcmDictEntry*> TagNameHT;
142 class GDCM_EXPORT gdcmDict {
145 TagKeyHT KeyHt; // Both accesses with a TagKey or with a
146 TagNameHT NameHt; // TagName are required.
148 gdcmDict(const char* FileName); // Reads Dict from ascii file
149 int AddNewEntry (gdcmDictEntry* NewEntry);
150 int ReplaceEntry(gdcmDictEntry* NewEntry);
151 int RemoveEntry (TagKey key);
152 int RemoveEntry (guint16 group, guint16 element);
153 gdcmDictEntry * GetTagByKey(guint16 group, guint16 element);
154 gdcmDictEntry * GetTagByName(TagName name);
155 void Print(ostream&);
156 void PrintByKey(ostream&);
157 void PrintByName(ostream&);
158 TagKeyHT & GetEntries(void) { return KeyHt; }
162 ////////////////////////////////////////////////////////////////////////////
163 // Container for managing a set of loaded dictionaries. Sharing dictionaries
165 // * reloading an allready loaded dictionary,
166 // * having many in memory representations of the same dictionary.
168 typedef string DictKey;
169 typedef map<DictKey, gdcmDict*> DictSetHT;
171 class GDCM_EXPORT gdcmDictSet {
173 string DictPath; // Directory path to dictionaries
175 int AppendDict(gdcmDict* NewDict);
176 int LoadDictFromFile(string filename, DictKey);
177 void SetDictPath(void);
179 gdcmDictSet(void); // loads THE DICOM v3 dictionary
180 // TODO Swig int LoadDictFromFile(string filename);
181 // QUESTION: the following function might not be thread safe !? Maybe
182 // we need some mutex here, to avoid concurent creation of
183 // the same dictionary !?!?!
184 // TODO Swig int LoadDictFromName(string filename);
185 // TODO Swig int LoadAllDictFromDirectory(string DirectoryName);
186 // TODO Swig string* GetAllDictNames();
188 // Question : ne faudra-t-il pas mettre LE dictionnaire DICOM dans un Directory
189 // et les eventuels 'dictionnaires prives' dans un autre?
190 // (pour eviter a un utilisateur mal dégourdi de tout saccager ?)
192 int LoadDicomV3Dict(void);
193 void Print(ostream&);
194 gdcmDict* GetDict(DictKey DictName);
195 gdcmDict* GetDefaultPublicDict(void);
198 ///////////////////////////////////////////////////////////////////////////
199 // The dicom header of a Dicom file contains a set of such ELement VALUES
200 // (when successfuly parsed against a given Dicom dictionary)
201 class GDCM_EXPORT ElValue {
203 gdcmDictEntry *entry;
205 bool ImplicitVr; // Even when reading explicit vr files, some
206 // elements happen to be implicit. Flag them here
207 // since we can't use the entry->vr without breaking
208 // the underlying dictionary.
211 size_t Offset; // Offset from the begining of file for direct user access
213 ElValue(gdcmDictEntry*);
214 void SetDictEntry(gdcmDictEntry *NewEntry) { entry = NewEntry; };
215 bool IsVrUnknown(void) { return entry->IsVrUnknown(); };
216 void SetImplicitVr(void) { ImplicitVr = true; };
217 bool IsImplicitVr(void) { return ImplicitVr; };
219 guint16 GetGroup(void) { return entry->GetGroup(); };
220 guint16 GetElement(void) { return entry->GetElement();};
221 string GetKey(void) { return entry->GetKey(); };
222 string GetName(void) { return entry->GetName(); };
223 string GetVR(void) { return entry->GetVR(); };
224 void SetVR(string v) { entry->SetVR(v); };
225 void SetLength(guint32 l){ LgrElem = l; };
226 guint32 GetLength(void) { return LgrElem; };
228 // Question : SetLength est public
229 // (sinon, on ne pourrait pas l'appeler dans ElValSet)
230 // alors que *personne* ne devrait s'en servir !
231 // c'est *forcément* la lgr de la string 'value', non?
233 void SetValue(string val){ value = val; };
234 string GetValue(void) { return value;};
236 void SetOffset(size_t of){ Offset = of; };
237 size_t GetOffset(void) { return Offset;};
238 // Question : SetOffset est public ...
239 // Quel utilisateur serait ammené à modifier l'Offset ?
243 ////////////////////////////////////////////////////////////////////////////
244 // Container for a set of successfully parsed ElValues.
245 typedef map<TagKey, ElValue*> TagElValueHT;
246 typedef map<string, ElValue*> TagElValueNameHT;
248 class GDCM_EXPORT ElValSet {
249 TagElValueHT tagHt; // Both accesses with a TagKey or with a
250 TagElValueNameHT NameHt; // the DictEntry.Name are required.
253 void Print(ostream &);
254 void PrintByName(ostream &);
256 ElValue* GetElementByNumber(guint32 group, guint32 element);
257 ElValue* GetElementByName (string);
258 string GetElValueByNumber(guint32 group, guint32 element);
259 string GetElValueByName (string);
261 TagElValueHT & GetTagHt(void);
263 int SetElValueByNumber(string content, guint32 group, guint32 element);
264 int SetElValueByName (string content, string TagName);
266 int SetElValueLengthByNumber(guint32 l, guint32 group, guint32 element);
267 int SetElValueLengthByName (guint32 l, string TagName);
271 ////////////////////////////////////////////////////////////////////////////
272 // The purpous of an instance of gdcmHeader is to act as a container of
273 // all the elements and their corresponding values (and additionaly the
274 // corresponding DICOM dictionary entry) of the header of a DICOM file.
276 // The typical usage of instances of class gdcmHeader is to classify a set of
277 // dicom files according to header information e.g. to create a file hierarchy
278 // reflecting the Patient/Study/Serie informations, or extracting a given
279 // SerieId. Accesing the content (image[s] or volume[s]) is beyond the
280 // functionality of this class and belong to gdmcFile (see below).
282 // * the various entries of the explicit value representation (VR) shall
283 // be managed within a dictionary which is shared by all gdcmHeader instances
284 // * the gdcmHeader::Set*Tag* family members cannot be defined as protected
285 // (Swig limitations for as Has_a dependency between gdcmFile and gdcmHeader)
287 typedef string VRKey;
288 typedef string VRAtr;
289 typedef map<VRKey, VRAtr> VRHT; // Value Representation Hash Table
291 class GDCM_EXPORT gdcmHeader {
292 void SkipBytes(guint32);
294 static VRHT *dicom_vr;
295 // Dictionaries of data elements:
297 static gdcmDictSet* Dicts; // global dictionary container
298 gdcmDict* RefPubDict; // public dictionary
299 gdcmDict* RefShaDict; // shadow dictionary (optional)
300 // Parsed element values:
301 ElValSet PubElVals; // parsed with Public Dictionary
302 ElValSet ShaElVals; // parsed with Shadow Dictionary
303 string filename; // refering underlying file
307 // Ne faudrait-il pas une indication sur la presence ou non
308 // du 'groupe des pixels' dans l'entete?
309 // (voir pb du DICOMDIR)
311 // Swap code (little, big, bad-big, bad-little endian): this code is not fixed
312 // during parsing.FIXME sw should be an enum e.g.
320 // Only the elements whose size is below this bound will be loaded.
321 // By default, this upper bound is limited to 1024 (which looks reasonable
322 // when one considers the definition of the various VR contents).
323 guint32 MaxSizeLoadElementValue;
325 guint16 ReadInt16(void);
326 guint32 ReadInt32(void);
327 guint16 SwapShort(guint16);
328 guint32 SwapLong(guint32);
329 guint32 FindLengthOB(void);
330 void Initialise(void);
331 void CheckSwap(void);
332 void InitVRDict(void);
333 void SwitchSwapToBigEndian(void);
334 void AddAndDefaultElements(void);
335 void SetMaxSizeLoadElementValue(long);
337 gdcmDictEntry * GetDictEntryByKey(guint16, guint16);
338 gdcmDictEntry * GetDictEntryByName(string name);
340 // ElValue related utilities
341 ElValue * ReadNextElement(void);
342 ElValue * NewElValueByKey(guint16 group, guint16 element);
343 ElValue * NewElValueByName(string name);
344 void FindLength(ElValue *);
345 void FindVR(ElValue *);
346 void LoadElementValue(ElValue *);
347 void LoadElementValueSafe(ElValue *);
348 void SkipElementValue(ElValue *);
349 void FixFoundLength(ElValue*, guint32);
350 bool IsAnInteger(ElValue *);
352 bool IsImplicitVRLittleEndianTransferSyntax(void);
353 bool IsExplicitVRLittleEndianTransferSyntax(void);
354 bool IsDeflatedExplicitVRLittleEndianTransferSyntax(void);
355 bool IsExplicitVRBigEndianTransferSyntax(void);
356 bool IsJPEGBaseLineProcess1TransferSyntax(void);
357 bool IsJPEGExtendedProcess2_4TransferSyntax(void);
358 bool IsJPEGExtendedProcess3_5TransferSyntax(void);
359 bool IsJPEGSpectralSelectionProcess6_8TransferSyntax(void);
368 ACR_LIBIDO}; // CLEANME
371 int anonymize(ostream&); // FIXME : anonymize should be a friend ?
373 void LoadElements(void);
374 virtual void ParseHeader(bool exception_on_error = false)
375 throw(gdcmFormatError);
376 gdcmHeader(const char *filename, bool exception_on_error = false)
377 throw(gdcmFileError);
378 virtual ~gdcmHeader();
380 size_t GetPixelOffset(void);
381 void GetPixels(size_t, void *);
382 int GetSwapCode(void) { return sw; }
384 // TODO Swig int SetPubDict(string filename);
385 // When some proprietary shadow groups are disclosed, we can set up
386 // an additional specific dictionary to access extra information.
387 // TODO Swig int SetShaDict(string filename);
389 // Retrieve all potentially available tag [tag = (group, element)] names
390 // from the standard (or public) dictionary. Typical usage : enable the
391 // user of a GUI based interface to select his favorite fields for sorting
393 list<string> * GetPubTagNames(void);
394 map<string, list<string> > * GetPubTagNamesByCategory(void);
395 // Get the element values themselves:
397 string GetPubElValByName(string TagName);
398 string GetPubElValByNumber(guint16 group, guint16 element);
400 // Getting the element value representation (VR) might be needed by caller
401 // to convert the string typed content to caller's native type
402 // (think of C/C++ vs Python).
404 string GetPubElValRepByName(string TagName);
405 string GetPubElValRepByNumber(guint16 group, guint16 element);
407 TagElValueHT & GetPubElVal(void) { return PubElVals.GetTagHt(); };
408 void PrintPubElVal(ostream & os = cout);
409 void PrintPubDict(ostream &);
411 // Same thing with the shadow :
412 // TODO Swig string* GetShaTagNames();
413 string GetShaElValByName(string TagName);
414 string GetShaElValByNumber(guint16 group, guint16 element);
415 string GetShaElValRepByName(string TagName);
416 string GetShaElValRepByNumber(guint16 group, guint16 element);
418 // Wrappers of the above (public is privileged over shadow) to avoid
419 // bugging the caller with knowing if ElVal is from the public or shadow
421 string GetElValByName(string TagName);
422 string GetElValByNumber(guint16 group, guint16 element);
423 string GetElValRepByName(string TagName);
424 string GetElValRepByNumber(guint16 group, guint16 element);
426 int SetPubElValByName(string content, string TagName);
427 int SetPubElValByNumber(string content, guint16 group, guint16 element);
428 int SetShaElValByName(string content, string ShadowTagName);
429 int SetShaElValByNumber(string content, guint16 group, guint16 element);
431 ElValSet GetPubElVals() { return(PubElVals); }
435 // ---------------------------------------------------- gdcmFile
437 // un fichier EST_UNE entete, ou A_UNE entete ?
439 // On dit 'EST_UNE' ...
442 ////////////////////////////////////////////////////////////////////////////
443 // In addition to Dicom header exploration, this class is designed
444 // for accessing the image/volume content. One can also use it to
445 // write Dicom files.
446 ////// QUESTION: this looks still like an open question whether the
447 ////// relationship between a gdcmFile and gdcmHeader is of
448 ////// type IS_A or HAS_A !
450 class GDCM_EXPORT gdcmFile: public gdcmHeader
454 // Data pointe sur quoi?
455 // sur les Pixels lus?
456 // --> j'ajoute un champ public : Pixels
457 // (il faudra que l'utilisateur puisse modifier les pixels ?)
460 int Parsed; // weather allready parsed
461 string OrigFileName; // To avoid file overwrite
463 // je ne suis pas sur d'avoir compris *où* il serait légitime de ranger ca.
464 // on pourra tjs le deplacer, et mettre des accesseurs
468 // Constructor dedicated to writing a new DICOMV3 part10 compliant
469 // file (see SetFileName, SetDcmTag and Write)
470 // TODO Swig gdcmFile();
471 // Opens (in read only and when possible) an existing file and checks
472 // for DICOM compliance. Returns NULL on failure.
473 // Note: the in-memory representation of all available tags found in
474 // the DICOM header is post-poned to first header information access.
475 // This avoid a double parsing of public part of the header when
476 // one sets an a posteriori shadow dictionary (efficiency can be
477 // seen as a side effect).
479 gdcmFile(string & filename);
481 // For promotion (performs a deepcopy of pointed header object)
482 // TODO Swig gdcmFile(gdcmHeader* header);
483 // TODO Swig ~gdcmFile();
485 // On writing purposes. When instance was created through
486 // gdcmFile(string filename) then the filename argument MUST be different
487 // from the constructor's one (no overwriting allowed).
488 // TODO Swig int SetFileName(string filename);
490 // Allocates necessary memory, copies the data (image[s]/volume[s]) to
491 // newly allocated zone and return a pointer to it:
493 void * GetImageData();
495 // Returns size (in bytes) of required memory to contain data
496 // represented in this file.
498 size_t GetImageDataSize();
500 // Copies (at most MaxSize bytes) of data to caller's memory space.
501 // Returns an error code on failure (if MaxSize is not big enough)
503 int GetImageDataIntoVector(void* destination, size_t MaxSize );
507 // GetImageData et GetImageDataIntoVector
508 // Get et Put pour 2 fonctions qui font presque la meme chose :-(
511 // Allocates ExpectedSize bytes of memory at this->Data and copies the
512 // pointed data to it.
515 // Pourquoi dupliquer les pixels, alors qu'on les a deja en mémoire,
516 // et que Data (dans le gdcmHeader) est un pointeur ?
518 // TODO Swig int SetImageData(void * Data, size_t ExpectedSize);
521 // A NE PAS OUBLIER : que fait-on en cas de Transfert Syntax (dans l'entete)
522 // incohérente avec l'ordre des octets en mémoire
523 // TODO Swig int Write();
525 // Ecrit sur disque les pixels d'UNE image
526 // Aucun test n'est fait sur l'"Endiannerie" du processeur.
527 // Ca sera à l'utilisateur d'appeler son Reader correctement
529 int WriteRawData (string nomFichier);
530 int WriteDcm (string nomFichier);
534 // ---------------------------------------------------- gdcmSerie
536 // une serie EST_UN fichier ????
540 //class gdcmSerie : gdcmFile;
543 // ---------------------------------------------------- gdcmMultiFrame
545 // un fichierMultiFrame EST_UN fichier
549 //class gdcmMultiFrame : gdcmFile;
552 #endif // #ifndef GDCM_H