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