]> Creatis software - gdcm.git/blob - Testing/TestAllReadCompareDicom.cxx
Track troubles on Big endian processors
[gdcm.git] / Testing / TestAllReadCompareDicom.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: TestAllReadCompareDicom.cxx,v $
5   Language:  C++
6   Date:      $Date: 2005/11/28 16:29:13 $
7   Version:   $Revision: 1.58 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18 #include "gdcmDirList.h"
19 #include "gdcmFile.h"
20 #include "gdcmFileHelper.h"
21 #include "gdcmGlobal.h"
22 #include "gdcmTS.h"
23 #include "gdcmDebug.h"
24 #include "gdcmUtil.h"
25
26 #include <iostream>
27
28 //Generated file:
29 #include "gdcmDataImages.h"
30
31 //-->
32 //--> WARNING :
33 //-->          The .tst files *must* be generated on a Little Endian based computer.
34 //-->
35 /**
36  * /brief   File Read/Writer specific for the TestAllReadCompareDicom test
37  * /remarks The Test file format is (only in little endian) :
38  *  - 4 bytes : 'gdcm'
39  *  - 4 bytes : size X
40  *  - 4 bytes : size Y
41  *  - 4 bytes : size Z
42  *  - 2 bytes : scalar size (8,16,32) --> ?!? 1 or 2 only in DICOM V3 !
43  *  - 2 bytes : number of components per pixel (1,2,3) ---> 1 or 3 only in DICOMV3 !
44  *  - n bytes : data
45  */
46 class TestFile
47 {
48 public:
49    TestFile();
50    ~TestFile();
51
52    bool IsReadable() {return readable;}
53    
54    int GetXSize() {return SizeX;}
55    int GetYSize() {return SizeY;}
56    int GetZSize() {return SizeZ;}
57    
58    void SetXSize(int size) {SizeX = size;}   
59    void SetYSize(int size) {SizeY = size;}
60    void SetZSize(int size) {SizeZ = size;}
61    
62    int GetScalarSize()                  {return ScalarSize;}
63    void SetScalarSize(int size)         {ScalarSize = size;}
64    
65    int GetNumberOfComponents()          {return Components;}
66    void SetNumberOfComponents(int size) {Components = size;}
67    int GetSwapCode() {return SwapCode;}
68
69    unsigned long GetDataSize() {return GetLineSize()*SizeY*SizeZ;}
70    uint8_t *GetData() {return Data;}
71    void SetData(const uint8_t *newData);
72
73    void Load(const std::string &filename);
74    void Write(const std::string &filename);
75
76 private:
77    unsigned long GetLineSize() {return SizeX*ScalarSize*Components;}
78    int ComputeSwapCode(uint32_t tag);
79
80    void NewData();
81    void DeleteData();
82
83    void ReadFile();
84    bool ReadFileHeader(std::ifstream *fp);
85    bool ReadFileData(std::ifstream *fp);
86    void WriteFile();
87    bool WriteFileHeader(std::ofstream *fp);
88    bool WriteFileData(std::ofstream *fp);
89
90    uint8_t  ReadInt8 (std::ifstream *fp)
91 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
92  throw( std::ios::failure );
93 #else
94  ;
95 #endif
96    uint16_t ReadInt16(std::ifstream *fp)
97 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
98   throw( std::ios::failure );
99 #else
100  ;
101 #endif
102    uint32_t ReadInt32(std::ifstream *fp)
103 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
104   throw( std::ios::failure );
105 #else
106  ;
107 #endif
108    void WriteInt8 (std::ofstream *fp,uint8_t  value);
109    void WriteInt16(std::ofstream *fp,uint16_t value);
110    void WriteInt32(std::ofstream *fp,uint32_t value);
111
112    std::string fileName;
113    bool readable;
114
115    int SizeX;
116    int SizeY;
117    int SizeZ;
118    uint16_t ScalarSize;
119    uint16_t Components;
120    uint8_t *Data;
121    int SwapCode;
122
123    static const unsigned int HEADER_SIZE;
124 };
125
126 const unsigned int MAX_NUMBER_OF_DIFFERENCE = 10;
127 const unsigned int TestFile::HEADER_SIZE = 20;
128
129 TestFile::TestFile()
130 {
131    fileName = "";
132    readable=false;
133
134    SizeX = 0;
135    SizeY = 0;
136    SizeZ = 0;
137    ScalarSize = 0;
138    Components = 0;
139    Data = NULL;
140
141    //SwapCode = 1234;
142 }
143
144 TestFile::~TestFile()
145 {
146    DeleteData();
147 }
148
149 void TestFile::SetData(const uint8_t *newData)
150 {
151    DeleteData();
152    NewData();
153    if( Data )
154       memcpy(Data,newData,GetDataSize());
155 }
156
157 void TestFile::Load(const std::string &filename)
158 {
159    fileName = filename;
160    ReadFile();
161 }
162
163 void TestFile::Write(const std::string &filename)
164 {
165    fileName = filename;
166    WriteFile();
167 }
168
169 int TestFile::ComputeSwapCode(uint32_t tag)
170 {
171 // FIXME : 100 % useless method !
172 // "gdcm" was written on disc byte per byte.
173 // when you fread if, you'll get *allways* "gdcm"
174 // whatever the processor indianess is !
175
176    int swap = 0;
177    //std::cout << std::hex << "0x(" << tag << ")" << std::dec << std::endl;
178    
179    for(int i=0;i<4;i++)
180    {
181       switch(tag&0x000000FF)
182       {
183          case 'g':
184             swap += (i+1)*1000;
185             break;
186          case 'd':
187             swap += (i+1)*100;
188             break;
189          case 'c':
190             swap += (i+1)*10;
191             break;
192          case 'm':
193             swap += (i+1);
194             break;
195          default:
196             return 0;
197       }
198       tag >>= 8;
199    }
200    return swap;
201 }
202
203 void TestFile::NewData()
204 {
205    DeleteData();
206    if( GetDataSize() == 0 )
207       return;
208    Data = new uint8_t[GetDataSize()];
209 }
210
211 void TestFile::DeleteData()
212 {
213    if( Data )
214       delete[] Data;
215    Data = NULL;
216 }
217
218 void TestFile::ReadFile()
219 {
220    readable=true;
221    std::ifstream fp(fileName.c_str(),std::ios::in | std::ios::binary);
222
223    if(!fp)
224    {
225       readable=false;
226       return;
227    }
228
229    try
230    {
231       readable=ReadFileHeader(&fp);
232       if(!readable)
233       {
234          std::cout << "Problems when reading Header part" << std::endl;
235          fp.close();
236          return;
237       }
238
239       readable=ReadFileData(&fp);
240       if(!readable)
241       {
242          std::cout << "Problems when reading data" << std::endl;
243          fp.close();
244          return;
245       }
246    }
247    catch(...)
248    {
249       readable=false;
250       fp.close();
251       return;
252    }
253
254    fp.close();
255 }
256
257 bool TestFile::ReadFileHeader(std::ifstream *fp)
258 {
259    uint32_t tag = ReadInt32(fp);
260    SwapCode = ComputeSwapCode(tag);
261    if( SwapCode == 0 )
262    {
263       std::cout << "TestFile: Bad tag - Must be 'gdcm'" << std::endl;
264       return(false);
265    }
266
267    SizeX = ReadInt32(fp); // Size X
268    SizeY = ReadInt32(fp); // Size Y
269    SizeZ = ReadInt32(fp); // Size Z
270    ScalarSize = ReadInt16(fp)/8; // bytes per scalar
271    Components = ReadInt16(fp);   // Number of components
272
273    return(true);
274 }
275
276 bool TestFile::ReadFileData(std::ifstream *fp)
277 {
278    DeleteData();
279
280    // Allocate data
281    NewData();
282    if( !Data )
283       return(false);
284
285    // Read data  Note : .tst images are *always* created 
286    //           on little endian processor !
287    fp->read((char *)Data,GetDataSize());
288
289    // Track BigEndian troubles
290    std::cout << " ScalarSize : " << GetScalarSize() 
291           << " IsCurrentProcessorBigEndian:" 
292           << gdcm::Util::IsCurrentProcessorBigEndian()
293           << std::endl;
294         
295    //if (GetScalarSize() == 1 || GetSwapCode() == 1234)  
296    if (GetScalarSize() == 1 || !gdcm::Util::IsCurrentProcessorBigEndian() )    
297    {
298       return true;
299    }
300    // We *know* the .tst files are written in 'Little Endian' format.
301    // We *know* DataSize may be 1 or 2 !  
302    uint16_t g;
303    
304    std::cout << " Let's swap Pixels" <<std::endl; 
305      
306    for (unsigned int i=0; i<GetDataSize()/2; i++)
307    {
308       g = ((uint16_t *)Data)[i];
309       g = ( g << 8 |  g >> 8  );
310       ((uint16_t *)Data)[i] = g;   
311    }
312    return(true);
313 }
314
315 void TestFile::WriteFile()
316 {
317    std::ofstream fp(fileName.c_str(),std::ios::out | std::ios::binary);
318
319    if(!fp)
320    {
321       readable=false;
322       return;
323    }
324
325    WriteFileHeader(&fp);
326    WriteFileData(&fp);
327
328    fp.close();
329 }
330
331 bool TestFile::WriteFileHeader(std::ofstream *fp)
332 {
333    WriteInt8(fp,'g'); // Bitmap tag - must be 'g'
334    WriteInt8(fp,'d'); // Bitmap tag - must be 'd'
335    WriteInt8(fp,'c'); // Bitmap tag - must be 'c'
336    WriteInt8(fp,'m'); // Bitmap tag - must be 'm'
337    
338    // FIXME : Think of writting an int32, better !
339    // (('g' << 8 + 'd') << 8 + 'c') + 'm'
340    // if you want to use it to check the endianess.
341    // (and upload again *all* the .tst files ...)
342    WriteInt32(fp,SizeX); // Size X
343    WriteInt32(fp,SizeY); // Size Y
344    WriteInt32(fp,SizeZ); // Size Z
345    WriteInt16(fp,ScalarSize*8); // bits per scalar
346    WriteInt16(fp,Components);   // number of components
347
348    return(true);
349 }
350
351 bool TestFile::WriteFileData(std::ofstream *fp)
352 {
353    fp->write((char *)Data,GetDataSize());
354
355    return(true);
356 }
357
358 uint8_t  TestFile::ReadInt8 (std::ifstream *fp)
359 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
360    throw( std::ios::failure )
361 #endif
362 {
363    uint8_t g;
364    fp->read ((char*)&g, (size_t)1);
365 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
366    if ( fp->fail() )
367       throw std::ios::failure( "TestFile::ReadInt8() - file error." );
368    if( fp->eof() )
369       throw std::ios::failure( "TestFile::ReadInt8() - EOF." );
370 #endif
371    return g;
372 }
373
374 uint16_t TestFile::ReadInt16(std::ifstream *fp)
375 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
376    throw( std::ios::failure )
377 #endif
378 {
379    uint16_t g;
380    fp->read ((char*)&g, (size_t)2);
381 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
382    if ( fp->fail() )
383       throw std::ios::failure( "TestFile::ReadInt16() - file error." );
384    if( fp->eof() )
385       throw std::ios::failure( "TestFile::ReadInt16() - EOF." );
386 #endif
387
388 #if defined(GDCM_WORDS_BIGENDIAN)
389    g = ( g << 8 |  g >> 8  );
390 #endif
391    return g;
392 }
393
394 uint32_t TestFile::ReadInt32(std::ifstream *fp)
395 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
396    throw( std::ios::failure )
397 #endif
398 {
399    uint32_t g;
400    fp->read ((char*)&g, (size_t)4);
401 #if !(__GNUC__==2  && __GNUC_MINOR__<=96)
402    if ( fp->fail() )
403       throw std::ios::failure( "TestFile::ReadInt32() - file error." );
404    if( fp->eof() )
405       throw std::ios::failure( "TestFile::ReadInt32() - EOF." );
406 #endif
407
408 #if defined(GDCM_WORDS_BIGENDIAN)
409    g = (  (g<<24)               | ((g<<8)  & 0x00ff0000) | 
410        (  (g>>8)  & 0x0000ff00) |  (g>>24)               );
411 #endif
412    return g;
413 }
414
415 void TestFile::WriteInt8 (std::ofstream *fp,uint8_t value)
416 {
417    fp->write((char*)&value, (size_t)1);
418 }
419
420 void TestFile::WriteInt16(std::ofstream *fp,uint16_t value)
421 {
422 #if defined(GDCM_WORDS_BIGENDIAN)
423    value = ( value << 8 |  value >> 8  );
424 #endif
425    fp->write((char*)&value, (size_t)2);
426 }
427
428 void TestFile::WriteInt32(std::ofstream *fp,uint32_t value)
429 {
430 #if defined(GDCM_WORDS_BIGENDIAN)
431    value = (  (value<<24)               | ((value<<8)  & 0x00ff0000) | 
432            (  (value>>8)  & 0x0000ff00) |  (value>>24)               );
433 #endif
434    fp->write((char*)&value, (size_t)4);
435 }
436
437 int InternalTest(std::string const &filename, 
438                  std::string const &referenceFileName )
439 {
440       std::cout << "   Testing: " << filename << std::endl;
441       std::cout << "      ";
442
443       ////// Step 1:
444       std::cout << "1...";
445
446        // new style 
447       gdcm::File *f = gdcm::File::New();
448       f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
449       f->SetFileName( filename );
450       f->Load();
451  
452       if( !f->IsReadable() )
453       {
454         std::cout << " Failed" << std::endl
455                    << "      Image not gdcm compatible:"
456                   << filename << std::endl;
457         f->Delete();
458         return 1;
459       }
460       gdcm::FileHelper *tested = gdcm::FileHelper::New( f );
461      
462       ////// Step 2:
463       ////// Check for existence of reference baseline dicom file:
464       std::cout << "2...";
465
466       TestFile *reference = new TestFile();
467       std::ifstream refFile(referenceFileName.c_str(),
468                             std::ios::binary|std::ios::in);
469       if(!refFile)
470       {
471          std::cout << " Failed" << std::endl
472                    << "      Image not found:"
473                    << referenceFileName << std::endl;
474          reference->SetXSize(tested->GetFile()->GetXSize());
475          reference->SetYSize(tested->GetFile()->GetYSize());
476          reference->SetZSize(tested->GetFile()->GetZSize());
477          reference->SetScalarSize(tested->GetFile()->GetPixelSize());
478          reference->SetNumberOfComponents(tested->GetFile()->GetNumberOfScalarComponents());
479          reference->SetData(tested->GetImageData());
480          reference->Write(referenceFileName);
481       }
482       else
483          refFile.close();
484
485       reference->Load(referenceFileName);
486       if(!reference->IsReadable())
487       {
488         std::cout << " Failed" << std::endl
489                    << "      Image not Testing compatible:"
490                   << filename << std::endl;
491          delete reference;
492          tested->Delete();
493          f->Delete();
494          return 1;
495       }
496
497       ////// Step 3:
498       std::string PixelType = tested->GetFile()->GetPixelType();
499       std::cout << "3...";
500       int testedDataSize    = tested->GetImageDataSize();
501       uint8_t *testedImageData = tested->GetImageData();
502     
503       int    referenceDataSize = reference->GetDataSize();
504       uint8_t *referenceImageData = reference->GetData();
505
506       // Test the image size
507       if (tested->GetFile()->GetXSize() != reference->GetXSize() ||
508           tested->GetFile()->GetYSize() != reference->GetYSize() ||
509           tested->GetFile()->GetZSize() != reference->GetZSize())
510       {
511          std::cout << "Failed" << std::endl
512                    << "        Size differs: "
513                    << "X: " << tested->GetFile()->GetXSize() << " # " 
514                    << reference->GetXSize() << " | "
515                    << "Y: " << tested->GetFile()->GetYSize() << " # " 
516                    << reference->GetYSize() << " | "
517                    << "Z: " << tested->GetFile()->GetZSize() << " # " 
518                    << reference->GetZSize() << std::endl;
519          delete reference;
520          tested->Delete();
521          f->Delete();
522          return 1;
523       }
524
525       // Test the pixel size
526       if (tested->GetFile()->GetPixelSize() != reference->GetScalarSize() ||
527           tested->GetFile()->GetNumberOfScalarComponents() != reference->GetNumberOfComponents())
528       {
529          std::cout << "Failed" << std::endl
530                    << "        Pixel size differs: " << std::endl
531                    << "        Scalar size: " << tested->GetFile()->GetPixelSize() << " # " 
532                    << reference->GetScalarSize() << std::endl
533                    << "        Number of scalar: " << tested->GetFile()->GetNumberOfScalarComponents() << " # " 
534                    << reference->GetNumberOfComponents() << std::endl
535                    << "        Pixel type: " << tested->GetFile()->GetPixelType() << std::endl;
536          delete reference;
537          tested->Delete();
538          f->Delete();
539          return 1;
540       }
541
542       // Test the data size
543       if (testedDataSize != referenceDataSize)
544       {
545          std::cout << " Failed" << std::endl
546                    << "        pixel ("
547                    << PixelType
548                    <<") areas lengths differ: "
549                    << testedDataSize << " # " << referenceDataSize
550                    << std::endl
551                    << "        Image size: ("
552                    << tested->GetFile()->GetXSize() << ","
553                    << tested->GetFile()->GetYSize() << ","
554                    << tested->GetFile()->GetZSize() << ")"
555                    << std::endl;
556          tested->Delete();
557          delete reference;
558          f->Delete();
559          return 1;
560       }
561
562       // Test the data content
563       if ( memcmp(testedImageData, referenceImageData,
564                            testedDataSize) != 0 )
565       {
566          std::string ts  = tested->GetFile()->GetTransferSyntax();
567
568          std::cout << " Failed" << std::endl
569                    << "        pixel (" 
570                    << PixelType
571                    << ") differ (as expanded in memory)."
572                    << std::endl
573                    << "        compression : " 
574                    << gdcm::Global::GetTS()->GetValue(ts) << std::endl;
575
576          std::cout << "        list of the first " << MAX_NUMBER_OF_DIFFERENCE
577                    << " pixels differing (pos : test - ref) :" 
578                    << std::endl;
579          int i;
580          unsigned int j;
581          for(i=0, j=0;i<testedDataSize && j<MAX_NUMBER_OF_DIFFERENCE;i++)
582          {
583             if(testedImageData[i]!=referenceImageData[i])
584               {
585                std::cout << std::hex << "(" << i << " : " 
586                          << std::hex << (int)(testedImageData[i]) << " - "
587                          << std::hex << (int)(referenceImageData[i]) << ") "
588                          << std::dec;
589                ++j;
590               }
591          }
592          std::cout << std::endl;
593
594          tested->Delete();
595          delete reference;
596          f->Delete();
597          return 1;
598       }
599
600       //////////////// Clean up:
601       tested->Delete();
602       delete reference;
603       f->Delete();
604
605       std::cout << "OK." << std::endl;
606       
607       return 0;
608 }
609
610 int TestAllReadCompareDicom(int argc, char *argv[]) 
611 {
612 // Temporarily added, to track BigEndian troubles
613 gdcm::Debug::WarningOn();
614
615    if (argc == 4)
616       gdcm::Debug::DebugOn();
617
618    if ( argc >= 3 )
619    {
620       // The test is specified a specific filename, use it instead of looping
621       // over all images
622       const std::string input = argv[1];
623       const std::string reference = argv[2];
624       return InternalTest( input, reference );
625    }
626    else if ( argc > 4 || argc == 2 )
627    {
628       std::cerr << "   Usage: " << argv[0]
629                 << " (no arguments needed)." << std::endl;
630       std::cerr << "or   Usage: " << argv[0]
631                 << " filename.dcm reference.dcm" << std::endl;
632       return 1;
633    }
634    // else other cases:
635    
636    std::cout << "   Description (Test::TestAllReadCompareDicom): "
637              << std::endl;
638    std::cout << "   For all images in gdcmData (and not blacklisted in "
639                 "Test/CMakeLists.txt)"
640              << std::endl;
641    std::cout << "   apply the following to each filename.xxx: "
642              << std::endl;
643    std::cout << "   step 1: parse the image (as gdcmFile) and call"
644              << " IsReadable(). "
645              << std::endl;
646    std::cout << "   step 2: find in GDCM_DATA_ROOT/BaselineDicom/filename.tst"
647              << std::endl
648              << "           special internal file format containing the"
649              << std::endl
650              << "           caracteristic of the image and the pixel data "
651              << "(uncompressed). This file is written if it's not found."
652              << std::endl;
653    std::cout << "   step 3: compare the DICOM image with the reference image"
654              << std::endl
655              << "           (.tst file). The test is made on the caracteristics"
656              << std::endl
657              << "           of the image and the pixel data"
658              << std::endl << std::endl;
659
660    int i = 0;
661    int result = 0;
662    while( gdcmDataImages[i] != 0 )
663    {
664       ////// Check for existence of reference baseline directory
665
666       std::string baseLineDir = GDCM_DATA_ROOT;
667       baseLineDir += "/BaselineDicom";
668
669       if( !gdcm::DirList::IsDirectory(baseLineDir) )
670       {
671          std::cerr << "   The reference baseline directory " << std::endl
672                    << "      "
673                    << baseLineDir << std::endl
674                    << "   couldn't be opened."
675                    << std::endl;
676          return 1;
677       }
678
679 //if (gdcmDataImages[i] == "D_CLUNIE_CT2_RLE.dcm")
680 //   gdcm::Debug::DebugOn(); // track pb on BigEndian Proc
681 //else 
682    gdcm::Debug::DebugOff();
683    
684       ////// Step 1 (see above description):
685       std::string filename = GDCM_DATA_ROOT;
686       filename += "/";
687       filename += gdcmDataImages[i];
688       
689       baseLineDir += '/';
690       std::string referenceFileName = baseLineDir + gdcmDataImages[i++];
691       std::string::size_type slash_pos = referenceFileName.rfind( "." );
692       if( slash_pos != std::string::npos )
693       {
694          referenceFileName.replace( slash_pos + 1, 3, "tst" );
695       }
696
697       if( InternalTest( filename, referenceFileName ) != 0 )
698       {
699          result++;
700       }
701    }
702
703    return result;
704 }