10 #include <netinet/in.h>
16 #define HEADER_LENGHT_TO_READ 256 // on ne lit plus que le debut
19 struct FileReadError {
20 FileReadError(FILE* fp, const char* Mesg) {
22 dbg.Verbose(1, "EOF encountered :", Mesg);
24 dbg.Verbose(1, "Error on reading :", Mesg);
29 //FIXME: this looks dirty to me...
30 #define str2num(str, typeNum) *((typeNum *)(str))
32 VRHT * gdcmHeader::dicom_vr = (VRHT*)0;
33 gdcmDictSet* gdcmHeader::Dicts = new gdcmDictSet();
35 void gdcmHeader::Initialise(void) {
36 if (!gdcmHeader::dicom_vr)
38 RefPubDict = gdcmHeader::Dicts->GetDefaultPublicDict();
39 RefShaDict = (gdcmDict*)0;
42 gdcmHeader::gdcmHeader (const char* InFilename) {
43 filename = InFilename;
45 fp=fopen(InFilename,"rw");
46 dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
50 gdcmHeader::~gdcmHeader (void) {
55 void gdcmHeader::InitVRDict (void) {
57 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
61 (*vr)["AE"] = "Application Entity"; // 16 car max
62 (*vr)["AS"] = "Age String"; // 4 car fixe
63 (*vr)["AT"] = "Attribute Tag"; // 2 unsigned short int
64 (*vr)["CS"] = "Code String"; // 16 car max
65 (*vr)["DA"] = "Date"; // 8 car fixe
66 (*vr)["DS"] = "Decimal String"; // Decimal codé Binaire 16 max
67 (*vr)["DT"] = "Date Time"; // 26 car max
68 (*vr)["FL"] = "Floating Point Single"; // 4 octets IEEE 754:1985
69 (*vr)["FD"] = "Floating Point Double"; // 8 octets IEEE 754:1985
70 (*vr)["IS"] = "Integer String"; // en format externe 12 max
71 (*vr)["LO"] = "Long String"; // 64 octets max
72 (*vr)["LT"] = "Long Text"; // 10240 max
73 (*vr)["OB"] = "Other Byte String";
74 (*vr)["OW"] = "Other Word String";
75 (*vr)["PN"] = "Person Name";
76 (*vr)["SH"] = "Short String"; // 16 car max
77 (*vr)["SL"] = "Signed Long";
78 (*vr)["SQ"] = "Sequence of Items"; // Not Applicable
79 (*vr)["SS"] = "Signed Short"; // 2 octets
80 (*vr)["ST"] = "Short Text"; // 1024 car max
81 (*vr)["TM"] = "Time"; // 16 car max
82 (*vr)["UI"] = "Unique Identifier"; // 64 car max
83 (*vr)["UN"] = "Unknown";
84 (*vr)["UT"] = "Unlimited Text"; // 2 puissance 32 -1 car max
85 (*vr)["UL"] = "Unsigned Long "; // 4 octets fixe
86 (*vr)["US"] = "Unsigned Short "; // 2 octets fixe
92 * \brief La seule maniere sure que l'on aie pour determiner
93 * si on est en LITTLE_ENDIAN, BIG-ENDIAN,
94 * BAD-LITTLE-ENDIAN, BAD-BIG-ENDIAN
95 * est de trouver l'element qui donne la longueur d'un 'GROUP'
96 * (on sait que la longueur de cet element vaut 0x00000004)
97 * et de regarder comment cette longueur est codee en memoire
99 * Le probleme vient de ce que parfois, il n'y en a pas ...
101 * On fait alors le pari qu'on a a faire a du LITTLE_ENDIAN propre.
102 * (Ce qui est la norme -pas respectee- depuis ACR-NEMA)
103 * Si ce n'est pas le cas, on ne peut rien faire.
105 * (il faudrait avoir des fonctions auxquelles
106 * on passe le code Swap en parametre, pour faire des essais 'manuels')
108 void gdcmHeader::CheckSwap()
111 guint32 x=4; // x : pour ntohs
112 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
116 char deb[HEADER_LENGHT_TO_READ];
118 // First, compare HostByteOrder and NetworkByteOrder in order to
119 // determine if we shall need to swap bytes (i.e. the Endian type).
125 // The easiest case is the one of a DICOM header, since it possesses a
126 // file preamble where it suffice to look for the sting "DICM".
127 lgrLue = fread(deb, 1, HEADER_LENGHT_TO_READ, fp);
130 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
131 filetype = TrueDicom;
132 dbg.Verbose(0, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
135 dbg.Verbose(0, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
138 if(filetype == TrueDicom) {
139 // Next, determine the value representation (VR). Let's skip to the
140 // first element (0002, 0000) and check there if we find "UL", in
141 // which case we (almost) know it is explicit VR.
142 // WARNING: if it happens to be implicit VR then what we will read
143 // is the length of the group. If this ascii representation of this
144 // length happens to be "UL" then we shall believe it is explicit VR.
145 // FIXME: in order to fix the above warning, we could read the next
146 // element value (or a couple of elements values) in order to make
147 // sure we are not commiting a big mistake.
149 // * the 128 bytes of File Preamble (often padded with zeroes),
150 // * the 4 bytes of "DICM" string,
151 // * the 4 bytes of the first tag (0002, 0000),
152 // i.e. a total of 136 bytes.
154 if(memcmp(entCur, "UL", (size_t)2) == 0) {
155 filetype = ExplicitVR;
156 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
157 "explicit Value Representation");
159 filetype = ImplicitVR;
160 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
161 "not an explicit Value Representation");
166 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
167 "HostByteOrder != NetworkByteOrder");
170 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
171 "HostByteOrder = NetworkByteOrder");
174 // Position the file position indicator at first tag (i.e.
175 // after the file preamble and the "DICM" string).
177 fseek (fp, 132L, SEEK_SET);
179 } // End of TrueDicom
181 // Alas, this is not a DicomV3 file and whatever happens there is no file
182 // preamble. We can reset the file position indicator to where the data
183 // is (i.e. the beginning of the file).
186 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
187 // By clean we mean that the length of the first tag is written down.
188 // If this is the case and since the length of the first group HAS to be
189 // four (bytes), then determining the proper swap code is straightforward.
192 s = str2num(entCur, int);
212 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
213 "ACE/NEMA unfound swap info (time to raise bets)");
216 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
217 // It is time for despaired wild guesses. So, let's assume this file
218 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group it
219 // not present. Then the only info we have is the net2host one.
220 //FIXME Si c'est du RAW, ca degagera + tard
230 * \ingroup gdcmHeader
231 * \brief recupere la longueur d'un champ DICOM.
233 * 1/ le fichier doit deja avoir ete ouvert,
234 * 2/ CheckSwap() doit avoir ete appele
235 * 3/ la partie 'group' ainsi que la partie 'elem'
236 * de l'acr_element doivent avoir ete lues.
238 * ACR-NEMA : we allways get
239 * GroupNumber (2 Octets)
240 * ElementNumber (2 Octets)
241 * ElementSize (4 Octets)
242 * DICOM en implicit Value Representation :
243 * GroupNumber (2 Octets)
244 * ElementNumber (2 Octets)
245 * ElementSize (4 Octets)
247 * DICOM en explicit Value Representation :
248 * GroupNumber (2 Octets)
249 * ElementNumber (2 Octets)
250 * ValueRepresentation (2 Octets)
251 * ElementSize (2 Octets)
253 * ATTENTION : dans le cas ou ValueRepresentation = OB, OW, SQ, UN
254 * GroupNumber (2 Octets)
255 * ElementNumber (2 Octets)
256 * ValueRepresentation (2 Octets)
257 * zone reservee (2 Octets)
258 * ElementSize (4 Octets)
260 * @param sw code swap
261 * @param skippedLength pointeur sur nombre d'octets que l'on a saute qd
262 * la lecture est finie
263 * @param longueurLue pointeur sur longueur (en nombre d'octets)
265 * @return longueur retenue pour le champ
268 void gdcmHeader::FindVR( ElValue *ElVal) {
271 long PositionOnEntry = ftell(fp);
273 if (filetype != ExplicitVR)
276 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
279 // Warning: we believe this is explicit VR (Value Representation) because
280 // we used a heuristic that found "UL" in the first tag. Alas this
281 // doesn't guarantee that all the tags will be in explicit VR. In some
282 // cases (see e-film filtered files) one finds implicit VR tags mixed
283 // within an explicit VR file. Hence we make sure the present tag
284 // is in explicit VR and try to fix things if it happens not to be
287 // FIXME There should be only one occurence returned. Avoid the
288 // first extraction by calling proper method.
289 VRAtr FoundVR = dicom_vr->find(string(VR))->first;
290 if ( ! FoundVR.empty()) {
291 ElVal->SetVR(FoundVR);
295 // We thought this was explicit VR, but we end up with an
296 // implicit VR tag. Let's backtrack.
297 ElVal->SetVR("Implicit");
298 fseek(fp, PositionOnEntry, SEEK_SET);
301 void gdcmHeader::FindLength( ElValue * ElVal) {
305 string vr = ElVal->GetVR();
307 if ( (filetype == ExplicitVR) && (vr != "Implicit") ) {
308 if ( ( vr == "OB" ) || ( vr == "OW" )
309 || ( vr == "SQ" ) || ( vr == "UN" ) ) {
311 // The following two bytes are reserved, so we skip them,
312 // and we proceed on reading the length on 4 bytes.
313 fseek(fp, 2L,SEEK_CUR);
314 length32 = ReadInt32();
317 // Length is encoded on 2 bytes.
318 length16 = ReadInt16();
320 if ( length16 == 0xffff) {
327 // Either implicit VR or an explicit VR that (at least for this
328 // element) lied a little bit. Length is on 4 bytes.
329 length32 = ReadInt32();
332 // Traitement des curiosites sur la longueur
333 if ( length32 == 0xffffffff)
336 ElVal->SetLength(length32);
341 * \ingroup gdcmHeader
342 * \brief remet les octets dans un ordre compatible avec celui du processeur
344 * @return longueur retenue pour le champ
346 guint32 gdcmHeader::SwapLong(guint32 a) {
347 // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
352 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
353 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
357 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
361 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
364 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
371 * \ingroup gdcmHeader
372 * \brief remet les octets dans un ordre compatible avec celui du processeur
374 * @return longueur retenue pour le champ
376 guint16 gdcmHeader::SwapShort(guint16 a) {
377 if ( (sw==4321) || (sw==2143) )
378 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
382 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
383 //FIXME don't dump the returned value
384 (void)fseek(fp, (long)ElVal->GetLength(), SEEK_CUR);
387 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
389 guint16 group = ElVal->GetGroup();
390 guint16 elem = ElVal->GetElement();
391 string vr = ElVal->GetVR();
392 guint32 length = ElVal->GetLength();
393 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
395 // Sequences not treated yet !
397 SkipElementValue(ElVal);
401 // A sequence "contains" a set of tags (called items). It looks like
402 // the last tag of a sequence (the one that terminates the sequence)
403 // has a group of 0xfffe (with a dummy length).
404 if( group == 0xfffe) {
405 SkipElementValue(ElVal);
410 if ( IsAnInteger(group, elem, vr, length) ) {
413 NewInt = ReadInt16();
414 } else if( length == 4 ) {
415 NewInt = ReadInt32();
417 dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
419 //FIXME: make the following an util fonction
422 ElVal->SetValue(s.str());
426 // FIXME The exact size should be length if we move to strings or whatever
427 char* NewValue = (char*)g_malloc(length+1);
429 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
434 // FIXME les elements trop long (seuil a fixer a la main) ne devraient
435 // pas etre charge's !!!! Voir TODO.
436 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
437 if ( item_read != 1 ) {
439 Error::FileReadError(fp, "gdcmHeader::LoadElementValue");
440 ElVal->SetValue("gdcm::UnRead");
443 ElVal->SetValue(NewValue);
447 guint16 gdcmHeader::ReadInt16(void) {
450 item_read = fread (&g, (size_t)2,(size_t)1, fp);
451 if ( item_read != 1 )
452 throw Error::FileReadError(fp, "gdcmHeader::ReadInt16");
457 guint32 gdcmHeader::ReadInt32(void) {
460 item_read = fread (&g, (size_t)4,(size_t)1, fp);
461 if ( item_read != 1 )
462 throw Error::FileReadError(fp, "gdcmHeader::ReadInt32");
468 * \ingroup gdcmHeader
469 * \brief Read the next tag without loading it's value
470 * @return On succes the newly created ElValue, NULL on failure.
473 ElValue * gdcmHeader::ReadNextElement(void) {
482 catch ( Error::FileReadError ) {
483 // We reached the EOF (or an error occured) and header parsing
484 // has to be considered as finished.
488 // Find out if the tag we encountered is in the dictionaries:
489 gdcmDictEntry * NewTag = IsInDicts(g, n);
491 NewTag = new gdcmDictEntry(g, n, "Unknown", "Unknown", "Unkown");
493 NewElVal = new ElValue(NewTag);
495 dbg.Verbose(1, "ReadNextElement: failed to allocate ElValue");
500 FindLength(NewElVal);
501 NewElVal->SetOffset(ftell(fp));
505 bool gdcmHeader::IsAnInteger(guint16 group, guint16 element,
506 string vr, guint32 length ) {
507 // When we have some semantics on the element we just read, and we
508 // a priori now we are dealing with an integer, then we can swap it's
509 // element value properly.
510 if ( element == 0 ) { // This is the group length of the group
512 dbg.Error("gdcmHeader::ShouldBeSwaped", "should be four");
516 if ( group % 2 != 0 )
517 // We only have some semantics on documented elements, which are
521 if ( (length != 4) && ( length != 2) )
522 // Swapping only make sense on integers which are 2 or 4 bytes long.
525 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
528 if ( (group == 0x0028) && (element == 0x0005) )
529 // This tag is retained from ACR/NEMA
530 // CHECKME Why should "Image Dimensions" be a single integer ?
533 if ( (group == 0x0028) && (element == 0x0200) )
534 // This tag is retained from ACR/NEMA
541 * \ingroup gdcmHeader
542 * \brief Recover the offset (from the beginning of the file) of the pixels.
544 size_t gdcmHeader::GetPixelOffset(void) {
545 // If this file complies with the norm we should encounter the
546 // "Image Location" tag (0x0028, 0x0200). This tag contains the
547 // the group that contains the pixel data (hence the "Pixel Data"
548 // is found by indirection through the "Image Location").
549 // Inside the group pointed by "Image Location" the searched element
550 // is conventionally the element 0x0010 (when the norm is respected).
551 // When the "Image Location" is absent we default to group 0x7fe0.
554 string ImageLocation = GetPubElValByName("Image Location");
555 if ( ImageLocation == "UNFOUND" ) {
558 grPixel = (guint16) atoi( ImageLocation.c_str() );
560 if (grPixel != 0x7fe0)
561 // FIXME is this still necessary ?
562 // Now, this looks like an old dirty fix for Philips imager
566 ElValue* PixelElement = PubElVals.GetElement(grPixel, numPixel);
568 return PixelElement->GetOffset();
573 gdcmDictEntry * gdcmHeader::IsInDicts(guint32 group, guint32 element) {
574 gdcmDictEntry * found = (gdcmDictEntry*)0;
575 if (!RefPubDict && !RefShaDict) {
576 //FIXME build a default dictionary !
577 printf("FIXME in gdcmHeader::IsInDicts\n");
580 found = RefPubDict->GetTag(group, element);
585 found = RefShaDict->GetTag(group, element);
592 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
593 return PubElVals.GetElValue(group, element);
596 string gdcmHeader::GetPubElValByName(string TagName) {
597 return PubElVals.GetElValue(TagName);
601 * \ingroup gdcmHeader
602 * \brief Parses the header of the file but does NOT load element values.
604 void gdcmHeader::ParseHeader(void) {
605 ElValue * newElValue = (ElValue *)0;
609 while ( (newElValue = ReadNextElement()) ) {
610 SkipElementValue(newElValue);
611 PubElVals.Add(newElValue);
616 * \ingroup gdcmHeader
617 * \brief Loads the element values of all the elements present in the
618 * public tag based hash table.
620 void gdcmHeader::LoadElements(void) {
622 TagElValueHT ht = PubElVals.GetTagHt();
623 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag)
624 LoadElementValue(tag->second);
627 void gdcmHeader::PrintPubElVal(ostream & os) {
631 void gdcmHeader::PrintPubDict(ostream & os) {
632 RefPubDict->Print(os);