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