]> git.uio.no Git - u/mrichter/AliRoot.git/blob - HLT/BASE/AliHLTComponent.cxx
adding functionality to configure from an OCDB object of type TMap of TObjStrings
[u/mrichter/AliRoot.git] / HLT / BASE / AliHLTComponent.cxx
1 // $Id$
2
3 //**************************************************************************
4 //* This file is property of and copyright by the ALICE HLT Project        * 
5 //* ALICE Experiment at CERN, All rights reserved.                         *
6 //*                                                                        *
7 //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
8 //*                  Timm Steinbeck <timm@kip.uni-heidelberg.de>           *
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   AliHLTComponent.cxx
21 //  @author Matthias Richter, Timm Steinbeck
22 //  @date   
23 //  @brief  Base class implementation for HLT components. */
24 //  @note   The class is both used in Online (PubSub) and Offline (AliRoot)
25 //          context
26
27
28 #if __GNUC__>= 3
29 using namespace std;
30 #endif
31
32 //#include "AliHLTStdIncludes.h"
33 #include "AliHLTComponent.h"
34 #include "AliHLTComponentHandler.h"
35 #include "AliHLTMessage.h"
36 #include "AliHLTCTPData.h"
37 #include "AliRawDataHeader.h"
38 #include "TString.h"
39 #include "TMath.h"
40 #include "TObjArray.h"
41 #include "TObjectTable.h"
42 #include "TClass.h"
43 #include "TStopwatch.h"
44 #include "TFormula.h"
45 #include "TUUID.h"
46 #include "TMD5.h"
47 #include "TRandom3.h"
48 #include "AliHLTMemoryFile.h"
49 #include "AliHLTMisc.h"
50 #include <cassert>
51 #include <ctime>
52 #include <stdint.h>
53
54 /**
55  * default compression level for ROOT objects
56  */
57 #define ALIHLTCOMPONENT_DEFAULT_OBJECT_COMPRESSION 5
58 #define ALIHLTCOMPONENT_STATTIME_SCALER 1000000
59
60 /** ROOT macro for the implementation of ROOT specific class methods */
61 ClassImp(AliHLTComponent);
62
63 /** stopwatch macro using the stopwatch guard */
64 #define ALIHLTCOMPONENT_STOPWATCH(type) AliHLTStopwatchGuard swguard(fpStopwatches!=NULL?reinterpret_cast<TStopwatch*>(fpStopwatches->At((int)type)):NULL)
65 //#define ALIHLTCOMPONENT_STOPWATCH(type) 
66
67 /** stopwatch macro for operations of the base class */
68 #define ALIHLTCOMPONENT_BASE_STOPWATCH() ALIHLTCOMPONENT_STOPWATCH(kSWBase)
69 /** stopwatch macro for operations of the detector algorithm (DA) */
70 #define ALIHLTCOMPONENT_DA_STOPWATCH() ALIHLTCOMPONENT_STOPWATCH(kSWDA)
71
72 AliHLTComponent::AliHLTComponent()
73   :
74   fEnvironment(),
75   fCurrentEvent(0),
76   fEventCount(-1),
77   fFailedEvents(0),
78   fCurrentEventData(),
79   fpInputBlocks(NULL),
80   fCurrentInputBlock(-1),
81   fSearchDataType(kAliHLTVoidDataType),
82   fClassName(),
83   fpInputObjects(NULL),
84   fpOutputBuffer(NULL),
85   fOutputBufferSize(0),
86   fOutputBufferFilled(0),
87   fOutputBlocks(),
88   fpStopwatches(new TObjArray(kSWTypeCount)),
89   fMemFiles(),
90   fpRunDesc(NULL),
91   fCDBSetRunNoFunc(false),
92   fChainId(),
93   fChainIdCrc(0),
94   fpBenchmark(NULL),
95   fFlags(0),
96   fEventType(gkAliEventTypeUnknown),
97   fComponentArgs(),
98   fEventDoneData(NULL),
99   fEventDoneDataSize(0),
100   fCompressionLevel(ALIHLTCOMPONENT_DEFAULT_OBJECT_COMPRESSION)
101   , fLastObjectSize(0)
102   , fpCTPData(NULL)
103   , fPushbackPeriod(0)
104   , fLastPushBackTime(-1)
105 {
106   // see header file for class documentation
107   // or
108   // refer to README to build package
109   // or
110   // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
111   memset(&fEnvironment, 0, sizeof(AliHLTAnalysisEnvironment));
112   if (fgpComponentHandler)
113     fgpComponentHandler->ScheduleRegister(this);
114   //SetLocalLoggingLevel(kHLTLogDefault);
115 }
116
117 AliHLTComponent::~AliHLTComponent()
118 {
119   // see header file for function documentation
120   if (fpBenchmark) delete fpBenchmark;
121   fpBenchmark=NULL;
122
123   CleanupInputObjects();
124   if (fpStopwatches!=NULL) delete fpStopwatches;
125   fpStopwatches=NULL;
126   AliHLTMemoryFilePList::iterator element=fMemFiles.begin();
127   while (element!=fMemFiles.end()) {
128     if (*element) {
129       if ((*element)->IsClosed()==0) {
130         HLTWarning("memory file has not been closed, possible data loss or incomplete buffer");
131         // close but do not flush as we dont know whether the buffer is still valid
132         (*element)->CloseMemoryFile(0);
133       }
134       delete *element;
135       *element=NULL;
136     }
137     element++;
138   }
139   if (fpRunDesc) {
140     delete fpRunDesc;
141     fpRunDesc=NULL;
142   }
143   if (fEventDoneData)
144     delete [] reinterpret_cast<AliHLTUInt8_t*>( fEventDoneData );
145   fEventDoneData=NULL;
146
147   if (fpCTPData) {
148     delete fpCTPData;
149   }
150   fpCTPData=NULL;
151 }
152
153 AliHLTComponentHandler* AliHLTComponent::fgpComponentHandler=NULL;
154
155 int AliHLTComponent::SetGlobalComponentHandler(AliHLTComponentHandler* pCH, int bOverwrite) 
156 {
157   // see header file for function documentation
158   int iResult=0;
159   if (fgpComponentHandler==NULL || bOverwrite!=0)
160     fgpComponentHandler=pCH;
161   else
162     iResult=-EPERM;
163   return iResult;
164 }
165
166 int AliHLTComponent::UnsetGlobalComponentHandler() 
167 {
168   // see header file for function documentation
169   return SetGlobalComponentHandler(NULL,1);
170 }
171
172 int AliHLTComponent::SetComponentEnvironment(const AliHLTAnalysisEnvironment* comenv, void* environParam)
173 {
174   // see header file for function documentation
175   HLTLogKeyword(fChainId.c_str());
176   int iResult=0;
177   if (comenv) {
178     memset(&fEnvironment, 0, sizeof(AliHLTAnalysisEnvironment));
179     memcpy(&fEnvironment, comenv, comenv->fStructSize<sizeof(AliHLTAnalysisEnvironment)?comenv->fStructSize:sizeof(AliHLTAnalysisEnvironment));
180     fEnvironment.fStructSize=sizeof(AliHLTAnalysisEnvironment);
181     fEnvironment.fParam=environParam;
182   }
183   return iResult;
184 }
185
186 int AliHLTComponent::Init(const AliHLTAnalysisEnvironment* comenv, void* environParam, int argc, const char** argv )
187 {
188   // see header file for function documentation
189   HLTLogKeyword(fChainId.c_str());
190   int iResult=0;
191   if (comenv) {
192     SetComponentEnvironment(comenv, environParam);
193   }
194   fPushbackPeriod=0;
195   fLastPushBackTime=-1;
196
197   fComponentArgs="";
198   const char** pArguments=NULL;
199   int iNofChildArgs=0;
200   TString argument="";
201   int bMissingParam=0;
202   if (argc>0) {
203     pArguments=new const char*[argc];
204     if (pArguments) {
205       for (int i=0; i<argc && iResult>=0; i++) {
206         if (fComponentArgs.size()>0) fComponentArgs+=" ";
207         fComponentArgs+=argv[i];
208         argument=argv[i];
209         if (argument.IsNull()) continue;
210
211         // benchmark
212         if (argument.CompareTo("-benchmark")==0) {
213
214           // -loglevel=
215         } else if (argument.BeginsWith("-loglevel=")) {
216           TString parameter=argument.ReplaceAll("-loglevel=", "");
217           parameter.Remove(TString::kLeading, ' '); // remove all blanks
218           if (parameter.BeginsWith("0x") &&
219               parameter.Replace(0,2,"",0).IsHex()) {
220             unsigned int loglevel=kHLTLogNone;
221             sscanf(parameter.Data(),"%x", &loglevel);
222             SetLocalLoggingLevel((AliHLTComponentLogSeverity)loglevel);
223           } else {
224             HLTError("wrong parameter for argument %s, hex number expected", argument.Data());
225             iResult=-EINVAL;
226           }
227           // -object-compression=
228         } else if (argument.BeginsWith("-object-compression=")) {
229           argument.ReplaceAll("-object-compression=", "");
230           if (argument.IsDigit()) {
231             fCompressionLevel=argument.Atoi();
232             if (fCompressionLevel<0 || fCompressionLevel>9) {
233               HLTWarning("invalid compression level %d, setting to default %d", fCompressionLevel, ALIHLTCOMPONENT_DEFAULT_OBJECT_COMPRESSION);
234               fCompressionLevel=ALIHLTCOMPONENT_DEFAULT_OBJECT_COMPRESSION;
235             }
236           } else {
237             HLTError("wrong parameter for argument -object-compression, number expected");
238           }
239           // -pushback-period=
240         } else if (argument.BeginsWith("-pushback-period=")) {
241           argument.ReplaceAll("-pushback-period=", "");
242           if (argument.IsDigit()) {
243             fPushbackPeriod=argument.Atoi();
244           } else {
245             HLTError("wrong parameter for argument -pushback-period, number expected");
246           }
247           // -disable-component-stat
248         } else if (argument.CompareTo("-disable-component-stat")==0) {
249           fFlags|=kDisableComponentStat;
250         } else {
251           pArguments[iNofChildArgs++]=argv[i];
252         }
253       }
254     } else {
255       iResult=-ENOMEM;
256     }
257   }
258   if (bMissingParam) {
259     HLTError("missing parameter for argument %s", argument.Data());
260     iResult=-EINVAL;
261   }
262   if (iResult>=0) {
263     iResult=CheckOCDBEntries();
264   }
265   if (iResult>=0) {
266     iResult=DoInit(iNofChildArgs, pArguments);
267   }
268   if (iResult>=0) {
269     fEventCount=0;
270
271     // find out if the component wants to get the steering events
272     // explicitly
273     AliHLTComponentDataTypeList inputDt;
274     GetInputDataTypes(inputDt);
275     bool bRequireSteeringBlocks=false;
276     for (AliHLTComponentDataTypeList::iterator dt=inputDt.begin();
277          dt!=inputDt.end() && !bRequireSteeringBlocks;
278          dt++) {
279       bRequireSteeringBlocks|=MatchExactly(*dt,kAliHLTDataTypeSOR);
280       bRequireSteeringBlocks|=MatchExactly(*dt,kAliHLTDataTypeRunType);
281       bRequireSteeringBlocks|=MatchExactly(*dt,kAliHLTDataTypeEOR);
282       bRequireSteeringBlocks|=MatchExactly(*dt,kAliHLTDataTypeDDL);
283       bRequireSteeringBlocks|=MatchExactly(*dt,kAliHLTDataTypeComponentStatistics);
284     }
285     if (bRequireSteeringBlocks) fFlags|=kRequireSteeringBlocks;
286   }
287   if (pArguments) delete [] pArguments;
288
289 #if defined(HLT_COMPONENT_STATISTICS)
290   // benchmarking stopwatch for the component statistics
291   fpBenchmark=new TStopwatch;
292 #endif // HLT_COMPONENT_STATISTICS
293
294   return iResult;
295 }
296
297 int AliHLTComponent::Deinit()
298 {
299   // see header file for function documentation
300   HLTLogKeyword(fChainId.c_str());
301   int iResult=0;
302   iResult=DoDeinit();
303   if (fpRunDesc) {
304     // TODO: the warning should be kept, but the condition is wrong since the
305     // AliHLTRunDesc is set before the SOR event in the SetRunDescription
306     // method. A couple of state flags should be defined but that is a bit more
307     // work to do. For the moment disable the warning (2009-07-01)
308     // 2009-09-08: now, the info is not cleared in the ProcessEvent, because it
309     // might be needed by components during the event processing.
310     //HLTWarning("did not receive EOR for run %d", fpRunDesc->fRunNo);
311     AliHLTRunDesc* pRunDesc=fpRunDesc;
312     fpRunDesc=NULL;
313     delete pRunDesc;
314   }
315   if (fpCTPData) {
316     delete fpCTPData;
317   }
318   fpCTPData=NULL;
319
320   fEventCount=0;
321   fFlags=0;
322   return iResult;
323 }
324
325 int AliHLTComponent::InitCDB(const char* cdbPath, AliHLTComponentHandler* pHandler)
326 {
327   // see header file for function documentation
328   int iResult=0;
329   HLTInfo("Using CDB: %s", cdbPath);
330   if (pHandler) {
331   // I have to think about separating the library handling from the
332   // component handler. Requiring the component handler here is not
333   // the cleanest solution.
334   // We presume the library already to be loaded, which is the case
335   // because it is loaded in the initialization of the logging functionality
336   //
337   // find the symbol
338   AliHLTMiscInitCDB_t pFunc=(AliHLTMiscInitCDB_t)pHandler->FindSymbol(ALIHLTMISC_LIBRARY, ALIHLTMISC_INIT_CDB);
339   if (pFunc) {
340     TString path;
341     if (cdbPath && cdbPath[0]!=0) {
342       path=cdbPath;
343       // very temporary fix, have to check for other formats
344       if (!path.BeginsWith("local://")) {
345         path="local://";
346         path+=cdbPath;
347       }
348     }
349     if ((iResult=(*pFunc)(path.Data()))>=0) {
350       if (!(fCDBSetRunNoFunc=pHandler->FindSymbol(ALIHLTMISC_LIBRARY, ALIHLTMISC_SET_CDB_RUNNO))) {
351         Message(NULL, kHLTLogWarning, "AliHLTComponent::InitCDB", "init CDB",
352                 "can not find function to set CDB run no");
353       }
354     }
355   } else {
356     Message(NULL, kHLTLogError, "AliHLTComponent::InitCDB", "init CDB",
357             "can not find initialization function");
358     iResult=-ENOSYS;
359   }
360   } else {
361     iResult=-EINVAL;
362   }
363   return iResult;
364 }
365
366 int AliHLTComponent::SetCDBRunNo(int runNo)
367 {
368   // see header file for function documentation
369   if (!fCDBSetRunNoFunc) return 0;
370   return (*((AliHLTMiscSetCDBRunNo_t)fCDBSetRunNoFunc))(runNo);
371 }
372
373 int AliHLTComponent::SetRunDescription(const AliHLTRunDesc* desc, const char* /*runType*/)
374 {
375   // see header file for function documentation
376   if (!desc) return -EINVAL;
377   if (desc->fStructSize!=sizeof(AliHLTRunDesc)) {
378     HLTError("invalid size of RunDesc struct (%ul)", desc->fStructSize);
379     return -EINVAL;
380   }
381
382   if (!fpRunDesc) {
383     fpRunDesc=new AliHLTRunDesc;
384     if (!fpRunDesc) return -ENOMEM;
385     *fpRunDesc=kAliHLTVoidRunDesc;
386   }
387
388   if (fpRunDesc->fRunNo!=kAliHLTVoidRunNo && fpRunDesc->fRunNo!=desc->fRunNo) {
389     HLTWarning("Run description has already been set");
390   }
391   *fpRunDesc=*desc;
392   SetCDBRunNo(fpRunDesc->fRunNo);
393   // TODO: we have to decide about the runType
394   return 0;
395 }
396
397 int AliHLTComponent::SetComponentDescription(const char* desc)
398 {
399   // see header file for function documentation
400   int iResult=0;
401   if (!desc) return 0;
402
403   TString descriptor=desc;
404   TObjArray* pTokens=descriptor.Tokenize(" ");
405   if (pTokens) {
406     for (int i=0; i<pTokens->GetEntriesFast() && iResult>=0; i++) {
407       TString argument=((TObjString*)pTokens->At(i++))->GetString();
408       if (!argument || argument.IsNull()) continue;
409
410       // chainid
411       if (argument.BeginsWith("chainid")) {
412         argument.ReplaceAll("chainid", "");
413         if (argument.BeginsWith("=")) {
414           fChainId=argument.Replace(0,1,"");
415           fChainIdCrc=CalculateChecksum((const AliHLTUInt8_t*)fChainId.c_str(), fChainId.length());
416           HLTDebug("setting component description: chain id %s crc 0x%8x", fChainId.c_str(), fChainIdCrc);
417         } else {
418           fChainId="";
419         }
420       } else {
421         HLTWarning("unknown component description %s", argument.Data());
422       }
423     }
424     delete pTokens;
425   }
426   
427   return iResult;
428 }
429
430 int AliHLTComponent::ConfigureFromArgumentString(int argc, const char** argv)
431 {
432   // see header file for function documentation
433   int iResult=0;
434   vector<const char*> array;
435   TObjArray choppedArguments;
436   TString argument="";
437   int i=0;
438   for (i=0; i<argc && iResult>=0; i++) {
439     argument=argv[i];
440     if (argument.IsWhitespace()) continue;
441
442     // special handling for single component arguments ending with
443     // a sequence of blanks
444     argument.Remove(0, argument.First(' '));
445     if (argument.IsWhitespace()) {
446       array.push_back(argv[i]);
447       continue;
448     }
449
450     // extra blank to insert blank token before leading quotes
451     argument=" ";
452     argument+=argv[i];
453     // insert blank in consecutive quotes to correctly tokenize
454     argument.ReplaceAll("''", "' '");
455     // replace newlines by blanks
456     argument.ReplaceAll("\n", " ");
457     if (argument.IsNull()) continue;
458     TObjArray* pTokensQuote=argument.Tokenize("'");
459     if (pTokensQuote) {
460       if (pTokensQuote->GetEntriesFast()>0) {
461         for (int k=0; k<pTokensQuote->GetEntriesFast(); k++) {
462           argument=((TObjString*)pTokensQuote->At(k))->GetString();
463           if (argument.IsWhitespace()) continue;
464           if (k%2) {
465             // every second entry is enclosed by quotes and thus
466             // one single argument
467             array.push_back(argument.Data());
468           } else {
469     TObjArray* pTokens=argument.Tokenize(" ");
470     if (pTokens) {
471       if (pTokens->GetEntriesFast()>0) {
472         for (int n=0; n<pTokens->GetEntriesFast(); n++) {
473           choppedArguments.AddLast(pTokens->At(n));
474           TString data=((TObjString*)pTokens->At(n))->GetString();
475           if (!data.IsNull()) {
476             array.push_back(data.Data());
477           }
478         }
479         pTokens->SetOwner(kFALSE);
480       }
481       delete pTokens;
482     }
483           }
484         }
485         pTokensQuote->SetOwner(kFALSE);
486       }
487       delete pTokensQuote;
488     }
489   }
490
491   for (i=0; (unsigned)i<array.size() && iResult>=0;) {
492     int result=ScanConfigurationArgument(array.size()-i, &array[i]);
493     if (result==0) {
494       HLTWarning("unknown component argument %s", array[i]);
495       i++;
496     } else if (result>0) {
497       i+=result;
498     } else {
499       iResult=result;
500       if (iResult==-EINVAL) {
501         HLTError("unknown argument %s", array[i]);
502       } else if (iResult==-EPROTO) {
503         HLTError("missing/wrong parameter for argument %s (%s)", array[i], (array.size()>(unsigned)i+1)?array[i+1]:"missing");
504       } else {
505         HLTError("scan of argument %s failed (%d)", array[i], iResult);
506       }
507     }
508   }
509
510   return iResult;
511 }
512
513 int AliHLTComponent::ConfigureFromCDBTObjString(const char* entries, const char* key)
514 {
515   // load a list of OCDB objects and configure from the objects
516   // can either be a TObjString or a TMap with a TObjString:TObjString key-value pair
517   int iResult=0;
518   TString arguments;
519   TString confEntries=entries;
520   TObjArray* pTokens=confEntries.Tokenize(" ");
521   if (pTokens) {
522     for (int n=0; n<pTokens->GetEntriesFast(); n++) {
523       const char* path=((TObjString*)pTokens->At(n))->GetString().Data();
524       const char* chainId=GetChainId();
525       HLTInfo("configure from entry \"%s\"%s%s, chain id %s", path, key?" key ":"",key?key:"", (chainId!=NULL && chainId[0]!=0)?chainId:"<none>");
526       TObject* pOCDBObject = LoadAndExtractOCDBObject(path, key);
527       if (pOCDBObject) {
528         TObjString* pString=dynamic_cast<TObjString*>(pOCDBObject);
529         if (!pString) {
530           TMap* pMap=dynamic_cast<TMap*>(pOCDBObject);
531           if (pMap) {
532             // this is the case where no key has been specified and the OCDB
533             // object is a TMap, search for the default key
534             TObject* pObject=pMap->GetValue("default");
535             if (pObject && (pString=dynamic_cast<TObjString*>(pObject))!=NULL) {
536               HLTInfo("using default key of TMap of configuration object \"%s\"", path);
537             } else {
538               HLTError("no default key available in TMap of configuration object \"%s\"", path);
539               iResult=-ENOENT;
540               break;
541             }
542           }
543         }
544
545         if (pString) {
546           HLTInfo("received configuration object string: \'%s\'", pString->GetString().Data());
547           arguments+=pString->GetString().Data();
548           arguments+=" ";
549         } else {
550           HLTError("configuration object \"%s\"%s%s has wrong type, required TObjString", path, key?" key ":"",key?key:"");
551           iResult=-EINVAL;
552         }
553       } else {
554         HLTError("can not fetch object \"%s\" from OCDB", path);
555         iResult=-ENOENT;
556       }
557     }
558     delete pTokens;
559   }
560   if (iResult>=0 && !arguments.IsNull())  {
561     const char* array=arguments.Data();
562     iResult=ConfigureFromArgumentString(1, &array);
563   }
564   return iResult;
565 }
566
567 TObject* AliHLTComponent::LoadAndExtractOCDBObject(const char* path, int version, int subVersion, const char* key)
568 {
569   // see header file for function documentation
570   AliCDBEntry* pEntry=AliHLTMisc::Instance().LoadOCDBEntry(path, GetRunNo(), version, subVersion);
571   if (!pEntry) return NULL;
572   TObject* pObject=AliHLTMisc::Instance().ExtractObject(pEntry);
573   TMap* pMap=dynamic_cast<TMap*>(pObject);
574   if (pMap && key) {
575     pObject=pMap->GetValue(key);
576     if (!pObject) {
577       pObject=pMap->GetValue("default");
578       if (pObject) {
579         HLTWarning("can not find object for key \"%s\" in TMap of configuration object \"%s\", using key \"default\"", key, path);
580       }
581     }
582     if (!pObject) {
583       HLTError("can not find object for key \"%s\" in TMap of configuration object \"%s\"", key, path);
584       return NULL;
585     }
586   }
587   return pObject;
588 }
589
590 int AliHLTComponent::DoInit( int /*argc*/, const char** /*argv*/)
591 {
592   // default implementation, childs can overload
593   HLTLogKeyword("dummy");
594   return 0;
595 }
596
597 int AliHLTComponent::DoDeinit()
598 {
599   // default implementation, childs can overload
600   HLTLogKeyword("dummy");
601   return 0;
602 }
603
604 int AliHLTComponent::Reconfigure(const char* /*cdbEntry*/, const char* /*chainId*/)
605 {
606   // default implementation, childs can overload
607   HLTLogKeyword("dummy");
608   return 0;
609 }
610
611 int AliHLTComponent::ReadPreprocessorValues(const char* /*modules*/)
612 {
613   // default implementation, childs can overload
614   HLTLogKeyword("dummy");
615   return 0;
616 }
617
618 int AliHLTComponent::ScanConfigurationArgument(int /*argc*/, const char** /*argv*/)
619 {
620   // default implementation, childs can overload
621   HLTLogKeyword("dummy");
622   HLTWarning("The function needs to be implemented by the component");
623   return 0;
624 }
625
626 int AliHLTComponent::StartOfRun()
627 {
628   // default implementation, childs can overload
629   HLTLogKeyword("dummy");
630   return 0;
631 }
632
633 int AliHLTComponent::EndOfRun()
634 {
635   // default implementation, childs can overload
636   HLTLogKeyword("dummy");
637   return 0;
638 }
639
640
641 int AliHLTComponent::GetOutputDataTypes(AliHLTComponentDataTypeList& /*tgtList*/)
642 {
643   // default implementation, childs can overload
644   HLTLogKeyword("dummy");
645   return 0;
646 }
647
648 void AliHLTComponent::GetOCDBObjectDescription( TMap* const /*targetArray*/)
649 {
650   // default implementation, childs can overload
651   HLTLogKeyword("dummy");
652 }
653
654 int AliHLTComponent::CheckOCDBEntries(const TMap* const externList)
655 {
656   // check the availability of the OCDB entry descriptions in the TMap
657   //  key : complete OCDB path of the entry
658   //  value : auxiliary object - short description
659   // if the external map was not provided the function invokes
660   // interface function GetOCDBObjectDescription() to retrieve the list.
661   int iResult=0;
662   if (externList) {
663     iResult=AliHLTMisc::Instance().CheckOCDBEntries(externList);
664   } else {
665     TMap* pMap=new TMap;
666     if (pMap) {
667       pMap->SetOwnerKeyValue(kTRUE);
668       GetOCDBObjectDescription(pMap);
669       iResult=AliHLTMisc::Instance().CheckOCDBEntries(pMap);
670       delete pMap;
671       pMap=NULL;
672     }
673   }
674
675   return iResult;
676 }
677
678 void AliHLTComponent::DataType2Text( const AliHLTComponentDataType& type, char output[kAliHLTComponentDataTypefIDsize+kAliHLTComponentDataTypefOriginSize+2] ) const
679 {
680   // see header file for function documentation
681   memset( output, 0, kAliHLTComponentDataTypefIDsize+kAliHLTComponentDataTypefOriginSize+2 );
682   strncat( output, type.fOrigin, kAliHLTComponentDataTypefOriginSize );
683   strcat( output, ":" );
684   strncat( output, type.fID, kAliHLTComponentDataTypefIDsize );
685 }
686
687 string AliHLTComponent::DataType2Text( const AliHLTComponentDataType& type, int mode)
688 {
689   // see header file for function documentation
690   string out("");
691
692   // 'typeid' 'origin'
693   // aligned to 8 and 4 chars respectively, blocks enclosed in quotes and
694   // separated by blank e.g.
695   // 'DDL_RAW ' 'TPC '
696   if (mode==3) {
697     int i=0;
698     char tmp[8];
699     out+="'";
700     for (i=0; i<kAliHLTComponentDataTypefIDsize; i++) {
701       unsigned char* puc=(unsigned char*)type.fID;
702       if (puc[i]<32)
703         sprintf(tmp, "\\%x", type.fID[i]);
704       else
705         sprintf(tmp, "%c", type.fID[i]);
706       out+=tmp;
707     }
708     out+="' '";
709     for (i=0; i<kAliHLTComponentDataTypefOriginSize; i++) {
710       unsigned char* puc=(unsigned char*)type.fOrigin;
711       if ((puc[i])<32)
712         sprintf(tmp, "\\%x", type.fOrigin[i]);
713       else
714         sprintf(tmp, "%c", type.fOrigin[i]);
715       out+=tmp;
716     }
717     out+="'";
718     return out;
719   }
720
721   // origin typeid as numbers separated by colon e.g.
722   // aligned to 8 and 4 chars respectively, all characters separated by
723   // quotes, e.g.
724   // '84'80'67'32':'68'68'76'95'82'65'87'32'
725   if (mode==2) {
726     int i=0;
727     char tmp[8];
728     for (i=0; i<kAliHLTComponentDataTypefOriginSize; i++) {
729       sprintf(tmp, "'%d", type.fOrigin[i]);
730       out+=tmp;
731     }
732     out+="':'";
733     for (i=0; i<kAliHLTComponentDataTypefIDsize; i++) {
734       sprintf(tmp, "%d'", type.fID[i]);
735       out+=tmp;
736     }
737     return out;
738   }
739
740   // origin typeid separated by colon e.g.
741   // aligned to 8 and 4 chars respectively, all characters separated by
742   // quotes, e.g.
743   // 'T'P'C' ':'D'D'L'_'R'A'W' '
744   if (mode==1) {
745     int i=0;
746     char tmp[8];
747     for (i=0; i<kAliHLTComponentDataTypefOriginSize; i++) {
748       unsigned char* puc=(unsigned char*)type.fOrigin;
749       if ((puc[i])<32)
750         sprintf(tmp, "'\\%x", type.fOrigin[i]);
751       else
752         sprintf(tmp, "'%c", type.fOrigin[i]);
753       out+=tmp;
754     }
755     out+="':'";
756     for (i=0; i<kAliHLTComponentDataTypefIDsize; i++) {
757       unsigned char* puc=(unsigned char*)type.fID;
758       if (puc[i]<32)
759         sprintf(tmp, "\\%x'", type.fID[i]);
760       else
761         sprintf(tmp, "%c'", type.fID[i]);
762       out+=tmp;
763     }
764     return out;
765   }
766
767   // origin typeid
768   // aligned to 8 and 4 chars respectively, separated by colon e.g.
769   // TPC :DDL_RAW 
770   if (type==kAliHLTVoidDataType) {
771     out="VOID:VOID";
772   } else {
773     // some gymnastics in order to avoid a '0' which is part of either or both
774     // ID and origin terminating the whole string. Unfortunately, string doesn't
775     // stop appending at the '0' if the number of elements to append was 
776     // explicitely specified
777     string tmp("");
778     tmp.append(type.fOrigin, kAliHLTComponentDataTypefOriginSize);
779     out.append(tmp.c_str());
780     out.append(":");
781     tmp="";
782     tmp.append(type.fID, kAliHLTComponentDataTypefIDsize);
783     out.append(tmp.c_str());
784   }
785   return out;
786 }
787
788
789 void* AliHLTComponent::AllocMemory( unsigned long size ) 
790 {
791   // see header file for function documentation
792   if (fEnvironment.fAllocMemoryFunc)
793     return (*fEnvironment.fAllocMemoryFunc)(fEnvironment.fParam, size );
794   HLTFatal("no memory allocation handler registered");
795   return NULL;
796 }
797
798 int AliHLTComponent::MakeOutputDataBlockList( const AliHLTComponentBlockDataList& blocks, AliHLTUInt32_t* blockCount,
799                                               AliHLTComponentBlockData** outputBlocks ) 
800 {
801   // see header file for function documentation
802     if ( blockCount==NULL || outputBlocks==NULL )
803         return -EFAULT;
804     AliHLTUInt32_t count = blocks.size();
805     if ( !count )
806         {
807         *blockCount = 0;
808         *outputBlocks = NULL;
809         return 0;
810         }
811     *outputBlocks = reinterpret_cast<AliHLTComponentBlockData*>( AllocMemory( sizeof(AliHLTComponentBlockData)*count ) );
812     if ( !*outputBlocks )
813         return -ENOMEM;
814     for ( unsigned long i = 0; i < count; i++ ) {
815         (*outputBlocks)[i] = blocks[i];
816         if (MatchExactly(blocks[i].fDataType, kAliHLTAnyDataType)) {
817           (*outputBlocks)[i].fDataType=GetOutputDataType();
818           /* data type was set to the output data type by the PubSub AliRoot
819              Wrapper component, if data type of the block was ********:****.
820              Now handled by the component base class in order to have same
821              behavior when running embedded in AliRoot
822           memset((*outputBlocks)[i].fDataType.fID, '*', kAliHLTComponentDataTypefIDsize);
823           memset((*outputBlocks)[i].fDataType.fOrigin, '*', kAliHLTComponentDataTypefOriginSize);
824           */
825         }
826     }
827     *blockCount = count;
828     return 0;
829
830 }
831
832 int AliHLTComponent::GetEventDoneData( unsigned long size, AliHLTComponentEventDoneData** edd ) const
833 {
834   // see header file for function documentation
835   if (fEnvironment.fGetEventDoneDataFunc)
836     return (*fEnvironment.fGetEventDoneDataFunc)(fEnvironment.fParam, fCurrentEvent, size, edd );
837   return -ENOSYS;
838 }
839
840 int AliHLTComponent::ReserveEventDoneData( unsigned long size )
841 {
842   // see header file for function documentation
843   int iResult=0;
844
845   unsigned long capacity=fEventDoneDataSize;
846   if (fEventDoneData) capacity-=sizeof(AliHLTComponentEventDoneData)+fEventDoneData->fDataSize;
847   if (size>capacity) {
848     unsigned long newSize=sizeof(AliHLTComponentEventDoneData)+size+(fEventDoneDataSize-capacity);
849     AliHLTComponentEventDoneData* newEDD = reinterpret_cast<AliHLTComponentEventDoneData*>( new AliHLTUInt8_t[newSize] );
850     if (!newEDD)
851       return -ENOMEM;
852     newEDD->fStructSize = sizeof(AliHLTComponentEventDoneData);
853     newEDD->fDataSize = 0;
854     newEDD->fData = reinterpret_cast<AliHLTUInt8_t*>(newEDD)+newEDD->fStructSize;
855     if (fEventDoneData) {
856       memcpy( newEDD->fData, fEventDoneData->fData, fEventDoneData->fDataSize );
857       newEDD->fDataSize = fEventDoneData->fDataSize;
858       delete [] reinterpret_cast<AliHLTUInt8_t*>( fEventDoneData );
859     }
860     fEventDoneData = newEDD;
861     fEventDoneDataSize = newSize;
862   }
863   return iResult;
864
865 }
866
867 int AliHLTComponent::PushEventDoneData( AliHLTUInt32_t eddDataWord )
868 {
869   // see header file for function documentation
870   if (!fEventDoneData)
871     return -ENOMEM;
872   if (fEventDoneData->fDataSize+sizeof(AliHLTUInt32_t)>fEventDoneDataSize)
873     return -ENOSPC;
874   *reinterpret_cast<AliHLTUInt32_t*>((reinterpret_cast<AliHLTUInt8_t*>(fEventDoneData->fData)+fEventDoneData->fDataSize)) = eddDataWord;
875   fEventDoneData->fDataSize += sizeof(AliHLTUInt32_t);
876   return 0;
877 }
878
879 void AliHLTComponent::ReleaseEventDoneData()
880 {
881    // see header file for function documentation
882  if (fEventDoneData)
883     delete [] reinterpret_cast<AliHLTUInt8_t*>( fEventDoneData );
884   fEventDoneData = NULL;
885   fEventDoneDataSize = 0;
886 }
887
888
889 int AliHLTComponent::FindMatchingDataTypes(AliHLTComponent* pConsumer, AliHLTComponentDataTypeList* tgtList) 
890 {
891   // see header file for function documentation
892   int iResult=0;
893   if (pConsumer) {
894     AliHLTComponentDataTypeList itypes;
895     AliHLTComponentDataTypeList otypes;
896     otypes.push_back(GetOutputDataType());
897     if (MatchExactly(otypes[0],kAliHLTMultipleDataType)) {
898       otypes.clear();
899       int count=0;
900       if ((count=GetOutputDataTypes(otypes))>0) {
901       } else if (GetComponentType()!=kSink) {
902         HLTWarning("component %s indicates multiple output data types but GetOutputDataTypes returns %d", GetComponentID(), count);
903       }
904     }
905     pConsumer->GetInputDataTypes(itypes);
906     AliHLTComponentDataTypeList::iterator otype=otypes.begin();
907     for (;otype!=otypes.end();otype++) {
908       //PrintDataTypeContent((*otype), "publisher \'%s\'");
909       if ((*otype)==(kAliHLTAnyDataType|kAliHLTDataOriginPrivate)) {
910         if (tgtList) tgtList->push_back(*otype);
911         iResult++;
912         continue;
913       }
914       
915       AliHLTComponentDataTypeList::iterator itype=itypes.begin();
916       for ( ; itype!=itypes.end() && (*itype)!=(*otype) ; itype++) {/* empty body */};
917       //if (itype!=itypes.end()) PrintDataTypeContent(*itype, "consumer \'%s\'");
918       if (itype!=itypes.end()) {
919         if (tgtList) tgtList->push_back(*otype);
920         iResult++;
921       }
922     }
923   } else {
924     iResult=-EINVAL;
925   }
926   return iResult;
927 }
928
929 void AliHLTComponent::PrintDataTypeContent(AliHLTComponentDataType& dt, const char* format)
930 {
931   // see header file for function documentation
932   const char* fmt="\'%s\'";
933   if (format) fmt=format;
934   AliHLTLogging::Message(NULL, kHLTLogNone, NULL , NULL, Form(fmt, (DataType2Text(dt)).c_str()));
935   AliHLTLogging::Message(NULL, kHLTLogNone, NULL , NULL, 
936                          Form("%x %x %x %x %x %x %x %x : %x %x %x %x", 
937                               dt.fID[0],
938                               dt.fID[1],
939                               dt.fID[2],
940                               dt.fID[3],
941                               dt.fID[4],
942                               dt.fID[5],
943                               dt.fID[6],
944                               dt.fID[7],
945                               dt.fOrigin[0],
946                               dt.fOrigin[1],
947                               dt.fOrigin[2],
948                               dt.fOrigin[3]));
949 }
950
951 void AliHLTComponent::FillBlockData( AliHLTComponentBlockData& blockData )
952 {
953   // see header file for function documentation
954   blockData.fStructSize = sizeof(blockData);
955   FillShmData( blockData.fShmKey );
956   blockData.fOffset = ~(AliHLTUInt32_t)0;
957   blockData.fPtr = NULL;
958   blockData.fSize = 0;
959   FillDataType( blockData.fDataType );
960   blockData.fSpecification = kAliHLTVoidDataSpec;
961 }
962
963 void AliHLTComponent::FillShmData( AliHLTComponentShmData& shmData )
964 {
965   // see header file for function documentation
966   shmData.fStructSize = sizeof(shmData);
967   shmData.fShmType = gkAliHLTComponentInvalidShmType;
968   shmData.fShmID = gkAliHLTComponentInvalidShmID;
969 }
970
971 void AliHLTComponent::FillDataType( AliHLTComponentDataType& dataType )
972 {
973   // see header file for function documentation
974   dataType=kAliHLTAnyDataType;
975 }
976
977 void AliHLTComponent::CopyDataType(AliHLTComponentDataType& tgtdt, const AliHLTComponentDataType& srcdt) 
978 {
979   // see header file for function documentation
980   memcpy(&tgtdt.fID[0], &srcdt.fID[0], kAliHLTComponentDataTypefIDsize);
981   memcpy(&tgtdt.fOrigin[0], &srcdt.fOrigin[0], kAliHLTComponentDataTypefOriginSize);
982 }
983
984 void AliHLTComponent::SetDataType(AliHLTComponentDataType& tgtdt, const char* id, const char* origin) 
985 {
986   // see header file for function documentation
987   tgtdt.fStructSize=sizeof(AliHLTComponentDataType);
988   if (id) {
989     memset(&tgtdt.fID[0], 0, kAliHLTComponentDataTypefIDsize);
990     strncpy(&tgtdt.fID[0], id, strlen(id)<(size_t)kAliHLTComponentDataTypefIDsize?strlen(id):kAliHLTComponentDataTypefIDsize);
991   }
992   if (origin) {
993     memset(&tgtdt.fOrigin[0], 0, kAliHLTComponentDataTypefOriginSize);
994     strncpy(&tgtdt.fOrigin[0], origin, strlen(origin)<(size_t)kAliHLTComponentDataTypefOriginSize?strlen(origin):kAliHLTComponentDataTypefOriginSize);
995   }
996 }
997
998 void AliHLTComponent::SetDataType(AliHLTComponentDataType& dt, AliHLTUInt64_t id, AliHLTUInt32_t origin)
999 {
1000   // see header file for function documentation
1001   dt.fStructSize=sizeof(AliHLTComponentDataType);
1002   assert(kAliHLTComponentDataTypefIDsize==sizeof(id));
1003   assert(kAliHLTComponentDataTypefOriginSize==sizeof(origin));
1004   memcpy(&dt.fID, &id, kAliHLTComponentDataTypefIDsize);
1005   memcpy(&dt.fOrigin, &origin, kAliHLTComponentDataTypefOriginSize);
1006 }
1007
1008 void AliHLTComponent::FillEventData(AliHLTComponentEventData& evtData)
1009 {
1010   // see header file for function documentation
1011   memset(&evtData, 0, sizeof(AliHLTComponentEventData));
1012   evtData.fStructSize=sizeof(AliHLTComponentEventData);
1013   evtData.fEventID=kAliHLTVoidEventID;
1014 }
1015
1016 void AliHLTComponent::PrintComponentDataTypeInfo(const AliHLTComponentDataType& dt) 
1017 {
1018   // see header file for function documentation
1019   TString msg;
1020   msg.Form("AliHLTComponentDataType(%d): ID=\"", dt.fStructSize);
1021   for ( int i = 0; i < kAliHLTComponentDataTypefIDsize; i++ ) {
1022    if (dt.fID[i]!=0) msg+=dt.fID[i];
1023    else msg+="\\0";
1024   }
1025   msg+="\" Origin=\"";
1026   for ( int i = 0; i < kAliHLTComponentDataTypefOriginSize; i++ ) {
1027    if (dt.fOrigin[i]!=0) msg+=dt.fOrigin[i];
1028    else msg+="\\0";
1029   }
1030   msg+="\"";
1031   AliHLTLogging::Message(NULL, kHLTLogNone, NULL , NULL, msg.Data());
1032 }
1033
1034 int AliHLTComponent::GetEventCount() const
1035 {
1036   // see header file for function documentation
1037   return fEventCount;
1038 }
1039
1040 int AliHLTComponent::IncrementEventCounter()
1041 {
1042   // see header file for function documentation
1043   if (fEventCount>=0) fEventCount++;
1044   return fEventCount;
1045 }
1046
1047 int AliHLTComponent::GetNumberOfInputBlocks() const
1048 {
1049   // see header file for function documentation
1050   if (fpInputBlocks!=NULL) {
1051     return fCurrentEventData.fBlockCnt;
1052   }
1053   return 0;
1054 }
1055
1056 AliHLTEventID_t AliHLTComponent::GetEventId() const
1057 {
1058   // see header file for function documentation
1059   if (fpInputBlocks!=NULL) {
1060     return fCurrentEventData.fEventID;
1061   }
1062   return 0;
1063 }
1064
1065 const TObject* AliHLTComponent::GetFirstInputObject(const AliHLTComponentDataType& dt,
1066                                                     const char* classname,
1067                                                     int bForce)
1068 {
1069   // see header file for function documentation
1070   ALIHLTCOMPONENT_BASE_STOPWATCH();
1071   fSearchDataType=dt;
1072   if (classname) fClassName=classname;
1073   else fClassName.clear();
1074   int idx=FindInputBlock(fSearchDataType, 0, 1);
1075   TObject* pObj=NULL;
1076   if (idx>=0) {
1077     HLTDebug("found block %d when searching for data type %s", idx, DataType2Text(dt).c_str());
1078     if ((pObj=GetInputObject(idx, fClassName.c_str(), bForce))!=NULL) {
1079       fCurrentInputBlock=idx;
1080     } else {
1081     }
1082   }
1083   return pObj;
1084 }
1085
1086 const TObject* AliHLTComponent::GetFirstInputObject(const char* dtID, 
1087                                                     const char* dtOrigin,
1088                                                     const char* classname,
1089                                                     int         bForce)
1090 {
1091   // see header file for function documentation
1092   ALIHLTCOMPONENT_BASE_STOPWATCH();
1093   AliHLTComponentDataType dt;
1094   SetDataType(dt, dtID, dtOrigin);
1095   return GetFirstInputObject(dt, classname, bForce);
1096 }
1097
1098 const TObject* AliHLTComponent::GetNextInputObject(int bForce)
1099 {
1100   // see header file for function documentation
1101   ALIHLTCOMPONENT_BASE_STOPWATCH();
1102   int idx=FindInputBlock(fSearchDataType, fCurrentInputBlock+1, 1);
1103   //HLTDebug("found block %d when searching for data type %s", idx, DataType2Text(fSearchDataType).c_str());
1104   TObject* pObj=NULL;
1105   if (idx>=0) {
1106     if ((pObj=GetInputObject(idx, fClassName.c_str(), bForce))!=NULL) {
1107       fCurrentInputBlock=idx;
1108     }
1109   }
1110   return pObj;
1111 }
1112
1113 int AliHLTComponent::FindInputBlock(const AliHLTComponentDataType& dt, int startIdx, int bObject) const
1114 {
1115   // see header file for function documentation
1116   int iResult=-ENOENT;
1117   if (fpInputBlocks!=NULL) {
1118     int idx=startIdx<0?0:startIdx;
1119     for ( ; (UInt_t)idx<fCurrentEventData.fBlockCnt && iResult==-ENOENT; idx++) {
1120       if (dt!=fpInputBlocks[idx].fDataType) continue;
1121
1122       if (bObject!=0) {
1123         if (fpInputBlocks[idx].fPtr==NULL) continue;
1124         AliHLTUInt32_t firstWord=*((AliHLTUInt32_t*)fpInputBlocks[idx].fPtr);
1125         if (firstWord!=fpInputBlocks[idx].fSize-sizeof(AliHLTUInt32_t)) continue;
1126       }
1127       iResult=idx;
1128     }
1129   }
1130   return iResult;
1131 }
1132
1133 TObject* AliHLTComponent::CreateInputObject(int idx, int bForce)
1134 {
1135   // see header file for function documentation
1136   TObject* pObj=NULL;
1137   if (fpInputBlocks!=NULL) {
1138     if ((UInt_t)idx<fCurrentEventData.fBlockCnt) {
1139       if (fpInputBlocks[idx].fPtr) {
1140         AliHLTUInt32_t firstWord=*((AliHLTUInt32_t*)fpInputBlocks[idx].fPtr);
1141         if (firstWord==fpInputBlocks[idx].fSize-sizeof(AliHLTUInt32_t)) {
1142           HLTDebug("create object from block %d size %d", idx, fpInputBlocks[idx].fSize);
1143           AliHLTMessage msg(fpInputBlocks[idx].fPtr, fpInputBlocks[idx].fSize);
1144           TClass* objclass=msg.GetClass();
1145           pObj=msg.ReadObject(objclass);
1146           if (pObj && objclass) {
1147             HLTDebug("object %p type %s created", pObj, objclass->GetName());
1148           } else {
1149           }
1150           //} else {
1151         } else if (bForce!=0) {
1152           HLTError("size mismatch: block size %d, indicated %d", fpInputBlocks[idx].fSize, firstWord+sizeof(AliHLTUInt32_t));
1153         }
1154       } else {
1155         HLTFatal("block descriptor empty");
1156       }
1157     } else {
1158       HLTError("index %d out of range %d", idx, fCurrentEventData.fBlockCnt);
1159     }
1160   } else {
1161     HLTError("no input blocks available");
1162   }
1163   
1164   return pObj;
1165 }
1166
1167 TObject* AliHLTComponent::GetInputObject(int idx, const char* /*classname*/, int bForce)
1168 {
1169   // see header file for function documentation
1170   if (fpInputObjects==NULL) {
1171     fpInputObjects=new TObjArray(fCurrentEventData.fBlockCnt);
1172   }
1173   TObject* pObj=NULL;
1174   if (fpInputObjects) {
1175     pObj=fpInputObjects->At(idx);
1176     if (pObj==NULL) {
1177       pObj=CreateInputObject(idx, bForce);
1178       if (pObj) {
1179         fpInputObjects->AddAt(pObj, idx);
1180       }
1181     }
1182   } else {
1183     HLTFatal("memory allocation failed: TObjArray of size %d", fCurrentEventData.fBlockCnt);
1184   }
1185   return pObj;
1186 }
1187
1188 int AliHLTComponent::CleanupInputObjects()
1189 {
1190   // see header file for function documentation
1191   if (!fpInputObjects) return 0;
1192   TObjArray* array=fpInputObjects;
1193   fpInputObjects=NULL;
1194   for (int i=0; i<array->GetEntriesFast(); i++) {
1195     TObject* pObj=array->At(i);
1196     // grrr, garbage collection strikes back: When read via AliHLTMessage
1197     // (CreateInputObject), and written to a TFile afterwards, the
1198     // TFile::Close calls ROOOT's garbage collection. No clue why the
1199     // object ended up in the key list and needs to be deleted
1200     //
1201     // Matthias 09.11.2008 follow up
1202     // This approach doesn't actually work in all cases: the object table
1203     // can be switched off globally, the flag needs to be checked here as
1204     // well in order to avoid memory leaks.
1205     // This means we have to find another solution for the problem if it
1206     // pops up again.
1207     if (pObj &&
1208         (!TObject::GetObjectStat() || gObjectTable->PtrIsValid(pObj))) {
1209       delete pObj;
1210     }
1211   }
1212   delete array;
1213   return 0;
1214 }
1215
1216 AliHLTComponentDataType AliHLTComponent::GetDataType(const TObject* pObject)
1217 {
1218   // see header file for function documentation
1219   ALIHLTCOMPONENT_BASE_STOPWATCH();
1220   AliHLTComponentDataType dt=kAliHLTVoidDataType;
1221   int idx=fCurrentInputBlock;
1222   if (pObject) {
1223     if (fpInputObjects==NULL || (idx=fpInputObjects->IndexOf(pObject))>=0) {
1224     } else {
1225       HLTError("unknown object %p", pObject);
1226     }
1227   }
1228   if (idx>=0) {
1229     if ((UInt_t)idx<fCurrentEventData.fBlockCnt) {
1230       dt=fpInputBlocks[idx].fDataType;
1231     } else {
1232       HLTFatal("severe internal error, index out of range");
1233     }
1234   }
1235   return dt;
1236 }
1237
1238 AliHLTUInt32_t AliHLTComponent::GetSpecification(const TObject* pObject)
1239 {
1240   // see header file for function documentation
1241   ALIHLTCOMPONENT_BASE_STOPWATCH();
1242   AliHLTUInt32_t iSpec=kAliHLTVoidDataSpec;
1243   int idx=fCurrentInputBlock;
1244   if (pObject) {
1245     if (fpInputObjects==NULL || (idx=fpInputObjects->IndexOf(pObject))>=0) {
1246     } else {
1247       HLTError("unknown object %p", pObject);
1248     }
1249   }
1250   if (idx>=0) {
1251     if ((UInt_t)idx<fCurrentEventData.fBlockCnt) {
1252       iSpec=fpInputBlocks[idx].fSpecification;
1253     } else {
1254       HLTFatal("severe internal error, index out of range");
1255     }
1256   }
1257   return iSpec;
1258 }
1259
1260 int AliHLTComponent::Forward(const TObject* pObject)
1261 {
1262   // see header file for function documentation
1263   int iResult=0;
1264   int idx=fCurrentInputBlock;
1265   if (pObject) {
1266     if (fpInputObjects==NULL || (idx=fpInputObjects->IndexOf(pObject))>=0) {
1267     } else {
1268       HLTError("unknown object %p", pObject);
1269       iResult=-ENOENT;
1270     }
1271   }
1272   if (idx>=0) {
1273     fOutputBlocks.push_back(fpInputBlocks[idx]);
1274   }
1275   return iResult;
1276 }
1277
1278 int AliHLTComponent::Forward(const AliHLTComponentBlockData* pBlock)
1279 {
1280   // see header file for function documentation
1281   int iResult=0;
1282   int idx=fCurrentInputBlock;
1283   if (pBlock) {
1284     if ((idx=FindInputBlock(pBlock))>=0) {
1285     } else {
1286       HLTError("unknown Block %p", pBlock);
1287       iResult=-ENOENT;      
1288     }
1289   }
1290   if (idx>=0) {
1291     // check for fpInputBlocks pointer done in FindInputBlock
1292     fOutputBlocks.push_back(fpInputBlocks[idx]);
1293   }
1294   return iResult;
1295 }
1296
1297 const AliHLTComponentBlockData* AliHLTComponent::GetFirstInputBlock(const AliHLTComponentDataType& dt)
1298 {
1299   // see header file for function documentation
1300   ALIHLTCOMPONENT_BASE_STOPWATCH();
1301   fSearchDataType=dt;
1302   fClassName.clear();
1303   int idx=FindInputBlock(fSearchDataType, 0);
1304   const AliHLTComponentBlockData* pBlock=NULL;
1305   if (idx>=0) {
1306     // check for fpInputBlocks pointer done in FindInputBlock
1307     pBlock=&fpInputBlocks[idx];
1308     fCurrentInputBlock=idx;
1309   }
1310   return pBlock;
1311 }
1312
1313 const AliHLTComponentBlockData* AliHLTComponent::GetFirstInputBlock(const char* dtID, 
1314                                                                     const char* dtOrigin)
1315 {
1316   // see header file for function documentation
1317   ALIHLTCOMPONENT_BASE_STOPWATCH();
1318   AliHLTComponentDataType dt;
1319   SetDataType(dt, dtID, dtOrigin);
1320   return GetFirstInputBlock(dt);
1321 }
1322
1323 const AliHLTComponentBlockData* AliHLTComponent::GetInputBlock(int index) const
1324 {
1325   // see header file for function documentation
1326   ALIHLTCOMPONENT_BASE_STOPWATCH();
1327   assert( 0 <= index and index < (int)fCurrentEventData.fBlockCnt );
1328   return &fpInputBlocks[index];
1329 }
1330
1331 const AliHLTComponentBlockData* AliHLTComponent::GetNextInputBlock()
1332 {
1333   // see header file for function documentation
1334   ALIHLTCOMPONENT_BASE_STOPWATCH();
1335   int idx=FindInputBlock(fSearchDataType, fCurrentInputBlock+1);
1336   const AliHLTComponentBlockData* pBlock=NULL;
1337   if (idx>=0) {
1338     // check for fpInputBlocks pointer done in FindInputBlock
1339     pBlock=&fpInputBlocks[idx];
1340     fCurrentInputBlock=idx;
1341   }
1342   return pBlock;
1343 }
1344
1345 int AliHLTComponent::FindInputBlock(const AliHLTComponentBlockData* pBlock) const
1346 {
1347   // see header file for function documentation
1348   int iResult=-ENOENT;
1349   if (fpInputBlocks!=NULL) {
1350     if (pBlock) {
1351       if (pBlock>=fpInputBlocks && pBlock<fpInputBlocks+fCurrentEventData.fBlockCnt) {
1352         iResult=(int)(pBlock-fpInputBlocks);
1353       }
1354     } else {
1355       iResult=-EINVAL;
1356     }
1357   }
1358   return iResult;
1359 }
1360
1361 AliHLTUInt32_t AliHLTComponent::GetSpecification(const AliHLTComponentBlockData* pBlock)
1362 {
1363   // see header file for function documentation
1364   ALIHLTCOMPONENT_BASE_STOPWATCH();
1365   AliHLTUInt32_t iSpec=kAliHLTVoidDataSpec;
1366   int idx=fCurrentInputBlock;
1367   if (pBlock) {
1368     if (fpInputObjects==NULL || (idx=FindInputBlock(pBlock))>=0) {
1369     } else {
1370       HLTError("unknown Block %p", pBlock);
1371     }
1372   }
1373   if (idx>=0) {
1374     // check for fpInputBlocks pointer done in FindInputBlock
1375     iSpec=fpInputBlocks[idx].fSpecification;
1376   }
1377   return iSpec;
1378 }
1379
1380 int AliHLTComponent::PushBack(TObject* pObject, const AliHLTComponentDataType& dt, AliHLTUInt32_t spec, 
1381                               void* pHeader, int headerSize)
1382 {
1383   // see header file for function documentation
1384   ALIHLTCOMPONENT_BASE_STOPWATCH();
1385   int iResult=0;
1386   fLastObjectSize=0;
1387   if (fPushbackPeriod>0) {
1388     // suppress the output
1389     TDatime time;
1390     if (fLastPushBackTime<0 || (int)time.Get()-fLastPushBackTime<fPushbackPeriod) return 0;
1391   }
1392   if (pObject) {
1393     AliHLTMessage msg(kMESS_OBJECT);
1394     msg.SetCompressionLevel(fCompressionLevel);
1395     msg.WriteObject(pObject);
1396     Int_t iMsgLength=msg.Length();
1397     if (iMsgLength>0) {
1398       // Matthias Sep 2008
1399       // NOTE: AliHLTMessage does implement it's own SetLength method
1400       // which is not architecture independent. The original SetLength
1401       // stores the size always in network byte order.
1402       // I'm trying to remember the rational for that, might be that
1403       // it was just some lack of knowledge. Want to change this, but
1404       // has to be done carefullt to be backward compatible.
1405       msg.SetLength(); // sets the length to the first (reserved) word
1406
1407       // does nothing if the level is 0
1408       msg.Compress();
1409
1410       char *mbuf = msg.Buffer();
1411       if (msg.CompBuffer()) {
1412         msg.SetLength(); // set once more to have to byte order
1413         mbuf = msg.CompBuffer();
1414         iMsgLength = msg.CompLength();
1415       }
1416       assert(mbuf!=NULL);
1417       iResult=InsertOutputBlock(mbuf, iMsgLength, dt, spec, pHeader, headerSize);
1418       if (iResult>=0) {
1419         HLTDebug("object %s (%p) size %d compression %d inserted to output", pObject->ClassName(), pObject, iMsgLength, msg.GetCompressionLevel());
1420       }
1421       fLastObjectSize=iMsgLength;
1422     } else {
1423       HLTError("object serialization failed for object %p", pObject);
1424       iResult=-ENOMSG;
1425     }
1426   } else {
1427     iResult=-EINVAL;
1428   }
1429   return iResult;
1430 }
1431
1432 int AliHLTComponent::PushBack(TObject* pObject, const char* dtID, const char* dtOrigin, AliHLTUInt32_t spec,
1433                               void* pHeader, int headerSize)
1434 {
1435   // see header file for function documentation
1436   ALIHLTCOMPONENT_BASE_STOPWATCH();
1437   AliHLTComponentDataType dt;
1438   SetDataType(dt, dtID, dtOrigin);
1439   return PushBack(pObject, dt, spec, pHeader, headerSize);
1440 }
1441
1442 int AliHLTComponent::PushBack(const void* pBuffer, int iSize, const AliHLTComponentDataType& dt, AliHLTUInt32_t spec,
1443                               const void* pHeader, int headerSize)
1444 {
1445   // see header file for function documentation
1446   ALIHLTCOMPONENT_BASE_STOPWATCH();
1447   if (fPushbackPeriod>0) {
1448     // suppress the output
1449     TDatime time;
1450     if (fLastPushBackTime<0 || (int)time.Get()-fLastPushBackTime<fPushbackPeriod) return 0;
1451   }
1452
1453   return InsertOutputBlock(pBuffer, iSize, dt, spec, pHeader, headerSize);
1454 }
1455
1456 int AliHLTComponent::PushBack(const void* pBuffer, int iSize, const char* dtID, const char* dtOrigin, AliHLTUInt32_t spec,
1457                               const void* pHeader, int headerSize)
1458 {
1459   // see header file for function documentation
1460   ALIHLTCOMPONENT_BASE_STOPWATCH();
1461   AliHLTComponentDataType dt;
1462   SetDataType(dt, dtID, dtOrigin);
1463   return PushBack(pBuffer, iSize, dt, spec, pHeader, headerSize);
1464 }
1465
1466 int AliHLTComponent::InsertOutputBlock(const void* pBuffer, int iBufferSize, const AliHLTComponentDataType& dt, AliHLTUInt32_t spec,
1467                                        const void* pHeader, int iHeaderSize)
1468 {
1469   // see header file for function documentation
1470   int iResult=0;
1471   int iBlkSize = iBufferSize + iHeaderSize;
1472
1473   if ((pBuffer!=NULL && iBufferSize>0) || (pHeader!=NULL && iHeaderSize>0)) {
1474     if (fpOutputBuffer && iBlkSize<=(int)(fOutputBufferSize-fOutputBufferFilled)) {
1475       AliHLTUInt8_t* pTgt=fpOutputBuffer+fOutputBufferFilled;
1476
1477       // copy header if provided but skip if the header is the target location
1478       // in that case it has already been copied
1479       if (pHeader!=NULL && pHeader!=pTgt) {
1480         memcpy(pTgt, pHeader, iHeaderSize);
1481       }
1482
1483       pTgt += (AliHLTUInt8_t) iHeaderSize;
1484
1485       // copy buffer if provided but skip if buffer is the target location
1486       // in that case it has already been copied
1487       if (pBuffer!=NULL && pBuffer!=pTgt) {
1488         memcpy(pTgt, pBuffer, iBufferSize);
1489         
1490         //AliHLTUInt32_t firstWord=*((AliHLTUInt32_t*)pBuffer); 
1491         //HLTDebug("copy %d bytes from %p to output buffer %p, first word %#x", iBufferSize, pBuffer, pTgt, firstWord);
1492       }
1493       //HLTDebug("buffer inserted to output: size %d data type %s spec %#x", iBlkSize, DataType2Text(dt).c_str(), spec);
1494     } else {
1495       if (fpOutputBuffer) {
1496         HLTError("too little space in output buffer: %d of %d, required %d", fOutputBufferSize-fOutputBufferFilled, fOutputBufferSize, iBlkSize);
1497       } else {
1498         HLTError("output buffer not available");
1499       }
1500       iResult=-ENOSPC;
1501     }
1502   }
1503   if (iResult>=0) {
1504     AliHLTComponentBlockData bd;
1505     FillBlockData( bd );
1506     bd.fOffset        = fOutputBufferFilled;
1507     bd.fSize          = iBlkSize;
1508     bd.fDataType      = dt;
1509     bd.fSpecification = spec;
1510     fOutputBlocks.push_back( bd );
1511     fOutputBufferFilled+=bd.fSize;
1512   }
1513
1514   return iResult;
1515 }
1516
1517 int AliHLTComponent::EstimateObjectSize(TObject* pObject) const
1518 {
1519   // see header file for function documentation
1520   if (!pObject) return 0;
1521
1522   AliHLTMessage msg(kMESS_OBJECT);
1523   msg.WriteObject(pObject);
1524   return msg.Length();  
1525 }
1526
1527 AliHLTMemoryFile* AliHLTComponent::CreateMemoryFile(int capacity, const char* dtID,
1528                                                     const char* dtOrigin,
1529                                                     AliHLTUInt32_t spec)
1530 {
1531   // see header file for function documentation
1532   ALIHLTCOMPONENT_BASE_STOPWATCH();
1533   AliHLTComponentDataType dt;
1534   SetDataType(dt, dtID, dtOrigin);
1535   return CreateMemoryFile(capacity, dt, spec);
1536 }
1537
1538 AliHLTMemoryFile* AliHLTComponent::CreateMemoryFile(int capacity,
1539                                                     const AliHLTComponentDataType& dt,
1540                                                     AliHLTUInt32_t spec)
1541 {
1542   // see header file for function documentation
1543   ALIHLTCOMPONENT_BASE_STOPWATCH();
1544   AliHLTMemoryFile* pFile=NULL;
1545   if (capacity>=0 && static_cast<unsigned int>(capacity)<=fOutputBufferSize-fOutputBufferFilled){
1546     AliHLTUInt8_t* pTgt=fpOutputBuffer+fOutputBufferFilled;
1547     pFile=new AliHLTMemoryFile((char*)pTgt, capacity);
1548     if (pFile) {
1549       unsigned int nofBlocks=fOutputBlocks.size();
1550       if (nofBlocks+1>fMemFiles.size()) {
1551         fMemFiles.resize(nofBlocks+1, NULL);
1552       }
1553       if (nofBlocks<fMemFiles.size()) {
1554         fMemFiles[nofBlocks]=pFile;
1555         AliHLTComponentBlockData bd;
1556         FillBlockData( bd );
1557         bd.fOffset        = fOutputBufferFilled;
1558         bd.fSize          = capacity;
1559         bd.fDataType      = dt;
1560         bd.fSpecification = spec;
1561         fOutputBufferFilled+=bd.fSize;
1562         fOutputBlocks.push_back( bd );
1563       } else {
1564         HLTError("can not allocate/grow object array");
1565         pFile->CloseMemoryFile(0);
1566         delete pFile;
1567         pFile=NULL;
1568       }
1569     }
1570   } else {
1571     HLTError("can not create memory file of size %d (%d available)", capacity, fOutputBufferSize-fOutputBufferFilled);
1572   }
1573   return pFile;
1574 }
1575
1576 AliHLTMemoryFile* AliHLTComponent::CreateMemoryFile(const char* dtID,
1577                                                     const char* dtOrigin,
1578                                                     AliHLTUInt32_t spec,
1579                                                     float capacity)
1580 {
1581   // see header file for function documentation
1582   ALIHLTCOMPONENT_BASE_STOPWATCH();
1583   AliHLTComponentDataType dt;
1584   SetDataType(dt, dtID, dtOrigin);
1585   int size=fOutputBufferSize-fOutputBufferFilled;
1586   if (capacity<0 || capacity>1.0) {
1587     HLTError("invalid parameter: capacity %f", capacity);
1588     return NULL;
1589   }
1590   size=(int)(size*capacity);
1591   return CreateMemoryFile(size, dt, spec);
1592 }
1593
1594 AliHLTMemoryFile* AliHLTComponent::CreateMemoryFile(const AliHLTComponentDataType& dt,
1595                                                     AliHLTUInt32_t spec,
1596                                                     float capacity)
1597 {
1598   // see header file for function documentation
1599   ALIHLTCOMPONENT_BASE_STOPWATCH();
1600   int size=fOutputBufferSize-fOutputBufferFilled;
1601   if (capacity<0 || capacity>1.0) {
1602     HLTError("invalid parameter: capacity %f", capacity);
1603     return NULL;
1604   }
1605   size=(int)(size*capacity);
1606   return CreateMemoryFile(size, dt, spec);
1607 }
1608
1609 int AliHLTComponent::Write(AliHLTMemoryFile* pFile, const TObject* pObject,
1610                            const char* key, int option)
1611 {
1612   // see header file for function documentation
1613   int iResult=0;
1614   if (pFile && pObject) {
1615     pFile->cd();
1616     iResult=pObject->Write(key, option);
1617     if (iResult>0) {
1618       // success
1619     } else {
1620       iResult=-pFile->GetErrno();
1621       if (iResult==-ENOSPC) {
1622         HLTError("error writing memory file, buffer too small");
1623       }
1624     }
1625   } else {
1626     iResult=-EINVAL;
1627   }
1628   return iResult;
1629 }
1630
1631 int AliHLTComponent::CloseMemoryFile(AliHLTMemoryFile* pFile)
1632 {
1633   // see header file for function documentation
1634   int iResult=0;
1635   if (pFile) {
1636     AliHLTMemoryFilePList::iterator element=fMemFiles.begin();
1637     int i=0;
1638     while (element!=fMemFiles.end() && iResult>=0) {
1639       if (*element && *element==pFile) {
1640         iResult=pFile->CloseMemoryFile();
1641         
1642         // sync memory files and descriptors
1643         if (iResult>=0) {
1644           fOutputBlocks[i].fSize=(*element)->GetSize()+(*element)->GetHeaderSize();
1645         }
1646         delete *element;
1647         *element=NULL;
1648         return iResult;
1649       }
1650       element++; i++;
1651     }
1652     HLTError("can not find memory file %p", pFile);
1653     iResult=-ENOENT;
1654   } else {
1655     iResult=-EINVAL;
1656   }
1657   return iResult;
1658 }
1659
1660 int AliHLTComponent::CreateEventDoneData(AliHLTComponentEventDoneData edd)
1661 {
1662   // see header file for function documentation
1663   int iResult=0;
1664
1665   AliHLTComponentEventDoneData* newEDD = NULL;
1666   
1667   unsigned long newSize=edd.fDataSize;
1668   if (fEventDoneData)
1669     newSize += fEventDoneData->fDataSize;
1670
1671   if (newSize>fEventDoneDataSize) {
1672     newEDD = reinterpret_cast<AliHLTComponentEventDoneData*>( new AliHLTUInt8_t[ sizeof(AliHLTComponentEventDoneData)+newSize ] );
1673     if (!newEDD)
1674       return -ENOMEM;
1675     newEDD->fStructSize = sizeof(AliHLTComponentEventDoneData);
1676     newEDD->fDataSize = newSize;
1677     newEDD->fData = reinterpret_cast<AliHLTUInt8_t*>(newEDD)+newEDD->fStructSize;
1678     unsigned long long offset = 0;
1679     if (fEventDoneData) {
1680       memcpy( newEDD->fData, fEventDoneData->fData, fEventDoneData->fDataSize );
1681       offset += fEventDoneData->fDataSize;
1682     }
1683     memcpy( reinterpret_cast<AliHLTUInt8_t*>(newEDD->fData)+offset, edd.fData, edd.fDataSize );
1684     if (fEventDoneData)
1685       delete [] reinterpret_cast<AliHLTUInt8_t*>( fEventDoneData );
1686     fEventDoneData = newEDD;
1687     fEventDoneDataSize = newSize;
1688   }
1689   else {
1690     memcpy( reinterpret_cast<AliHLTUInt8_t*>(fEventDoneData->fData)+fEventDoneData->fDataSize, edd.fData, edd.fDataSize );
1691     fEventDoneData->fDataSize += edd.fDataSize;
1692   }
1693   return iResult;
1694 }
1695
1696 int AliHLTComponent::ProcessEvent( const AliHLTComponentEventData& evtData,
1697                                    const AliHLTComponentBlockData* blocks, 
1698                                    AliHLTComponentTriggerData& trigData,
1699                                    AliHLTUInt8_t* outputPtr, 
1700                                    AliHLTUInt32_t& size,
1701                                    AliHLTUInt32_t& outputBlockCnt, 
1702                                    AliHLTComponentBlockData*& outputBlocks,
1703                                    AliHLTComponentEventDoneData*& edd )
1704 {
1705   // see header file for function documentation
1706   HLTLogKeyword(fChainId.c_str());
1707   ALIHLTCOMPONENT_BASE_STOPWATCH();
1708   int iResult=0;
1709   fCurrentEvent=evtData.fEventID;
1710   fCurrentEventData=evtData;
1711   fpInputBlocks=blocks;
1712   fCurrentInputBlock=-1;
1713   fSearchDataType=kAliHLTAnyDataType;
1714   fpOutputBuffer=outputPtr;
1715   fOutputBufferSize=size;
1716   fOutputBufferFilled=0;
1717   fOutputBlocks.clear();
1718   outputBlockCnt=0;
1719   outputBlocks=NULL;
1720
1721   AliHLTComponentBlockDataList forwardedBlocks;
1722
1723   // optional component statistics
1724   AliHLTComponentStatisticsList compStats;
1725   bool bAddComponentTableEntry=false;
1726   vector<AliHLTUInt32_t> parentComponentTables;
1727 #if defined(HLT_COMPONENT_STATISTICS)
1728   if ((fFlags&kDisableComponentStat)==0) {
1729     AliHLTComponentStatistics outputStat;
1730     memset(&outputStat, 0, sizeof(AliHLTComponentStatistics));
1731     outputStat.fStructSize=sizeof(AliHLTComponentStatistics);
1732     outputStat.fId=fChainIdCrc;
1733     if (fpBenchmark) {
1734       fpBenchmark->Stop();
1735       outputStat.fComponentCycleTime=(AliHLTUInt32_t)(fpBenchmark->RealTime()*ALIHLTCOMPONENT_STATTIME_SCALER);
1736       fpBenchmark->Reset();
1737       fpBenchmark->Start();
1738     }
1739     compStats.push_back(outputStat);
1740   }
1741 #endif // HLT_COMPONENT_STATISTICS
1742
1743   // data processing is skipped
1744   // -  if there are only steering events in the block list.
1745   //    For the sake of data source components data processing
1746   //    is not skipped if there is no block list at all or if it
1747   //    just contains the eventType block
1748   // - always skipped if the event is of type
1749   //   - gkAliEventTypeConfiguration
1750   //   - gkAliEventTypeReadPreprocessor
1751   const unsigned int skipModeDefault=0x1;
1752   const unsigned int skipModeForce=0x2;
1753   unsigned int bSkipDataProcessing=skipModeDefault;
1754
1755   // find special events
1756   if (fpInputBlocks && evtData.fBlockCnt>0) {
1757     // first look for all special events and execute in the appropriate
1758     // sequence afterwords
1759     int indexComConfEvent=-1;
1760     int indexUpdtDCSEvent=-1;
1761     int indexSOREvent=-1;
1762     int indexEOREvent=-1;
1763     int indexECSParamBlock=-1;
1764     for (unsigned int i=0; i<evtData.fBlockCnt && iResult>=0; i++) {
1765       if (fpInputBlocks[i].fDataType==kAliHLTDataTypeSOR) {
1766         indexSOREvent=i;
1767         // the AliHLTCalibrationProcessor relies on the SOR and EOR events
1768         bSkipDataProcessing&=~skipModeDefault;
1769       } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeRunType) {
1770         // run type string
1771         // handling is not clear yet
1772         if (fpInputBlocks[i].fPtr) {
1773           HLTDebug("got run type \"%s\"\n", fpInputBlocks[i].fPtr);
1774         }
1775       } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeEOR) {
1776         indexEOREvent=i;
1777         // the calibration processor relies on the SOR and EOR events
1778         bSkipDataProcessing&=~skipModeDefault;
1779       } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeDDL) {
1780         // DDL list
1781         // this event is most likely deprecated
1782       } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeComConf) {
1783         indexComConfEvent=i;
1784       } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeUpdtDCS) {
1785         indexUpdtDCSEvent=i;
1786       } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeEvent) {
1787         fEventType=fpInputBlocks[i].fSpecification;
1788
1789         // skip always in case of gkAliEventTypeConfiguration
1790         if (fpInputBlocks[i].fSpecification==gkAliEventTypeConfiguration) bSkipDataProcessing|=skipModeForce;
1791
1792         // skip always in case of gkAliEventTypeReadPreprocessor
1793         if (fpInputBlocks[i].fSpecification==gkAliEventTypeReadPreprocessor) bSkipDataProcessing|=skipModeForce;
1794
1795         // never skip if the event type block is the only block
1796         if (evtData.fBlockCnt==1) bSkipDataProcessing&=~skipModeDefault;
1797
1798       } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeComponentStatistics) {
1799         if (compStats.size()>0) {
1800           AliHLTUInt8_t* pData=reinterpret_cast<AliHLTUInt8_t*>(fpInputBlocks[i].fPtr);
1801           for (AliHLTUInt32_t offset=0;
1802                offset+sizeof(AliHLTComponentStatistics)<=fpInputBlocks[i].fSize;
1803                offset+=sizeof(AliHLTComponentStatistics)) {
1804             AliHLTComponentStatistics* pStat=reinterpret_cast<AliHLTComponentStatistics*>(pData+offset);
1805             if (pStat && compStats[0].fLevel<=pStat->fLevel) {
1806               compStats[0].fLevel=pStat->fLevel+1;
1807             }
1808             compStats.push_back(*pStat);
1809           }
1810         }
1811       } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeComponentTable) {
1812         forwardedBlocks.push_back(fpInputBlocks[i]);
1813         parentComponentTables.push_back(fpInputBlocks[i].fSpecification);
1814       } else if (fpInputBlocks[i].fDataType==kAliHLTDataTypeECSParam) {
1815         indexECSParamBlock=i;
1816       } else {
1817         // the processing function is called if there is at least one
1818         // non-steering data block. Steering blocks are not filtered out
1819         // for sake of performance 
1820         bSkipDataProcessing&=~skipModeDefault;
1821         if (compStats.size()>0) {
1822           compStats[0].fInputBlockCount++;
1823           compStats[0].fTotalInputSize+=fpInputBlocks[i].fSize;
1824         }
1825       }
1826     }
1827
1828     if (indexSOREvent>=0) {
1829       // start of run
1830       bAddComponentTableEntry=true;
1831       if (fpRunDesc==NULL) {
1832         fpRunDesc=new AliHLTRunDesc;
1833         if (fpRunDesc) *fpRunDesc=kAliHLTVoidRunDesc;
1834       }
1835       if (fpRunDesc) {
1836         AliHLTRunDesc rundesc;
1837         if ((iResult=CopyStruct(&rundesc, sizeof(AliHLTRunDesc), indexSOREvent, "AliHLTRunDesc", "SOR"))>0) {
1838           if (fpRunDesc->fRunNo==kAliHLTVoidRunNo) {
1839             *fpRunDesc=rundesc;
1840             HLTDebug("set run decriptor, run no %d", fpRunDesc->fRunNo);
1841             SetCDBRunNo(fpRunDesc->fRunNo);
1842           } else if (fpRunDesc->fRunNo!=rundesc.fRunNo) {
1843             HLTWarning("already set run properties run no %d, ignoring SOR with run no %d", fpRunDesc->fRunNo, rundesc.fRunNo);
1844           }
1845         }
1846       } else {
1847         iResult=-ENOMEM;
1848       }
1849
1850       if (indexECSParamBlock>=0) {
1851         if (fpInputBlocks[indexECSParamBlock].fSize>0) {
1852           const char* param=reinterpret_cast<const char*>(fpInputBlocks[indexECSParamBlock].fPtr);
1853           TString paramString;
1854           if (param[fpInputBlocks[indexECSParamBlock].fSize-1]!=0) {
1855             HLTWarning("ECS parameter string not terminated");
1856             paramString.Insert(0, param, fpInputBlocks[indexECSParamBlock].fSize);
1857             paramString+="";
1858           } else {
1859             paramString=param;
1860           }
1861           ScanECSParam(paramString.Data());
1862         } else {
1863           HLTWarning("empty ECS parameter received");
1864         }
1865       } else {
1866         // TODO: later on we might throw a warning here since the CTP trigger classes
1867         // should be mandatory
1868       }
1869     }
1870     if (indexEOREvent>=0) {
1871       fLastPushBackTime=0; // always send at EOR
1872       bAddComponentTableEntry=true;
1873       if (fpRunDesc!=NULL) {
1874         if (fpRunDesc) {
1875           AliHLTRunDesc rundesc;
1876           if ((iResult=CopyStruct(&rundesc, sizeof(AliHLTRunDesc), indexEOREvent, "AliHLTRunDesc", "SOR"))>0) {
1877             if (fpRunDesc->fRunNo!=rundesc.fRunNo) {
1878               HLTWarning("run no mismatch: SOR %d, EOR %d", fpRunDesc->fRunNo, rundesc.fRunNo);
1879             } else {
1880               HLTDebug("EOR run no %d", fpRunDesc->fRunNo);
1881             }
1882           }
1883           // we do not unload the fpRunDesc struct here in order to have the run information
1884           // available during the event processing
1885           // https://savannah.cern.ch/bugs/?39711
1886           // the info will be cleared in DeInit
1887         }
1888       } else {
1889         HLTWarning("did not receive SOR, ignoring EOR");
1890       }
1891     }
1892     if (indexComConfEvent>=0 || fEventType==gkAliEventTypeConfiguration) {
1893       TString cdbEntry;
1894       if (indexComConfEvent>=0 && fpInputBlocks[indexComConfEvent].fPtr!=NULL && fpInputBlocks[indexComConfEvent].fSize>0) {
1895         cdbEntry.Append(reinterpret_cast<const char*>(fpInputBlocks[indexComConfEvent].fPtr), fpInputBlocks[indexComConfEvent].fSize);
1896       }
1897       HLTDebug("received component configuration command: entry %s", cdbEntry.IsNull()?"none":cdbEntry.Data());
1898       int tmpResult=Reconfigure(cdbEntry[0]==0?NULL:cdbEntry.Data(), fChainId.c_str());
1899       if (tmpResult<0) {
1900         HLTWarning("reconfiguration of component %p (%s) failed with error code %d", this, GetComponentID(), tmpResult);
1901       }
1902     }
1903     if (indexUpdtDCSEvent>=0 || fEventType==gkAliEventTypeReadPreprocessor) {
1904       TString modules;
1905       if (fpInputBlocks[indexUpdtDCSEvent].fPtr!=NULL && fpInputBlocks[indexUpdtDCSEvent].fSize>0) {
1906         modules.Append(reinterpret_cast<const char*>(fpInputBlocks[indexUpdtDCSEvent].fPtr), fpInputBlocks[indexUpdtDCSEvent].fSize);
1907       }
1908       HLTDebug("received preprocessor update command: detectors %s", modules.IsNull()?"ALL":modules.Data());
1909       int tmpResult=ReadPreprocessorValues(modules[0]==0?"ALL":modules.Data());
1910       if (tmpResult<0) {
1911         HLTWarning("preprocessor update of component %p (%s) failed with error code %d", this, GetComponentID(), tmpResult);
1912       }
1913     }
1914   } else {
1915     // processing function needs to be called if there are no input data
1916     // blocks in order to make data source components working.
1917     bSkipDataProcessing&=~skipModeDefault;
1918   }
1919
1920   // data processing is not skipped if the component explicitly asks
1921   // for the private blocks
1922   if ((fFlags&kRequireSteeringBlocks)!=0) bSkipDataProcessing=0;
1923
1924   if (fpCTPData) {
1925     // set the active triggers for this event
1926     fpCTPData->SetTriggers(trigData);
1927     // increment CTP trigger counters if available
1928     if (IsDataEvent()) fpCTPData->Increment(trigData);
1929   }
1930
1931   AliHLTComponentBlockDataList blockData;
1932   if (iResult>=0 && !bSkipDataProcessing)
1933   { // dont delete, sets the scope for the stopwatch guard
1934     // do not use ALIHLTCOMPONENT_DA_STOPWATCH(); macro
1935     // in order to avoid 'shadowed variable' warning
1936     AliHLTStopwatchGuard swguard2(fpStopwatches!=NULL?reinterpret_cast<TStopwatch*>(fpStopwatches->At((int)kSWDA)):NULL);
1937     iResult=DoProcessing(evtData, blocks, trigData, outputPtr, size, blockData, edd);
1938   } // end of the scope of the stopwatch guard
1939   if (iResult>=0 && !bSkipDataProcessing) {
1940     if (fOutputBlocks.size()>0) {
1941       // High Level interface
1942
1943       //HLTDebug("got %d block(s) via high level interface", fOutputBlocks.size());      
1944       // sync memory files and descriptors
1945       AliHLTMemoryFilePList::iterator element=fMemFiles.begin();
1946       int i=0;
1947       while (element!=fMemFiles.end() && iResult>=0) {
1948         if (*element) {
1949           if ((*element)->IsClosed()==0) {
1950             HLTWarning("memory file has not been closed, force flush");
1951             iResult=CloseMemoryFile(*element);
1952           }
1953         }
1954         element++; i++;
1955       }
1956
1957       if (iResult>=0) {
1958         // create the descriptor list
1959         if (blockData.size()>0) {
1960           HLTError("low level and high interface must not be mixed; use PushBack methods to insert data blocks");
1961           iResult=-EFAULT;
1962         } else {
1963           if (compStats.size()>0 && IsDataEvent()) {
1964             int offset=AddComponentStatistics(fOutputBlocks, fpOutputBuffer, fOutputBufferSize, fOutputBufferFilled, compStats);
1965             if (offset>0) fOutputBufferFilled+=offset;
1966           }
1967           if (bAddComponentTableEntry) {
1968             int offset=AddComponentTableEntry(fOutputBlocks, fpOutputBuffer, fOutputBufferSize, fOutputBufferFilled, parentComponentTables);
1969             if (offset>0) size+=offset;
1970           }
1971           if (forwardedBlocks.size()>0) {
1972             fOutputBlocks.insert(fOutputBlocks.end(), forwardedBlocks.begin(), forwardedBlocks.end());
1973           }
1974           iResult=MakeOutputDataBlockList(fOutputBlocks, &outputBlockCnt, &outputBlocks);
1975           size=fOutputBufferFilled;
1976         }
1977       }
1978     } else {
1979       // Low Level interface
1980       if (compStats.size()>0) {
1981         int offset=AddComponentStatistics(blockData, fpOutputBuffer, fOutputBufferSize, size, compStats);
1982         if (offset>0) size+=offset;
1983       }
1984       if (bAddComponentTableEntry) {
1985         int offset=AddComponentTableEntry(blockData, fpOutputBuffer, fOutputBufferSize, size, parentComponentTables);
1986         if (offset>0) size+=offset;
1987       }
1988       if (forwardedBlocks.size()>0) {
1989         blockData.insert(blockData.end(), forwardedBlocks.begin(), forwardedBlocks.end());
1990       }
1991       iResult=MakeOutputDataBlockList(blockData, &outputBlockCnt, &outputBlocks);
1992     }
1993     if (iResult<0) {
1994       HLTFatal("component %s (%p): can not convert output block descriptor list", GetComponentID(), this);
1995     }
1996   }
1997   if (iResult<0 || bSkipDataProcessing) {
1998     outputBlockCnt=0;
1999     outputBlocks=NULL;
2000   }
2001   CleanupInputObjects();
2002   if (iResult>=0 && IsDataEvent()) {
2003     IncrementEventCounter();
2004   }
2005   if (outputBlockCnt==0) {
2006     // no output blocks, set size to 0
2007     size=0;
2008   }
2009
2010   // reset the internal EventData struct
2011   FillEventData(fCurrentEventData);
2012
2013   // reset the active triggers
2014   if (fpCTPData) fpCTPData->SetTriggers(0);
2015
2016   // set the time for the pushback period
2017   if (fPushbackPeriod>0) {
2018     // suppress the output
2019     TDatime time;
2020     if (fLastPushBackTime<0 || (int)time.Get()-fLastPushBackTime>=fPushbackPeriod) {
2021       fLastPushBackTime=time.Get();
2022     }
2023   }
2024
2025   return iResult;
2026 }
2027
2028 int  AliHLTComponent::AddComponentStatistics(AliHLTComponentBlockDataList& blocks, 
2029                                              AliHLTUInt8_t* buffer,
2030                                              AliHLTUInt32_t bufferSize,
2031                                              AliHLTUInt32_t offset,
2032                                              AliHLTComponentStatisticsList& stats) const
2033 {
2034   // see header file for function documentation
2035   int iResult=0;
2036   if ((fFlags&kDisableComponentStat)!=0) return 0;
2037 #if defined(HLT_COMPONENT_STATISTICS)
2038   if (stats.size()==0) return -ENOENT;
2039   // check if there is space for at least one entry
2040   if (offset+sizeof(AliHLTComponentStatistics)>bufferSize) return 0;
2041   stats[0].fTotalOutputSize=offset;
2042   stats[0].fOutputBlockCount=blocks.size();
2043   if (fpBenchmark) {
2044     fpBenchmark->Stop();
2045     stats[0].fTime=(AliHLTUInt32_t)(fpBenchmark->RealTime()*ALIHLTCOMPONENT_STATTIME_SCALER);
2046     stats[0].fCTime=(AliHLTUInt32_t)(fpBenchmark->CpuTime()*ALIHLTCOMPONENT_STATTIME_SCALER);
2047     fpBenchmark->Continue();
2048   }
2049   if (offset+stats.size()*sizeof(AliHLTComponentStatistics)>bufferSize) {
2050     AliHLTUInt32_t removedLevel=0;
2051     do {
2052       // remove all entries of the level of the last entry
2053       removedLevel=stats.back().fLevel;
2054       AliHLTComponentStatisticsList::iterator element=stats.begin();
2055       element++;
2056       while (element!=stats.end()) {
2057         if (element->fLevel<=removedLevel) {
2058           element=stats.erase(element);
2059         } else {
2060           element++;
2061         }
2062       }
2063     } while (stats.size()>1 && 
2064              (offset+stats.size()*sizeof(AliHLTComponentStatistics)>bufferSize));
2065   }
2066   assert(stats.size()>0);
2067   if (stats.size()==0) return 0;
2068
2069   if (offset+stats.size()*sizeof(AliHLTComponentStatistics)<=bufferSize) {
2070     AliHLTComponentBlockData bd;
2071     FillBlockData( bd );
2072     bd.fOffset        = offset;
2073     bd.fSize          = stats.size()*sizeof(AliHLTComponentStatistics);
2074     bd.fDataType      = kAliHLTDataTypeComponentStatistics;
2075     bd.fSpecification = kAliHLTVoidDataSpec;
2076     unsigned int master=0;
2077     for (unsigned int i=1; i<blocks.size(); i++) {
2078       if (blocks[i].fSize>blocks[master].fSize && 
2079           !MatchExactly(blocks[i].fDataType, kAliHLTVoidDataType|kAliHLTDataOriginPrivate))
2080         master=i;
2081     }
2082     if (blocks.size()>0 && !MatchExactly(blocks[master].fDataType, kAliHLTVoidDataType|kAliHLTDataOriginPrivate)) {
2083       // take the data origin of the biggest block as specification
2084       // this is similar to the treatment in the HOMER interface. For traditional
2085       // reasons, the bytes are swapped there on a little endian architecture, so
2086       // we do it as well.
2087       memcpy(&bd.fSpecification, &blocks[master].fDataType.fOrigin, sizeof(bd.fSpecification));
2088 #ifdef R__BYTESWAP // set on little endian architectures
2089       bd.fSpecification=((bd.fSpecification & 0xFFULL) << 24) | 
2090         ((bd.fSpecification & 0xFF00ULL) << 8) | 
2091         ((bd.fSpecification & 0xFF0000ULL) >> 8) | 
2092         ((bd.fSpecification & 0xFF000000ULL) >> 24);
2093 #endif
2094     }
2095     memcpy(buffer+offset, &(stats[0]), bd.fSize);
2096     blocks.push_back(bd);
2097     iResult=bd.fSize;
2098   }
2099 #else
2100   if (blocks.size() && buffer && bufferSize && offset && stats.size()) {
2101     // get rid of warning
2102   }
2103 #endif // HLT_COMPONENT_STATISTICS
2104   return iResult;
2105 }
2106
2107 int  AliHLTComponent::AddComponentTableEntry(AliHLTComponentBlockDataList& blocks, 
2108                                              AliHLTUInt8_t* buffer,
2109                                              AliHLTUInt32_t bufferSize,
2110                                              AliHLTUInt32_t offset,
2111                                              const vector<AliHLTUInt32_t>& parents) const
2112 {
2113   // see header file for function documentation
2114   int iResult=0;
2115   if ((fFlags&kDisableComponentStat)!=0) return 0;
2116 #if defined(HLT_COMPONENT_STATISTICS)
2117   // the payload consists of the AliHLTComponentTableEntry struct,
2118   // followed by a an array of 32bit crc chain ids and the component
2119   // description string
2120   unsigned int payloadSize=sizeof(AliHLTComponentTableEntry);
2121   payloadSize+=parents.size()*sizeof(AliHLTUInt32_t);
2122
2123   // the component description has the following format:
2124   // chain-id{component-id:arguments}
2125   const char* componentId=const_cast<AliHLTComponent*>(this)->GetComponentID();
2126   unsigned int descriptionSize=fChainId.size()+1;
2127   descriptionSize+=2; // the '{}' around the component id
2128   descriptionSize+=strlen(componentId);
2129   descriptionSize+=1; // the ':' between component id and arguments
2130   descriptionSize+=fComponentArgs.size();
2131
2132   payloadSize+=descriptionSize;
2133   if (buffer && (offset+payloadSize<=bufferSize)) {
2134     AliHLTUInt8_t* pTgt=buffer+offset;
2135     memset(pTgt, 0, payloadSize);
2136
2137     // write entry
2138     AliHLTComponentTableEntry* pEntry=reinterpret_cast<AliHLTComponentTableEntry*>(pTgt);
2139     pEntry->fStructSize=sizeof(AliHLTComponentTableEntry);
2140     pEntry->fNofParents=parents.size();
2141     pEntry->fSizeDescription=descriptionSize;
2142     pTgt=pEntry->fBuffer;
2143
2144     // write array of parents
2145     if (parents.size()>0) {
2146       unsigned int copy=parents.size()*sizeof(vector<AliHLTUInt32_t>::value_type);
2147       memcpy(pTgt, &parents[0], parents.size()*sizeof(vector<AliHLTUInt32_t>::value_type));
2148       pTgt+=copy;
2149     }
2150
2151     // write component description
2152     memcpy(pTgt, fChainId.c_str(), fChainId.size());
2153     pTgt+=fChainId.size();
2154     *pTgt++='{';
2155     memcpy(pTgt, componentId, strlen(componentId));
2156     pTgt+=strlen(componentId);
2157     *pTgt++=':';
2158     memcpy(pTgt, fComponentArgs.c_str(), fComponentArgs.size());
2159     pTgt+=fComponentArgs.size();
2160     *pTgt++='}';
2161     *pTgt++=0;
2162
2163     AliHLTComponentBlockData bd;
2164     FillBlockData( bd );
2165     bd.fOffset        = offset;
2166     bd.fSize          = payloadSize;
2167     bd.fDataType      = kAliHLTDataTypeComponentTable;
2168     bd.fSpecification = fChainIdCrc;
2169     blocks.push_back(bd);
2170     iResult=bd.fSize;
2171   }
2172 #else
2173   if (blocks.size() && buffer && bufferSize && offset && parents.size()) {
2174     // get rid of warning
2175   }
2176 #endif // HLT_COMPONENT_STATISTICS
2177   return iResult;
2178 }
2179
2180 AliHLTComponent::AliHLTStopwatchGuard::AliHLTStopwatchGuard()
2181   :
2182   fpStopwatch(NULL),
2183   fpPrec(NULL)
2184 {
2185   // standard constructor (not for use)
2186 }
2187
2188 AliHLTComponent::AliHLTStopwatchGuard::AliHLTStopwatchGuard(TStopwatch* pStopwatch)
2189   :
2190   fpStopwatch(pStopwatch),
2191   fpPrec(NULL)
2192 {
2193   // constructor
2194
2195   // check for already existing guard
2196   if (fgpCurrent) fpPrec=fgpCurrent;
2197   fgpCurrent=this;
2198
2199   // stop the preceeding guard if it controls a different stopwatch
2200   int bStart=1;
2201   if (fpPrec && fpPrec!=this) bStart=fpPrec->Hold(fpStopwatch);
2202
2203   // start the stopwatch if the current guard controls a different one
2204   if (fpStopwatch && bStart==1) fpStopwatch->Start(kFALSE);
2205 }
2206
2207 AliHLTComponent::AliHLTStopwatchGuard::AliHLTStopwatchGuard(const AliHLTStopwatchGuard&)
2208   :
2209   fpStopwatch(NULL),
2210   fpPrec(NULL)
2211 {
2212   //
2213   // copy constructor not for use
2214   //
2215 }
2216
2217 AliHLTComponent::AliHLTStopwatchGuard& AliHLTComponent::AliHLTStopwatchGuard::operator=(const AliHLTStopwatchGuard&)
2218 {
2219   //
2220   // assignment operator not for use
2221   //
2222   fpStopwatch=NULL;
2223   fpPrec=NULL;
2224   return *this;
2225 }
2226
2227 AliHLTComponent::AliHLTStopwatchGuard* AliHLTComponent::AliHLTStopwatchGuard::fgpCurrent=NULL;
2228
2229 AliHLTComponent::AliHLTStopwatchGuard::~AliHLTStopwatchGuard()
2230 {
2231   // destructor
2232
2233   // resume the preceeding guard if it controls a different stopwatch
2234   int bStop=1;
2235   if (fpPrec && fpPrec!=this) bStop=fpPrec->Resume(fpStopwatch);
2236
2237   // stop the stopwatch if the current guard controls a different one
2238   if (fpStopwatch && bStop==1) fpStopwatch->Stop();
2239
2240   // resume to the preceeding guard
2241   fgpCurrent=fpPrec;
2242 }
2243
2244 int AliHLTComponent::AliHLTStopwatchGuard::Hold(const TStopwatch* pSucc)
2245 {
2246   // see header file for function documentation
2247   if (fpStopwatch!=NULL && fpStopwatch!=pSucc) fpStopwatch->Stop();
2248   return fpStopwatch!=pSucc?1:0;
2249 }
2250
2251 int AliHLTComponent::AliHLTStopwatchGuard::Resume(const TStopwatch* pSucc)
2252 {
2253   // see header file for function documentation
2254   if (fpStopwatch!=NULL && fpStopwatch!=pSucc) fpStopwatch->Start(kFALSE);
2255   return fpStopwatch!=pSucc?1:0;
2256 }
2257
2258 int AliHLTComponent::SetStopwatch(TObject* pSW, AliHLTStopwatchType type) 
2259 {
2260   // see header file for function documentation
2261   int iResult=0;
2262   if (pSW!=NULL && type<kSWTypeCount) {
2263     if (fpStopwatches) {
2264       TObject* pObj=fpStopwatches->At((int)type);
2265       if (pSW==NULL        // explicit reset
2266           || pObj==NULL) { // explicit set
2267         fpStopwatches->AddAt(pSW, (int)type);
2268       } else if (pObj!=pSW) {
2269         HLTWarning("stopwatch %d already set, reset first", (int)type);
2270         iResult=-EBUSY;
2271       }
2272     }
2273   } else {
2274     iResult=-EINVAL;
2275   }
2276   return iResult;
2277 }
2278
2279 int AliHLTComponent::SetStopwatches(TObjArray* pStopwatches)
2280 {
2281   // see header file for function documentation
2282   if (pStopwatches==NULL) return -EINVAL;
2283
2284   int iResult=0;
2285   for (int i=0 ; i<(int)kSWTypeCount && pStopwatches->GetEntriesFast(); i++)
2286     SetStopwatch(pStopwatches->At(i), (AliHLTStopwatchType)i);
2287   return iResult;
2288 }
2289
2290 AliHLTUInt32_t AliHLTComponent::GetRunNo() const
2291 {
2292   // see header file for function documentation
2293
2294   // 2010-02-11 OCDB is now the reliable source for the run number, it is
2295   // initialized either by aliroot or the external interface depending
2296   // on the environment. It turned out that the rundescriptor is not set
2297   // in the aliroot mode, resulting in an invalid run number. However this
2298   // did not cause problems until now. OCDB initialization has been revised
2299   // already in 10/2009. This was a remnant.
2300   // Have to check whether we get rid of the rundescriptor at some point.
2301   if (fpRunDesc==NULL) return AliHLTMisc::Instance().GetCDBRunNo();
2302   if (fpRunDesc->fRunNo!=(unsigned)AliHLTMisc::Instance().GetCDBRunNo()) {
2303     HLTWarning("run number mismatch: ocdb %d   run descriptor %d", AliHLTMisc::Instance().GetCDBRunNo(), fpRunDesc->fRunNo);
2304   }
2305   return fpRunDesc->fRunNo;
2306 }
2307
2308 AliHLTUInt32_t AliHLTComponent::GetRunType() const
2309 {
2310   // see header file for function documentation
2311   if (fpRunDesc==NULL) return kAliHLTVoidRunType;
2312   return fpRunDesc->fRunType;
2313 }
2314
2315 AliHLTUInt32_t    AliHLTComponent::GetTimeStamp() const
2316 {
2317   // see header file for function documentation
2318   if (fCurrentEventData.fEventCreation_s) {
2319     return  fCurrentEventData.fEventCreation_s;
2320   }
2321   // using the actual UTC if the time stamp was not set by the framework
2322   return static_cast<AliHLTUInt32_t>(time(NULL));
2323 }
2324
2325 AliHLTUInt32_t    AliHLTComponent::GetPeriodNumber() const
2326 {
2327   // see header file for function documentation
2328   return (GetEventId()>>36)&0xfffffff;
2329 }
2330
2331 AliHLTUInt32_t    AliHLTComponent::GetOrbitNumber() const
2332 {
2333   // see header file for function documentation
2334   return (GetEventId()>>12)&0xffffff;
2335 }
2336
2337 AliHLTUInt16_t    AliHLTComponent::GetBunchCrossNumber() const
2338 {
2339   // see header file for function documentation
2340   return GetEventId()&0xfff;
2341 }
2342
2343 bool AliHLTComponent::IsDataEvent(AliHLTUInt32_t* pTgt) const
2344 {
2345   // see header file for function documentation
2346   if (pTgt) *pTgt=fEventType;
2347   return (fEventType==gkAliEventTypeData ||
2348           fEventType==gkAliEventTypeDataReplay ||
2349           fEventType==gkAliEventTypeCalibration);
2350 }
2351
2352 int AliHLTComponent::CopyStruct(void* pStruct, unsigned int iStructSize, unsigned int iBlockNo,
2353                                 const char* structname, const char* eventname)
2354 {
2355   // see header file for function documentation
2356   int iResult=0;
2357   if (pStruct!=NULL && iStructSize>sizeof(AliHLTUInt32_t)) {
2358     if (fpInputBlocks!=NULL && iBlockNo<fCurrentEventData.fBlockCnt) {
2359       AliHLTUInt32_t* pTgt=(AliHLTUInt32_t*)pStruct;
2360       if (fpInputBlocks[iBlockNo].fPtr && fpInputBlocks[iBlockNo].fSize) {
2361         AliHLTUInt32_t copy=*((AliHLTUInt32_t*)fpInputBlocks[iBlockNo].fPtr);
2362         if (fpInputBlocks[iBlockNo].fSize!=copy) {
2363           HLTWarning("%s event: mismatch of block size (%d) and structure size (%d)", eventname, fpInputBlocks[iBlockNo].fSize, copy);
2364           if (copy>fpInputBlocks[iBlockNo].fSize) copy=fpInputBlocks[iBlockNo].fSize;
2365         }
2366         if (copy!=iStructSize) {
2367           HLTWarning("%s event: mismatch in %s version (data type version %d)", eventname, structname, ALIHLT_DATA_TYPES_VERSION);
2368           if (copy>iStructSize) {
2369             copy=iStructSize;
2370           } else {
2371             memset(pTgt, 0, iStructSize);
2372           }
2373         }
2374         memcpy(pTgt, fpInputBlocks[iBlockNo].fPtr, copy);
2375         *pTgt=iStructSize;
2376         iResult=copy;
2377       } else {
2378         HLTWarning("%s event: missing data block", eventname);
2379       }
2380     } else {
2381       iResult=-ENODATA;
2382     }
2383   } else {
2384     HLTError("invalid struct");
2385     iResult=-EINVAL;
2386   }
2387   return iResult;
2388 }
2389
2390 AliHLTUInt32_t AliHLTComponent::CalculateChecksum(const AliHLTUInt8_t* buffer, int size)
2391 {
2392   // see header file for function documentation
2393   AliHLTUInt32_t  remainder = 0; 
2394   const AliHLTUInt8_t crcwidth=(8*sizeof(AliHLTUInt32_t));
2395   const AliHLTUInt32_t topbit=1 << (crcwidth-1);
2396   const AliHLTUInt32_t polynomial=0xD8;  /* 11011 followed by 0's */
2397
2398   // code from
2399   // http://www.netrino.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
2400
2401   /*
2402    * Perform modulo-2 division, a byte at a time.
2403    */
2404   for (int byte = 0; byte < size; ++byte)
2405     {
2406       /*
2407        * Bring the next byte into the remainder.
2408        */
2409       remainder ^= (buffer[byte] << (crcwidth - 8));
2410
2411       /*
2412        * Perform modulo-2 division, a bit at a time.
2413        */
2414       for (uint8_t bit = 8; bit > 0; --bit)
2415         {
2416           /*
2417            * Try to divide the current data bit.
2418            */
2419           if (remainder & topbit)
2420             {
2421               remainder = (remainder << 1) ^ polynomial;
2422             }
2423           else
2424             {
2425               remainder = (remainder << 1);
2426             }
2427         }
2428     }
2429
2430   /*
2431    * The final remainder is the CRC result.
2432    */
2433   return (remainder);
2434 }
2435
2436 int AliHLTComponent::ExtractComponentTableEntry(const AliHLTUInt8_t* pBuffer, AliHLTUInt32_t size,
2437                                                 string& retChainId, string& retCompId, string& retCompArgs,
2438                                                 vector<AliHLTUInt32_t>& parents)
2439 {
2440   // see header file for function documentation
2441   retChainId.clear();
2442   retCompId.clear();
2443   retCompArgs.clear();
2444   parents.clear();
2445   if (!pBuffer || size==0) return 0;
2446
2447   const AliHLTComponentTableEntry* pEntry=reinterpret_cast<const AliHLTComponentTableEntry*>(pBuffer);
2448   if (size<8/* the initial size of the structure*/ ||
2449       pEntry==NULL || pEntry->fStructSize<8) return -ENOMSG;
2450   const AliHLTUInt32_t* pParents=reinterpret_cast<const AliHLTUInt32_t*>(pEntry->fBuffer);
2451   const AliHLTUInt8_t* pEnd=pBuffer+size;
2452
2453   if (pParents+pEntry->fNofParents>=reinterpret_cast<const AliHLTUInt32_t*>(pEnd)) return -ENODEV;
2454   for (unsigned int i=0; i<pEntry->fNofParents; i++, pParents++) {
2455     parents.push_back(*pParents);
2456   }
2457
2458   const char* pDescription=reinterpret_cast<const char*>(pParents);
2459   if (pDescription+pEntry->fSizeDescription>=reinterpret_cast<const char*>(pEnd) ||
2460       *(pDescription+pEntry->fSizeDescription)!=0) {
2461     return -EBADF;
2462   }
2463
2464   TString descriptor=reinterpret_cast<const char*>(pDescription);
2465   TString chainId;
2466   TString compId;
2467   TString compArgs;
2468   TObjArray* pTokens=descriptor.Tokenize("{");
2469   if (pTokens) {
2470     int n=0;
2471     if (pTokens->GetEntriesFast()>n) {
2472       retChainId=((TObjString*)pTokens->At(n++))->GetString();
2473     }
2474     if (pTokens->GetEntriesFast()>n) {
2475       compId=((TObjString*)pTokens->At(n++))->GetString();
2476     }
2477     delete pTokens;
2478   }
2479   if (!compId.IsNull() && (pTokens=compId.Tokenize(":"))!=NULL) {
2480     int n=0;
2481     if (pTokens->GetEntriesFast()>n) {
2482       compId=((TObjString*)pTokens->At(n++))->GetString();
2483     }
2484     if (pTokens->GetEntriesFast()>n) {
2485       compArgs=((TObjString*)pTokens->At(n++))->GetString();
2486     }
2487     delete pTokens;
2488   }
2489   compId.ReplaceAll("}", "");
2490   compArgs.ReplaceAll("}", "");
2491
2492   retCompId=compId;
2493   retCompArgs=compArgs;
2494
2495   if (retChainId.size()==0) return -ENODATA;
2496
2497   return 1;
2498 }
2499
2500 int AliHLTComponent::ExtractTriggerData(
2501     const AliHLTComponentTriggerData& trigData,
2502     const AliHLTUInt8_t (**attributes)[gkAliHLTBlockDAttributeCount],
2503     AliHLTUInt64_t* status,
2504     const AliRawDataHeader** cdh,
2505     AliHLTReadoutList* readoutlist,
2506     bool printErrors
2507   )
2508 {
2509   // see header file for function documentation
2510   
2511   // Check that the trigger data structure is the correct size.
2512   if (trigData.fStructSize != sizeof(AliHLTComponentTriggerData))
2513   {
2514     if (printErrors)
2515     {
2516       AliHLTLogging log;
2517       log.LoggingVarargs(kHLTLogError, Class_Name(), FUNCTIONNAME(), __FILE__, __LINE__,
2518           "Invalid trigger structure size: %d but expected %d.", trigData.fStructSize, sizeof(AliHLTComponentTriggerData)
2519         );
2520     }
2521     return -ENOENT;
2522   }
2523   
2524   // Get the size of the AliHLTEventTriggerData structure without the readout list part.
2525   // The way we do this here should also handle memory alignment correctly.
2526   AliHLTEventTriggerData* dummy = NULL;
2527   size_t sizeWithoutReadout = (char*)(&dummy->fReadoutList) - (char*)(dummy);
2528   
2529   // Check that the trigger data pointer points to data of a size we can handle.
2530   // Either it is the size of AliHLTEventTriggerData or the size of the old
2531   // version of AliHLTEventTriggerData using AliHLTEventDDLV0.
2532   if (trigData.fDataSize != sizeof(AliHLTEventTriggerData) and
2533       trigData.fDataSize != sizeWithoutReadout + sizeof(AliHLTEventDDLV0)
2534      )
2535   {
2536     if (printErrors)
2537     {
2538       AliHLTLogging log;
2539       log.LoggingVarargs(kHLTLogError, Class_Name(), FUNCTIONNAME(), __FILE__, __LINE__,
2540           "Invalid trigger data size: %d but expected %d.", trigData.fDataSize, sizeof(AliHLTEventTriggerData)
2541         );
2542     }
2543     return -EBADF;
2544   }
2545   
2546   AliHLTEventTriggerData* evtData = reinterpret_cast<AliHLTEventTriggerData*>(trigData.fData);
2547   assert(evtData != NULL);
2548   
2549   // Check that the CDH has 8 words.
2550   if (cdh != NULL and evtData->fCommonHeaderWordCnt != 8)
2551   {
2552     if (printErrors)
2553     {
2554       AliHLTLogging log;
2555       log.LoggingVarargs(kHLTLogError, Class_Name(), FUNCTIONNAME(), __FILE__, __LINE__,
2556           "Common Data Header (CDH) has wrong number of data words: %d but expected %d",
2557           evtData->fCommonHeaderWordCnt, sizeof(AliRawDataHeader)/sizeof(AliHLTUInt32_t)
2558         );
2559     }
2560     return -EBADMSG;
2561   }
2562   
2563   // Check that the readout list has the correct count of words. i.e. something we can handle,
2564   if (readoutlist != NULL and
2565       evtData->fReadoutList.fCount != (unsigned)gkAliHLTDDLListSizeV0 and
2566       evtData->fReadoutList.fCount != (unsigned)gkAliHLTDDLListSizeV1
2567      )
2568   {
2569     if (printErrors)
2570     {
2571       AliHLTLogging log;
2572       log.LoggingVarargs(kHLTLogError, Class_Name(), FUNCTIONNAME(), __FILE__, __LINE__,
2573           "Readout list structure has wrong number of data words: %d but expected %d",
2574           evtData->fReadoutList.fCount, gkAliHLTDDLListSize
2575         );
2576     }
2577     return -EPROTO;
2578   }
2579   
2580   if (attributes != NULL)
2581   {
2582     *attributes = &evtData->fAttributes;
2583   }
2584   if (status != NULL)
2585   {
2586     *status = evtData->fHLTStatus;
2587   }
2588   if (cdh != NULL)
2589   {
2590     const AliRawDataHeader* cdhptr = reinterpret_cast<const AliRawDataHeader*>(&evtData->fCommonHeader);
2591     *cdh = cdhptr;
2592   }
2593   if (readoutlist != NULL)
2594   {
2595     *readoutlist = AliHLTReadoutList(evtData->fReadoutList);
2596   }
2597   return 0;
2598 }
2599
2600 int AliHLTComponent::LoggingVarargs(AliHLTComponentLogSeverity severity, 
2601                                     const char* originClass, const char* originFunc,
2602                                     const char* file, int line, ... ) const
2603 {
2604   // see header file for function documentation
2605   int iResult=0;
2606
2607   va_list args;
2608   va_start(args, line);
2609
2610   // logging function needs to be const in order to be called from const member functions
2611   // without problems. But at this point we face the problem with virtual members which
2612   // are not necessarily const.
2613   AliHLTComponent* nonconst=const_cast<AliHLTComponent*>(this);
2614   AliHLTLogging::SetLogString(this, ", %p", "%s (%s_pfmt_): ", 
2615                               fChainId[0]!=0?fChainId.c_str():nonconst->GetComponentID(),
2616                               nonconst->GetComponentID());
2617   iResult=SendMessage(severity, originClass, originFunc, file, line, AliHLTLogging::BuildLogString(NULL, args, true /*append*/));
2618   va_end(args);
2619
2620   return iResult;
2621 }
2622
2623 TUUID AliHLTComponent::GenerateGUID()
2624 {
2625   // Generates a globally unique identifier.
2626
2627   // Start by creating a new UUID. We cannot use the one automatically generated
2628   // by ROOT because the algorithm used will not guarantee unique IDs when generating
2629   // these UUIDs at a high rate in parallel.
2630   TUUID uuid;
2631   // We then use the generated UUID to form part of the random number seeds which
2632   // will be used to generate a proper random UUID. For good measure we use a MD5
2633   // hash also. Note that we want to use the TUUID class because it will combine the
2634   // host address information into the UUID. Using gSystem->GetHostByName() apparently
2635   // can cause problems on Windows machines with a firewall, because it always tries
2636   // to contact a DNS. The TUUID class handles this case appropriately.
2637   union
2638   {
2639     UChar_t buf[16];
2640     UShort_t word[8];
2641     UInt_t dword[4];
2642   };
2643   uuid.GetUUID(buf);
2644   TMD5 md5;
2645   md5.Update(buf, sizeof(buf));
2646   TMD5 md52 = md5;
2647   md5.Final(buf);
2648   dword[0] += gSystem->GetUid();
2649   dword[1] += gSystem->GetGid();
2650   dword[2] += gSystem->GetPid();
2651   for (int i = 0; i < 4; ++i)
2652   {
2653     gRandom->SetSeed(dword[i]);
2654     dword[i] = gRandom->Integer(0xFFFFFFFF);
2655   }
2656   md52.Update(buf, sizeof(buf));
2657   md52.Final(buf);
2658   // To keep to the standard we need to set the version and reserved bits.
2659   word[3] = (word[3] & 0x0FFF) | 0x4000;
2660   buf[8] = (buf[8] & 0x3F) | 0x80;
2661
2662   // Create the name of the new class and file.
2663   char uuidstr[64];
2664   sprintf(uuidstr, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
2665     dword[0], word[2], word[3], buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], buf[14], buf[15]
2666   );
2667
2668   uuid.SetUUID(uuidstr);
2669   return uuid;
2670 }
2671
2672 int AliHLTComponent::ScanECSParam(const char* ecsParam)
2673 {
2674   // see header file for function documentation
2675
2676   // format of the parameter string from ECS
2677   // <command>;<parameterkey>=<parametervalue>;<parameterkey>=<parametervalue>;...
2678   // search for a subset of the parameterkeys
2679   //   RUN_TYPE=
2680   //   RUN_NUMBER=
2681   //   HLT_IN_DDL_LIST=
2682   //   CTP_TRIGGER_CLASS=
2683   //   DATA_FORMAT_VERSION=
2684   //   BEAM_TYPE=
2685   //   HLT_OUT_DDL_LIST=
2686   //   HLT_TRIGGER_CODE=
2687   //   DETECTOR_LIST=
2688   //   HLT_MODE=
2689   // The command apears not to be sent by the online framework
2690   int iResult=0;
2691   TString string=ecsParam;
2692   TObjArray* parameter=string.Tokenize(";");
2693   if (parameter) {
2694     for (int i=0; i<parameter->GetEntriesFast(); i++) {
2695       TString entry=((TObjString*)parameter->At(i))->GetString();
2696       HLTDebug("scanning ECS entry: %s", entry.Data());
2697       TObjArray* entryParams=entry.Tokenize("=");
2698       if (entryParams) {
2699         if (entryParams->GetEntriesFast()>1) {
2700           if ((((TObjString*)entryParams->At(0))->GetString()).CompareTo("CTP_TRIGGER_CLASS")==0) {
2701             int result=InitCTPTriggerClasses((((TObjString*)entryParams->At(1))->GetString()).Data());
2702             if (iResult>=0 && result<0) iResult=result;
2703           } else {
2704             // TODO: scan the other parameters
2705             // e.g. consistency check of run number
2706           }
2707         }
2708         delete entryParams;
2709       }
2710     }
2711     delete parameter;
2712   }
2713
2714   return iResult;
2715 }
2716
2717 int AliHLTComponent::SetupCTPData()
2718 {
2719   // see header file for function documentation
2720   if (fpCTPData) delete fpCTPData;
2721   fpCTPData=new AliHLTCTPData;
2722   if (!fpCTPData) return -ENOMEM;
2723   return 0;
2724 }
2725
2726 int AliHLTComponent::InitCTPTriggerClasses(const char* ctpString)
2727 {
2728   // see header file for function documentation
2729   if (!fpCTPData) return 0; // silently accept as the component has to announce that it want's the CTP info
2730   return fpCTPData->InitCTPTriggerClasses(ctpString);
2731 }
2732
2733 bool AliHLTComponent::EvaluateCTPTriggerClass(const char* expression, AliHLTComponentTriggerData& trigData) const
2734 {
2735   // see header file for function documentation
2736   if (!fpCTPData) {
2737     static bool bWarningThrown=false;
2738     if (!bWarningThrown) HLTError("Trigger classes not initialized, use SetupCTPData from DoInit()");
2739     bWarningThrown=true;
2740     return false;
2741   }
2742
2743   return fpCTPData->EvaluateCTPTriggerClass(expression, trigData);
2744 }
2745
2746 int AliHLTComponent::CheckCTPTrigger(const char* name) const
2747 {
2748   // see header file for function documentation
2749   if (!fpCTPData) {
2750     static bool bWarningThrown=false;
2751     if (!bWarningThrown) HLTError("Trigger classes not initialized, use SetupCTPData from DoInit()");
2752     bWarningThrown=true;
2753     return false;
2754   }
2755
2756   return fpCTPData->CheckTrigger(name);
2757 }
2758
2759 Double_t AliHLTComponent::GetBz()
2760 {
2761   // Returns Bz.
2762   return AliHLTMisc::Instance().GetBz();
2763 }
2764
2765 Double_t AliHLTComponent::GetBz(const Double_t *r)
2766 {
2767   // Returns Bz (kG) at the point "r" .
2768   return AliHLTMisc::Instance().GetBz(r);
2769 }
2770
2771 void AliHLTComponent::GetBxByBz(const Double_t r[3], Double_t b[3])
2772 {
2773   // Returns Bx, By and Bz (kG) at the point "r" .
2774   AliHLTMisc::Instance().GetBxByBz(r, b);
2775 }