]> git.uio.no Git - u/mrichter/AliRoot.git/blob - HLT/TPCLib/HWCFemulator/AliHLTTPCHWCFSupport.cxx
f913076c85329f146fffefe914b5f1b139cb3b46
[u/mrichter/AliRoot.git] / HLT / TPCLib / HWCFemulator / AliHLTTPCHWCFSupport.cxx
1 // $Id$
2 //****************************************************************************
3 //* This file is property of and copyright by the ALICE HLT Project          * 
4 //* ALICE Experiment at CERN, All rights reserved.                           *
5 //*                                                                          *
6 //* Primary Authors: Sergey Gorbunov, Torsten Alt                            *
7 //* Developers:      Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de> *
8 //*                  Torsten Alt <talt@cern.ch>                              *
9 //*                  for The ALICE HLT Project.                              *
10 //*                                                                          *
11 //* Permission to use, copy, modify and distribute this software and its     *
12 //* documentation strictly for non-commercial purposes is hereby granted     *
13 //* without fee, provided that the above copyright notice appears in all     *
14 //* copies and that both the copyright notice and this permission notice     *
15 //* appear in the supporting documentation. The authors make no claims       *
16 //* about the suitability of this software for any purpose. It is            *
17 //* provided "as is" without express or implied warranty.                    *
18 //****************************************************************************
19
20 //  @file   AliHLTTPCHWCFSupport.cxx
21 //  @author Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de>
22 //  @author Torsten Alt <talt@cern.ch> 
23 //  @brief  Input interfaces for FPGA ClusterFinder Emulator for TPC
24 //  @brief  ( see AliHLTTPCHWCFEmulator class )
25 //  @note
26
27
28 #include "AliHLTTPCHWCFSupport.h"
29 #include "AliHLTDataTypes.h"
30 #include "AliHLTTPCMapping.h"
31 #include "AliHLTTPCDigitReaderUnpacked.h"
32 #include "AliHLTTPCTransform.h"
33 #include "AliHLTTPCDefinitions.h"
34 #include "AliRawDataHeader.h"
35 #include "AliHLTTPCHWCFEmulator.h"
36 #include "AliTPCcalibDB.h"
37 #include "AliTPCCalPad.h"
38 #include "AliTPCCalROC.h"
39 #include "TMath.h"
40
41 #include <cstdlib>
42 #include <algorithm>
43 #include <cerrno>
44 #include <sys/time.h>
45
46 using namespace std;
47
48 AliHLTTPCHWCFSupport::AliHLTTPCHWCFSupport()
49   : 
50   AliHLTLogging(),
51   fEventMemory(0),
52   fEventMCMemory(0)
53 {
54   // see header file for class documentation
55   for( int i=0; i<fgkNSlices; i++ )
56     for( int j=0; j<fgkNPatches; j++ ) fMapping[i][j] = 0;
57 }
58
59
60 AliHLTTPCHWCFSupport::~AliHLTTPCHWCFSupport()
61 {
62   // see header file for class documentation
63   for( int i=0; i<fgkNSlices; i++ )
64     for( int j=0; j<fgkNPatches; j++ ) delete[] fMapping[i][j];
65   ReleaseEventMemory(); 
66 }
67
68 AliHLTTPCHWCFSupport::AliHLTTPCHWCFSupport(const AliHLTTPCHWCFSupport&)
69   : 
70   AliHLTLogging(),
71   fEventMemory(0),
72   fEventMCMemory(0)
73 {
74   // dummy
75 }
76
77 AliHLTTPCHWCFSupport& AliHLTTPCHWCFSupport::operator=(const AliHLTTPCHWCFSupport&){
78   // dummy
79   return *this;
80 }
81
82
83 void AliHLTTPCHWCFSupport::ReleaseEventMemory()
84 {
85   // clean up 
86   if( fEventMemory ) delete[] fEventMemory;
87   if( fEventMCMemory )delete[] fEventMCMemory;
88   fEventMemory = 0;
89   fEventMCMemory = 0;
90 }
91
92
93 const AliHLTUInt32_t *AliHLTTPCHWCFSupport::GetMapping( int slice, int patch )
94
95   // see header file for class documentation
96   if( slice<0 || slice>=fgkNSlices ){
97     HLTFatal("Wrong slice number %d, no mapping is provided.", slice);
98     return 0;
99   }
100   if( patch<0 || patch>= fgkNPatches ){
101     HLTFatal("Wrong patch number %d, no mapping is provided.", patch);
102     return 0;
103   }
104   if( !fMapping[slice][patch] ) fMapping[slice][patch] = ReadMapping(slice,patch);
105 return fMapping[slice][patch];
106 }
107
108
109 AliHLTUInt32_t *AliHLTTPCHWCFSupport::ReadMapping( int slice, int patch, const char *mappingFileName ) const
110 {
111   // Create mapping array for one patch 
112   // If no mapping file provided, reads from default file
113   // Output: mapping [] array of type AliHLTUInt32_t, where :
114   //
115   // mapping[0] == N hardware adresses in the array (mapping size is maping[0] + 1 )
116   // mapping[hwAddress] == configWord
117   //
118   // configWord consist of:
119   //
120   // bits 0-7: pad number
121   // bits 8-13: row number
122   // bit  14 : flag for border pad
123   // bit  15 : is the pad active
124   // bits 16->28 : gain calibration as 13 bit fixed point,
125   //               with 1 bit position before decimal point
126
127   const AliHLTUInt32_t  kBorderFlag = (1 << 14); 
128   const AliHLTUInt32_t  kActiveFlag = (1 << 15); 
129   
130   if( slice<0 || slice>=fgkNSlices ){
131      HLTFatal("Wrong slice number %d, no mapping is provided.", slice);
132      return 0;
133   }
134
135   if( patch<0 || patch>5 ){
136      HLTFatal("Wrong patch number %d, no mapping is provided.", patch);
137      return 0;
138   }
139
140   // AliHLTTPCTransform::GetFirstRow returns first row in scheme A.
141   // We have to transform to scheme B by AliHLTTPCTransform::Slice2Sector.
142
143   UInt_t offsetSchemeB=0;
144   Int_t sector = 0;
145   {
146     Int_t tmp=0;
147     AliHLTTPCTransform::Slice2Sector(slice, AliHLTTPCTransform::GetFirstRow(patch),
148                                      sector, tmp);
149     offsetSchemeB = (UInt_t) tmp;
150   }
151   
152
153   AliTPCcalibDB *calib = AliTPCcalibDB::Instance();  
154   AliTPCCalPad * gainTPC = 0;
155   AliTPCCalROC * gainROC = 0;
156   if( calib ) gainTPC = calib->GetPadGainFactor();
157   if( gainTPC ) gainROC = gainTPC->GetCalROC(sector);  // pad gains per given sector
158   else{      
159     HLTWarning("No TPC gain calibration found");  
160   }
161
162   TString filename;
163   
164   if( mappingFileName ){
165     filename = mappingFileName;
166   } else {
167     const char* basePath=getenv("ALICE_ROOT");
168     if (basePath) filename.Form("%s/TPC/mapping/Patch%d.data", basePath,patch);    
169   } 
170   
171   ifstream inFile;
172   inFile.open(filename.Data());
173   if (!inFile) {
174     HLTFatal("Unable to open mapping file: %s   This means no mapping is provided.", filename.Data());
175     return 0;
176   }
177
178
179   AliHLTUInt32_t *mapping = 0; 
180   AliHLTUInt32_t *rowBranchPadHw = 0;
181   bool err = 1;
182   do{
183
184     UInt_t nHWAdd=0;
185     UInt_t maxHWAdd=0;
186
187     if( !(inFile >> nHWAdd ) || !(inFile >> maxHWAdd)  ){
188       HLTError("Mapping file for patch %d corrupted &s", patch,filename.Data());
189       break;
190     }
191
192     if( maxHWAdd > 0xFFF ){
193       HLTError("Max hardware address exceeded for patch %d, max number is %d, number from mapping file is %d.",patch, 0xFFF, maxHWAdd+1);       
194       break;
195     }
196
197     if(nHWAdd > maxHWAdd ){
198       HLTError("Too large number of hardware addresses for patch %d: max number is %d, number from mapping file is %d.",patch, maxHWAdd, nHWAdd );
199       break;
200     }
201       
202     mapping = new AliHLTUInt32_t[maxHWAdd+2];
203     rowBranchPadHw = new AliHLTUInt32_t[nHWAdd];
204     if( !mapping || !rowBranchPadHw ){
205       HLTError("Can not allocate &d bytes of memory", (maxHWAdd+1+nHWAdd)*sizeof(AliHLTUInt32_t));
206       break;
207     }
208
209     for( unsigned int i=0; i<maxHWAdd+2; i++ ) mapping[i] = 0;
210     for( unsigned int i=0; i<nHWAdd; i++ ) rowBranchPadHw[i] = 0;    
211     mapping[0] = maxHWAdd+1;
212     UInt_t nRead = 0;
213     err = 0;
214     while(!err ){
215       UInt_t hwAdd=0;
216       UInt_t row=0;
217       UInt_t pad=0;
218       if( !(inFile>>hwAdd) || !(inFile>>row) || !(inFile>>pad) ) break;      
219
220       err = 1;
221
222       if ( nRead >= nHWAdd ){
223         HLTError("Too many hardware addresses: %d, expected %d, mapping file %s corrupted?", nRead+1,  nHWAdd, filename.Data());
224         break;
225       }
226       if (hwAdd>maxHWAdd) {
227         HLTError("hardware address exceeds max hwAddress %d, mapping file %s corrupted?", maxHWAdd, filename.Data());   
228         break;
229       }
230
231       if( row < offsetSchemeB ){
232         HLTError("row number %d below minimum %d for patch %d, mapping file %s corrupted?", row, offsetSchemeB, patch, filename.Data());        
233         break;    
234       } 
235
236       row -= offsetSchemeB;
237         
238       if( row > 0x3F ){
239         HLTError("row number %d withing patch exceed the maximum %d for patch %d, mapping file %s corrupted?", row, 0x3F, patch, filename.Data());      
240         break;    
241       }
242
243       if( pad > 0xFF ){
244         HLTError("pad number %d exceed the maximum %d for patch %d, mapping file %s corrupted?", pad, 0xFF, patch, filename.Data());    
245         break;    
246       }
247
248       bool active = true; // Currently all channels are always active   
249       //
250
251       AliHLTFloat64_t gain = 1.;
252       if( gainROC ){
253         gain = gainROC->GetValue(offsetSchemeB+row,pad);
254         if( gain>1.e-4 ) gain = 1./gain;
255         else gain = 0;
256       }
257       gain*= (1<<12);
258       AliHLTUInt32_t  gainCalib = TMath::Nint(gain); 
259       if( gainCalib > 0x1FFF ) gainCalib = 0x1FFF;
260
261       AliHLTUInt32_t configWord = ( (row & 0x3F) << 8 ) | (pad & 0xFF);
262       if ( active ) configWord |= kActiveFlag;
263       configWord |= (gainCalib & 0x1FFF) << 16; 
264
265       mapping[1+hwAdd] = configWord;
266         
267       AliHLTUInt32_t branch = (hwAdd >> 11) & 0x1;      
268       rowBranchPadHw[nRead] = (row<<25) | (branch<<24) | (pad<<16) | hwAdd;
269
270       nRead++;
271       err = 0;
272     }
273     
274     if( err ) break;
275     
276     if ( nRead!= nHWAdd ){
277       HLTError("Too less hardware addresses: %d, expected %d, mapping file %s corrupted?", nRead,  nHWAdd, filename.Data());
278       err = 1;
279       break;
280     }
281     
282     // mark pads at borders of A/B branches 
283       
284     std::sort(rowBranchPadHw, rowBranchPadHw + nHWAdd);
285     int rowBranchLast = -1;
286     for( unsigned int i=0; i<nHWAdd; i++ ){
287       int rowBranch = rowBranchPadHw[i]>>24;
288       if( rowBranch != rowBranchLast ){
289         mapping[1+(rowBranchPadHw[i] & 0xFFF)] |= kBorderFlag;
290         rowBranchLast = rowBranch;
291         if( i>0 ) mapping[1+(rowBranchPadHw[i-1] & 0xFFF)] |= kBorderFlag;        
292       }
293     }
294     mapping[1+(rowBranchPadHw[nRead-1] & 0xFFF)] |= kBorderFlag;
295     
296   } while(0);
297   
298   inFile.close();
299
300   delete[] rowBranchPadHw;
301
302   if( err ){
303     delete[] mapping; 
304     return 0;
305   }
306   return mapping;
307 }
308
309
310 int AliHLTTPCHWCFSupport::CreateRawEvent
311 ( const AliHLTComponentBlockData* block, 
312   const AliHLTUInt32_t *&rawEvent, AliHLTUInt32_t &rawEventSize32, 
313   const AliHLTTPCClusterMCLabel *&mcLabels,  AliHLTUInt32_t &nMCLabels 
314 )
315 {
316   // the method creates TPC raw data out of the input block
317   // MC labels are provided if possible  
318   //
319
320   ReleaseEventMemory();
321   
322   rawEvent = 0;
323   rawEventSize32 = 0;
324   mcLabels = 0;
325   nMCLabels = 0;
326       
327   if( block->fPtr==NULL ){
328     HLTWarning("NULL pointer to the data block");
329     return 0;
330   }
331
332   Int_t slice = AliHLTTPCDefinitions::GetMinSliceNr( *block );
333   Int_t patch = AliHLTTPCDefinitions::GetMinPatchNr( *block );
334   AliHLTTPCMapping mapping(patch);
335
336   const char *str=Form("slice %d patch %d:", slice, patch);
337
338   if ( block->fDataType == (kAliHLTDataTypeDDLRaw | kAliHLTDataOriginTPC) )
339     {    
340       // already raw format -> only set the pointers and estimate the size
341
342       // read CDH header, estimate size of the data 
343       
344       AliHLTUInt64_t headerSize = sizeof(AliRawDataHeader);                  
345  
346       AliRawDataHeader *cdhHeader = reinterpret_cast<AliRawDataHeader*>(block->fPtr);
347       
348       AliHLTUInt64_t blockSize = block->fSize; // size of the raw data in bytes      
349
350       if( cdhHeader->fSize!=0xFFFFFFFF ){ // use size information from the header
351         blockSize = cdhHeader->fSize;
352         if( blockSize > block->fSize ){
353           HLTWarning("%s Could not find a valid DDL header!",str);
354           return 0;
355         }
356       }
357       
358       if( blockSize < headerSize ){
359         HLTWarning("%s Buffer size is smaller than CDH header size", str);
360         return 0;
361       }
362       
363       rawEvent = reinterpret_cast<AliHLTUInt32_t*> (reinterpret_cast<UChar_t*>(block->fPtr)+headerSize);
364       rawEventSize32 = ( blockSize - headerSize )/sizeof(AliHLTUInt32_t);
365
366     }
367   else if ( block->fDataType == AliHLTTPCDefinitions::fgkUnpackedRawDataType )
368     {
369
370       AliHLTTPCDigitReaderUnpacked digitReader;          
371       digitReader.SetUnsorted(kTRUE);      
372       
373       if( digitReader.InitBlock(block->fPtr,block->fSize,patch,slice)<0 ) {
374         HLTWarning("failed setting up digit reader (InitBlock)");
375         return 0;
376       }
377
378       int nDigitsTotal = 0;
379       int nBunchesTotal = 0;
380      
381       while( digitReader.NextChannel() ){
382         while(digitReader.NextBunch()){
383           nBunchesTotal++;
384           nDigitsTotal+=digitReader.GetBunchSize();
385         }
386       }
387       
388       digitReader.Reset();
389
390       if( digitReader.InitBlock(block->fPtr,block->fSize,patch,slice)<0) {
391         HLTWarning("failed setting up digit reader (InitBlock)");
392         return 0;
393       }
394       
395       Int_t nPadsTotal = 0;
396       Int_t firstRow = AliHLTTPCTransform::GetFirstRow(patch);
397       Int_t nRows = AliHLTTPCTransform::GetNRows(patch);
398
399       for( int i=0; i<nRows; i++ ){
400         nPadsTotal += AliHLTTPCTransform::GetNPads(firstRow+i); 
401       }
402
403       AliHLTUInt32_t totalSize32 = (nDigitsTotal + nBunchesTotal*2)/3+2*nPadsTotal + 10;
404       AliHLTUInt32_t totalNMC = nDigitsTotal + 10;
405       
406       fEventMemory = new AliHLTUInt32_t[totalSize32];
407       if( !fEventMemory ){
408         HLTWarning("Not enougth memory: can not allocate %d bytes",totalSize32*8);
409         return 0;
410       }
411
412       fEventMCMemory = new AliHLTTPCClusterMCLabel[totalNMC];
413       if( !fEventMCMemory ){
414         HLTWarning("Not enougth memory: can not allocate %d bytes",totalNMC*sizeof(AliHLTTPCClusterMCLabel));
415         delete[] fEventMemory;
416         fEventMemory = 0;
417         return 0;
418       }
419
420       AliHLTUInt32_t nWords32 = 0;
421       AliHLTUInt32_t mcIndex = 0;
422       int err=0;
423
424       AliHLTTPCDigitData tmpDigit;
425       tmpDigit.fTrackID[0] = -1;
426       tmpDigit.fTrackID[1] = -1;
427       tmpDigit.fTrackID[2] = -1;
428
429       while( !err && digitReader.NextChannel() ){
430         
431         Int_t row=digitReader.GetRow();
432         Int_t pad=digitReader.GetPad();
433
434         AliHLTUInt32_t hwAddr = mapping.GetHwAddress(row, pad);
435
436         // create header
437
438         if( nWords32 >= totalSize32){ err = 1; break; } 
439         
440         AliHLTUInt32_t *header = fEventMemory + nWords32;
441         nWords32++;
442
443         int seek10 = 2;
444         int prevTime = 10000000;
445         int nWords10 = 0;
446         while(digitReader.NextBunch()){
447
448           if( hwAddr > 0xFFF ) continue;
449
450           Int_t nSignals = digitReader.GetBunchSize();
451           if( nSignals <=0 ){
452             HLTWarning("Empty bunch received");
453             continue;
454           }
455
456           Int_t time = digitReader.GetTime() + nSignals-1;
457           
458           if( time-nSignals+1<0 || time>=AliHLTTPCTransform::GetNTimeBins() ){
459             HLTWarning("Wrong time bins received: %d-%d for row %d pad %d", time-nSignals+1, time, row, pad);
460             break;
461           }
462
463           if( time >= prevTime ){
464             HLTWarning("Unexpected order of TPC bunches in row %d, pad %d", row, pad);      
465             break;
466           }
467
468           prevTime = time-nSignals+1;
469           
470           if( nWords32+( 2+nSignals)/3+1 >= totalSize32 ){ err = 1; break; }
471           if( mcIndex + nSignals   >= totalNMC ){ err = 1; break; }
472
473           if( nWords10 + 2 + nSignals > 0x3FF ){
474             HLTWarning("Too much data in row %d, pad %d", row, pad);        
475             break;
476           }
477
478           nWords10 += 2 + nSignals;
479
480           Add10Word( nWords32, seek10, nSignals + 2 );
481           Add10Word( nWords32, seek10, time );
482           
483           const UInt_t *bunchData = digitReader.GetSignals();
484           const AliHLTTPCDigitData *mcDigits = digitReader.GetBunchDigits();
485           if( !mcDigits ){
486             HLTWarning("No MC labels found for a bunch of digits");
487           }
488
489           for(Int_t is=nSignals-1; is>=0; is--){
490             Add10Word( nWords32, seek10, bunchData[is] );           
491             const AliHLTTPCDigitData &digit = mcDigits ?mcDigits[is] :tmpDigit;
492             int nmc = 0;
493             for( int i=0; i<3; i++ ) if( digit.fTrackID[i] >=0 ) nmc++;      
494             for( int i=0; i<3; i++ ){
495               fEventMCMemory[mcIndex].fClusterID[i].fMCID = digit.fTrackID[i];
496               fEventMCMemory[mcIndex].fClusterID[i].fWeight = 0;
497               if( digit.fTrackID[i] >=0 ){                      
498                 fEventMCMemory[mcIndex].fClusterID[i].fWeight  = ((float)bunchData[is])/nmc;
499               }
500             }     
501             mcIndex++;
502           }       
503
504         } // bunches
505         
506       *header = (1<<30) | ((nWords10&0x3FF)<<16) | (hwAddr & 0xFFF);
507
508       }// channels (pads)
509
510       if( err ){
511         HLTError("Internal error: too less memory allocated");  
512       } else {
513         for( AliHLTUInt32_t i=0; i<nWords32; i++ ) fEventMemory[i] = AliHLTTPCHWCFEmulator::WriteBigEndian(fEventMemory[i]);
514         rawEvent = fEventMemory;
515         rawEventSize32 = nWords32;
516         mcLabels = fEventMCMemory;
517         nMCLabels = mcIndex;
518       }
519
520     } // unpacked data type
521
522   return 0;
523 }
524
525
526 void AliHLTTPCHWCFSupport::Add10Word( AliHLTUInt32_t &nWords32, int &seek10, UInt_t data )
527 {
528   // add 10-bit data to the 32-bit word
529   // fEventMemory [nWords32] --- current 32-bit word
530   // *seek10 --- 10-bit position withing the word
531   // pointers are increased, a new word is first initialised to 0
532
533   data = data & 0x3FF; // truncate to 10 bits
534
535   if( seek10 == 2 ){
536     nWords32++;
537     fEventMemory[nWords32-1] = data<<20;
538     seek10 = 1;
539   } else if( seek10 == 1 ){
540     fEventMemory[nWords32-1] &= 0xFFF003FF;
541     fEventMemory[nWords32-1] |= (data<<10);
542     seek10 = 0;
543   } else if( seek10 == 0 ){
544     fEventMemory[nWords32-1] &= 0xFFFFFC00;
545     fEventMemory[nWords32-1] |= data;
546     seek10 = 2;
547   } 
548 }
549
550
551
552 int AliHLTTPCHWCFSupport::CheckRawData( const AliHLTUInt32_t *buffer,
553                                                    unsigned long bufferSize32, int patch, int slice )
554 {
555   //
556   // The procedure checks consistency of the data
557   //
558
559   const unsigned int headerSize32 = 8;
560
561   if (!buffer) return 0;
562
563   const char *str=Form("slice %d patch %d:", slice, patch);
564   
565   if( bufferSize32 < headerSize32 ){
566     HLTWarning("%s Buffer size is smaller than CDH header size", str);
567     return kFALSE;
568   }    
569   
570   // read data header 
571  
572   AliHLTUInt32_t blockSize32 = bufferSize32; // size of the raw data in words
573
574   if( buffer[0]!=0xFFFFFFFF ) blockSize32 = buffer[0]/4; // use size information from the header  
575   if( blockSize32 > bufferSize32 ){  
576     HLTWarning(Form("%s Could not find a valid DDL header!",str));
577     return 0;
578   }
579   
580   UChar_t rcuVer = (UChar_t)( (buffer[1] >> 24) & 0xFF ); 
581
582   if (rcuVer < 2) {
583     HLTWarning("%s Old data format, RCU version %d", str,rcuVer);
584     return 0;
585   }
586
587   // is the block valid
588   //AliHLTUInt32_t blockAttributes = buffer[3]; // block attributes (bits 24-31) and participating sub detectors 
589   //cout<<blockAttributes<<" "<<(blockAttributes >> 24)<<endl;
590   //if ( !( (blockAttributes >> 24) & 1) ) return 0; 
591      
592
593   const AliHLTUInt32_t* fData = buffer + headerSize32;
594   unsigned long  dataSize32 = blockSize32 - headerSize32;       
595   
596   // Read the RCU trailer according to the RCU formware version specified in CDH
597   // Cross-check with version found in the trailer
598   // The two major bit should be 11 (identifies the end of the trailer)    
599   
600   AliHLTUInt32_t word = fData[dataSize32 - 1];
601   
602   if ((word >> 30) != 3) {
603     HLTWarning("%s Last RCU trailer word not found!", str);
604     return 0;
605   }
606   
607   UChar_t ver = (word >> 16) & 0xFF;
608   //AliHLTUInt32_t rcuId = (Int_t)((word >> 7) & 0x1FF);
609   AliHLTUInt32_t rcuTrailerSize32 = (word & 0x7F); // size of RCU trailer data in words
610   
611   if (ver != rcuVer) {
612     HLTWarning("%s Wrong RCU firmware version detected: %d != %d",
613                str,ver,rcuVer);
614     return 0;
615   }  
616
617   if (rcuTrailerSize32 < 2) {
618     HLTWarning(Form("Invalid trailer size found (%d bytes) !",
619                     rcuTrailerSize32*4));
620     return 0;
621   }
622   
623   if( rcuTrailerSize32 > dataSize32 ){
624     HLTWarning(Form("%s Invalid trailer size found (%d bytes) ! The size is bigger than the raw data size (%ld bytes)!",
625                     str, rcuTrailerSize32*4,dataSize32*4));
626     return 0;    
627   }
628
629   // check the trailer
630
631   Int_t trailerIndex = dataSize32 - rcuTrailerSize32;
632
633   for( unsigned int i=trailerIndex; i<dataSize32-1; i++){
634     if ((fData[i] >> 30) != 2) {
635       HLTWarning("%s Missing RCU trailer identifier pattern!",str);
636       continue;
637     }
638   }
639
640   // Read the payload size  
641  
642   Int_t  rcuPayloadSize32 = fData[trailerIndex] & 0x3FFFFFF;
643
644   if ( rcuPayloadSize32 + rcuTrailerSize32  != dataSize32) {
645     HLTWarning(Form("%s Inconsistent raw data size ! Raw data size - %ld bytes (from CDH), RCU trailer - %d bytes, raw data size (from RCU trailer) - %d bytes !",
646                     str, dataSize32*4,
647                     (rcuTrailerSize32)*4,
648                     rcuPayloadSize32*4));
649     return 0;
650   }
651     
652   
653   //AliHLTTPCMapping *mapping = new AliHLTTPCMapping(patch);
654   const int kMaxNTimeBins = 2000;
655
656   UShort_t  *channelData10 = new UShort_t[kMaxNTimeBins];    // cache for the decoded altro payload
657
658   Int_t position = 0; // current position (32-bit words) in fData
659  
660   while(1){
661
662     // Search for the next Altro channel
663
664     word = 0;
665     while( position < rcuPayloadSize32 ){
666       word = fData[position++];
667       if( (word >> 30) == 1) break;
668     }
669     if (position >= rcuPayloadSize32 ) break; // no next channel found
670     
671     // extract channel payload and hw address
672
673     Int_t channelPayloadSize10 = (word >> 16) & 0x3FF; // payload size in 10-bit words 
674     Int_t channelPayloadSize32 = (channelPayloadSize10+2)/3;
675     Bool_t channelIOErrors = (word >> 29) & 0x1; // check for readout errors    
676     Short_t  channelHWAddress = word & 0xFFF;
677
678     if( position + channelPayloadSize32-1> rcuPayloadSize32 ){
679       HLTWarning(Form("%s Inconsistent channel payload data size: expected <= %d bytes from RCU trailer, found %d bytes in the channel header!",
680                       str,(rcuPayloadSize32 - position)*4, channelPayloadSize32*4 ));
681       continue;
682     }
683
684     //bool channelBranchAB = ((channelHWAddress >> 11) & 0x1);
685     // int channelFEC       = ((channelHWAddress >> 7) & 0xF); // front-end card index
686     //int channelAltro = ((channelHWAddress >> 4) & 0x7); // altro chip index
687     //int channelIndex = (channelHWAddress & 0xF); // channel index
688     //int channelRow = mapping->GetRow(channelHWAddress);
689     //int channelPad = mapping->GetPad(channelHWAddress);
690
691     // Now unpack the Altro data: 10-bit words to 16 bit-words    
692     
693     Int_t channelData10Index = 0;// current position in the payload
694
695     for (Int_t iword = 0; iword < channelPayloadSize32; iword++) {
696       word = fData[position++];
697       if ((word >> 30) != 0) {
698         HLTWarning(Form("%s Unexpected end of payload in altro channel payload! Address=0x%x, word=0x%x",
699                         str, channelHWAddress,word));
700         channelIOErrors = 1;
701         position--;
702         break;
703       }
704       channelData10[channelData10Index++] = (word >> 20) & 0x3FF;
705       channelData10[channelData10Index++] = (word >> 10) & 0x3FF;
706       channelData10[channelData10Index++] = word & 0x3FF;
707     }
708   
709     if ( channelIOErrors ) continue;    
710
711     // read bunches
712
713     Int_t prevTimeBin =  1024;
714     channelData10Index = 0;
715
716     while(1){
717       
718       // Read next Altro bunch 
719   
720       if ((channelData10Index+1 >= channelPayloadSize10) ) break;
721     
722       Int_t bunchLength = channelData10[channelData10Index++];
723       Int_t bunchStartTimeBin = channelData10[channelData10Index++];
724
725       if (bunchLength <= 2) {
726         // Invalid bunch size
727         HLTWarning(Form("%s Too short bunch length (%d) in Address=0x%x!",
728                         str, bunchLength,channelHWAddress));    
729         break;
730       }
731       if( channelData10Index + bunchLength - 2 > channelPayloadSize10 ){
732         // Too long bunch detected
733         HLTWarning(Form("%s Too long bunch detected in Address=0x%x! Expected <= %d 10-bit words, found %d !",
734                         str,channelHWAddress,channelPayloadSize10-channelData10Index,bunchLength));
735         break;
736       }
737             
738       if( bunchStartTimeBin-bunchLength+1 < 0) {
739         HLTWarning(Form("%s Invalid start time-bin in Address=0x%x ! (%d-%d+1) < 0",
740                         str,channelHWAddress,bunchStartTimeBin,bunchLength));
741         break;
742       }
743       if (bunchStartTimeBin >= prevTimeBin) {
744         HLTWarning(Form("%s Invalid start time-bin in Address=0x%x! (%d>=%d)",
745                         str,channelHWAddress,bunchStartTimeBin,prevTimeBin));
746         break;
747       }
748
749       prevTimeBin = bunchStartTimeBin-bunchLength+1;
750   
751       bunchLength -= 2;
752         
753       //UShort_t* bunchData = &channelData10[channelData10Index];   // pointer to the current bunch samples
754       channelData10Index += bunchLength;            
755     }
756   }
757   
758   delete[] channelData10;
759   //delete mapping;
760
761   return 1;
762 }
763