7 #include <netinet/in.h>
9 #include <cctype> // for isalpha
14 #define HEADER_LENGHT_TO_READ 256 // on ne lit plus que le debut
17 struct FileReadError {
18 FileReadError(FILE* fp, const char* Mesg) {
20 dbg.Verbose(1, "EOF encountered :", Mesg);
22 dbg.Verbose(1, "Error on reading :", Mesg);
27 //FIXME: this looks dirty to me...
28 #define str2num(str, typeNum) *((typeNum *)(str))
30 VRHT * gdcmHeader::dicom_vr = (VRHT*)0;
31 gdcmDictSet* gdcmHeader::Dicts = new gdcmDictSet();
33 void gdcmHeader::Initialise(void) {
34 if (!gdcmHeader::dicom_vr)
36 RefPubDict = gdcmHeader::Dicts->GetDefaultPublicDict();
37 RefShaDict = (gdcmDict*)0;
40 gdcmHeader::gdcmHeader (const char* InFilename) {
41 filename = InFilename;
43 fp=fopen(InFilename,"rw");
44 dbg.Error(!fp, "gdcmHeader::gdcmHeader cannot open file", InFilename);
48 gdcmHeader::~gdcmHeader (void) {
53 void gdcmHeader::InitVRDict (void) {
55 dbg.Verbose(0, "gdcmHeader::InitVRDict:", "VR dictionary allready set");
59 (*vr)["AE"] = "Application Entity"; // 16 car max
60 (*vr)["AS"] = "Age String"; // 4 car fixe
61 (*vr)["AT"] = "Attribute Tag"; // 2 unsigned short int
62 (*vr)["CS"] = "Code String"; // 16 car max
63 (*vr)["DA"] = "Date"; // 8 car fixe
64 (*vr)["DS"] = "Decimal String"; // Decimal codé Binaire 16 max
65 (*vr)["DT"] = "Date Time"; // 26 car max
66 (*vr)["FL"] = "Floating Point Single"; // 4 octets IEEE 754:1985
67 (*vr)["FD"] = "Floating Point Double"; // 8 octets IEEE 754:1985
68 (*vr)["IS"] = "Integer String"; // en format externe 12 max
69 (*vr)["LO"] = "Long String"; // 64 octets max
70 (*vr)["LT"] = "Long Text"; // 10240 max
71 (*vr)["OB"] = "Other Byte String";
72 (*vr)["OW"] = "Other Word String";
73 (*vr)["PN"] = "Person Name";
74 (*vr)["SH"] = "Short String"; // 16 car max
75 (*vr)["SL"] = "Signed Long";
76 (*vr)["SQ"] = "Sequence of Items"; // Not Applicable
77 (*vr)["SS"] = "Signed Short"; // 2 octets
78 (*vr)["ST"] = "Short Text"; // 1024 car max
79 (*vr)["TM"] = "Time"; // 16 car max
80 (*vr)["UI"] = "Unique Identifier"; // 64 car max
81 (*vr)["UN"] = "Unknown";
82 (*vr)["UT"] = "Unlimited Text"; // 2 puissance 32 -1 car max
83 (*vr)["UL"] = "Unsigned Long "; // 4 octets fixe
84 (*vr)["US"] = "Unsigned Short "; // 2 octets fixe
90 * \brief La seule maniere sure que l'on aie pour determiner
91 * si on est en LITTLE_ENDIAN, BIG-ENDIAN,
92 * BAD-LITTLE-ENDIAN, BAD-BIG-ENDIAN
93 * est de trouver l'element qui donne la longueur d'un 'GROUP'
94 * (on sait que la longueur de cet element vaut 0x00000004)
95 * et de regarder comment cette longueur est codee en memoire
97 * Le probleme vient de ce que parfois, il n'y en a pas ...
99 * On fait alors le pari qu'on a a faire a du LITTLE_ENDIAN propre.
100 * (Ce qui est la norme -pas respectee- depuis ACR-NEMA)
101 * Si ce n'est pas le cas, on ne peut rien faire.
103 * (il faudrait avoir des fonctions auxquelles
104 * on passe le code Swap en parametre, pour faire des essais 'manuels')
106 void gdcmHeader::CheckSwap()
109 guint32 x=4; // x : pour ntohs
110 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
114 char deb[HEADER_LENGHT_TO_READ];
116 // First, compare HostByteOrder and NetworkByteOrder in order to
117 // determine if we shall need to swap bytes (i.e. the Endian type).
123 // The easiest case is the one of a DICOM header, since it possesses a
124 // file preamble where it suffice to look for the sting "DICM".
125 lgrLue = fread(deb, 1, HEADER_LENGHT_TO_READ, fp);
128 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
129 filetype = TrueDicom;
130 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
133 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
136 if(filetype == TrueDicom) {
137 // Next, determine the value representation (VR). Let's skip to the
138 // first element (0002, 0000) and check there if we find "UL", in
139 // which case we (almost) know it is explicit VR.
140 // WARNING: if it happens to be implicit VR then what we will read
141 // is the length of the group. If this ascii representation of this
142 // length happens to be "UL" then we shall believe it is explicit VR.
143 // FIXME: in order to fix the above warning, we could read the next
144 // element value (or a couple of elements values) in order to make
145 // sure we are not commiting a big mistake.
147 // * the 128 bytes of File Preamble (often padded with zeroes),
148 // * the 4 bytes of "DICM" string,
149 // * the 4 bytes of the first tag (0002, 0000),
150 // i.e. a total of 136 bytes.
152 if(memcmp(entCur, "UL", (size_t)2) == 0) {
153 filetype = ExplicitVR;
154 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
155 "explicit Value Representation");
157 filetype = ImplicitVR;
158 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
159 "not an explicit Value Representation");
164 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
165 "HostByteOrder != NetworkByteOrder");
168 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
169 "HostByteOrder = NetworkByteOrder");
172 // Position the file position indicator at first tag (i.e.
173 // after the file preamble and the "DICM" string).
175 fseek (fp, 132L, SEEK_SET);
177 } // End of TrueDicom
179 // Alas, this is not a DicomV3 file and whatever happens there is no file
180 // preamble. We can reset the file position indicator to where the data
181 // is (i.e. the beginning of the file).
184 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
185 // By clean we mean that the length of the first tag is written down.
186 // If this is the case and since the length of the first group HAS to be
187 // four (bytes), then determining the proper swap code is straightforward.
190 s = str2num(entCur, int);
210 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
211 "ACE/NEMA unfound swap info (time to raise bets)");
214 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
215 // It is time for despaired wild guesses. So, let's assume this file
216 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group it
217 // not present. Then the only info we have is the net2host one.
218 //FIXME Si c'est du RAW, ca degagera + tard
228 * \ingroup gdcmHeader
229 * \brief recupere la longueur d'un champ DICOM.
231 * 1/ le fichier doit deja avoir ete ouvert,
232 * 2/ CheckSwap() doit avoir ete appele
233 * 3/ la partie 'group' ainsi que la partie 'elem'
234 * de l'acr_element doivent avoir ete lues.
236 * ACR-NEMA : we allways get
237 * GroupNumber (2 Octets)
238 * ElementNumber (2 Octets)
239 * ElementSize (4 Octets)
240 * DICOM en implicit Value Representation :
241 * GroupNumber (2 Octets)
242 * ElementNumber (2 Octets)
243 * ElementSize (4 Octets)
245 * DICOM en explicit Value Representation :
246 * GroupNumber (2 Octets)
247 * ElementNumber (2 Octets)
248 * ValueRepresentation (2 Octets)
249 * ElementSize (2 Octets)
251 * ATTENTION : dans le cas ou ValueRepresentation = OB, OW, SQ, UN
252 * GroupNumber (2 Octets)
253 * ElementNumber (2 Octets)
254 * ValueRepresentation (2 Octets)
255 * zone reservee (2 Octets)
256 * ElementSize (4 Octets)
258 * @param sw code swap
259 * @param skippedLength pointeur sur nombre d'octets que l'on a saute qd
260 * la lecture est finie
261 * @param longueurLue pointeur sur longueur (en nombre d'octets)
263 * @return longueur retenue pour le champ
266 void gdcmHeader::FindVR( ElValue *ElVal) {
270 long PositionOnEntry = ftell(fp);
271 // Warning: we believe this is explicit VR (Value Representation) because
272 // we used a heuristic that found "UL" in the first tag. Alas this
273 // doesn't guarantee that all the tags will be in explicit VR. In some
274 // cases (see e-film filtered files) one finds implicit VR tags mixed
275 // within an explicit VR file. Hence we make sure the present tag
276 // is in explicit VR and try to fix things if it happens not to be
278 bool RealExplicit = true;
280 if (filetype != ExplicitVR)
283 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
287 // Assume we are reading a falsely explicit VR file i.e. we reached
288 // a tag where we expect reading a VR but are in fact we read the
289 // first to bytes of the length. Then we will interogate (through find)
290 // the dicom_vr dictionary with oddities like "\004\0" which crashes
291 // both GCC and VC++ implentations of the STL map. Hence when the
292 // expected VR read happens to be non-ascii characters we consider
293 // we hit falsely explicit VR tag.
295 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
296 RealExplicit = false;
298 // CLEANME searching the dicom_vr at each occurence is expensive.
299 // PostPone this test in an optional integrity check at the end
300 // of parsing or only in debug mode.
301 if ( RealExplicit && !dicom_vr->count(vr) )
302 RealExplicit = false;
304 if ( RealExplicit ) {
305 if ( ElVal->IsVrUnknown() )
310 // We thought this was explicit VR, but we end up with an
311 // implicit VR tag. Let's backtrack.
312 dbg.Verbose(1, "gdcmHeader::FindVR:", "Falsely explicit vr file");
313 fseek(fp, PositionOnEntry, SEEK_SET);
314 // When this element is known in the dictionary we shall use, e.g. for
315 // the semantics (see the usage of IsAnInteger), the vr proposed by the
316 // dictionary entry. Still we have to flag the element as implicit since
317 // we know now our assumption on expliciteness is not furfilled.
319 if ( ElVal->IsVrUnknown() )
320 ElVal->SetVR("Implicit");
321 ElVal->SetImplicitVr();
324 void gdcmHeader::FindLength( ElValue * ElVal) {
327 string vr = ElVal->GetVR();
329 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
330 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
332 // The following two bytes are reserved, so we skip them,
333 // and we proceed on reading the length on 4 bytes.
334 fseek(fp, 2L,SEEK_CUR);
335 length32 = ReadInt32();
338 // Length is encoded on 2 bytes.
339 length16 = ReadInt16();
341 if ( length16 == 0xffff) {
348 // Either implicit VR or an explicit VR that (at least for this
349 // element) lied a little bit. Length is on 4 bytes.
350 length32 = ReadInt32();
353 // Traitement des curiosites sur la longueur
354 if ( length32 == 0xffffffff)
357 ElVal->SetLength(length32);
362 * \ingroup gdcmHeader
363 * \brief remet les octets dans un ordre compatible avec celui du processeur
365 * @return longueur retenue pour le champ
367 guint32 gdcmHeader::SwapLong(guint32 a) {
368 // FIXME: il pourrait y avoir un pb pour les entiers negatifs ...
373 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
374 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
378 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
382 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
385 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
392 * \ingroup gdcmHeader
393 * \brief Swaps the bytes so they agree with the processor order
395 * @return longueur retenue pour le champ
397 guint16 gdcmHeader::SwapShort(guint16 a) {
398 //FIXME how could sw be equal to 2143 since we never set it this way ?
399 if ( (sw==4321) || (sw==2143) )
400 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
404 void gdcmHeader::SkipElementValue(ElValue * ElVal) {
405 //FIXME don't dump the returned value
406 (void)fseek(fp, (long)ElVal->GetLength(), SEEK_CUR);
410 * \ingroup gdcmHeader
411 * \brief Loads the element if it's size is not to big.
412 * @param ElVal Element whose value shall be loaded.
413 * @param MaxSize Size treshold above which the element value is not
414 * loaded in memory. The element value is allways loaded
415 * when MaxSize is equal to UINT32_MAX.
418 void gdcmHeader::LoadElementValue(ElValue * ElVal) {
420 guint16 group = ElVal->GetGroup();
421 guint16 elem = ElVal->GetElement();
422 string vr = ElVal->GetVR();
423 guint32 length = ElVal->GetLength();
425 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
427 // Sequences not treated yet !
429 SkipElementValue(ElVal);
433 // A sequence "contains" a set of tags (called items). It looks like
434 // the last tag of a sequence (the one that terminates the sequence)
435 // has a group of 0xfffe (with a dummy length).
436 if( group == 0xfffe) {
437 SkipElementValue(ElVal);
442 if ( IsAnInteger(group, elem, vr, length) ) {
445 NewInt = ReadInt16();
446 } else if( length == 4 ) {
447 NewInt = ReadInt32();
449 dbg.Error(true, "LoadElementValue: Inconsistency when reading Int.");
451 //FIXME: make the following an util fonction
454 ElVal->SetValue(s.str());
458 // FIXME The exact size should be length if we move to strings or whatever
459 char* NewValue = (char*)g_malloc(length+1);
461 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
466 // FIXME les elements trop long (seuil a fixer a la main) ne devraient
467 // pas etre charge's !!!! Voir TODO.
468 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
469 if ( item_read != 1 ) {
471 Error::FileReadError(fp, "gdcmHeader::LoadElementValue");
472 ElVal->SetValue("gdcm::UnRead");
475 ElVal->SetValue(NewValue);
479 guint16 gdcmHeader::ReadInt16(void) {
482 item_read = fread (&g, (size_t)2,(size_t)1, fp);
483 if ( item_read != 1 )
484 throw Error::FileReadError(fp, "gdcmHeader::ReadInt16");
489 guint32 gdcmHeader::ReadInt32(void) {
492 item_read = fread (&g, (size_t)4,(size_t)1, fp);
493 if ( item_read != 1 )
494 throw Error::FileReadError(fp, "gdcmHeader::ReadInt32");
500 * \ingroup gdcmHeader
501 * \brief Read the next tag without loading it's value
502 * @return On succes the newly created ElValue, NULL on failure.
505 ElValue * gdcmHeader::ReadNextElement(void) {
514 catch ( Error::FileReadError ) {
515 // We reached the EOF (or an error occured) and header parsing
516 // has to be considered as finished.
520 // Find out if the tag we encountered is in the dictionaries:
521 gdcmDictEntry * NewTag = IsInDicts(g, n);
523 NewTag = new gdcmDictEntry(g, n);
525 NewElVal = new ElValue(NewTag);
527 dbg.Verbose(1, "ReadNextElement: failed to allocate ElValue");
532 FindLength(NewElVal);
533 NewElVal->SetOffset(ftell(fp));
537 bool gdcmHeader::IsAnInteger(guint16 group, guint16 element,
538 string vr, guint32 length ) {
539 // When we have some semantics on the element we just read, and if we
540 // a priori know we are dealing with an integer, then we shall be
541 // able to swap it's element value properly.
542 if ( element == 0 ) { // This is the group length of the group
544 dbg.Error("gdcmHeader::ShouldBeSwaped", "should be four");
548 if ( group % 2 != 0 )
549 // We only have some semantics on documented elements, which are
553 if ( (length != 4) && ( length != 2) )
554 // Swapping only make sense on integers which are 2 or 4 bytes long.
557 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
560 if ( (group == 0x0028) && (element == 0x0005) )
561 // This tag is retained from ACR/NEMA
562 // CHECKME Why should "Image Dimensions" be a single integer ?
565 if ( (group == 0x0028) && (element == 0x0200) )
566 // This tag is retained from ACR/NEMA
573 * \ingroup gdcmHeader
574 * \brief Recover the offset (from the beginning of the file) of the pixels.
576 size_t gdcmHeader::GetPixelOffset(void) {
577 // If this file complies with the norm we should encounter the
578 // "Image Location" tag (0x0028, 0x0200). This tag contains the
579 // the group that contains the pixel data (hence the "Pixel Data"
580 // is found by indirection through the "Image Location").
581 // Inside the group pointed by "Image Location" the searched element
582 // is conventionally the element 0x0010 (when the norm is respected).
583 // When the "Image Location" is absent we default to group 0x7fe0.
586 string ImageLocation = GetPubElValByName("Image Location");
587 if ( ImageLocation == "UNFOUND" ) {
590 grPixel = (guint16) atoi( ImageLocation.c_str() );
592 if (grPixel != 0x7fe0)
593 // FIXME is this still necessary ?
594 // Now, this looks like an old dirty fix for Philips imager
598 ElValue* PixelElement = PubElVals.GetElement(grPixel, numPixel);
600 return PixelElement->GetOffset();
605 gdcmDictEntry * gdcmHeader::IsInDicts(guint32 group, guint32 element) {
606 gdcmDictEntry * found = (gdcmDictEntry*)0;
607 if (!RefPubDict && !RefShaDict) {
608 //FIXME build a default dictionary !
609 printf("FIXME in gdcmHeader::IsInDicts\n");
612 found = RefPubDict->GetTag(group, element);
617 found = RefShaDict->GetTag(group, element);
624 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
625 return PubElVals.GetElValue(group, element);
628 string gdcmHeader::GetPubElValByName(string TagName) {
629 return PubElVals.GetElValue(TagName);
633 * \ingroup gdcmHeader
634 * \brief Parses the header of the file but does NOT load element values.
636 void gdcmHeader::ParseHeader(void) {
637 ElValue * newElValue = (ElValue *)0;
641 while ( (newElValue = ReadNextElement()) ) {
642 SkipElementValue(newElValue);
643 PubElVals.Add(newElValue);
648 * \ingroup gdcmHeader
649 * \brief Loads the element values of all the elements present in the
650 * public tag based hash table.
652 void gdcmHeader::LoadElements(void) {
654 TagElValueHT ht = PubElVals.GetTagHt();
655 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag)
656 LoadElementValue(tag->second);
659 void gdcmHeader::PrintPubElVal(ostream & os) {
663 void gdcmHeader::PrintPubDict(ostream & os) {
664 RefPubDict->Print(os);