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